public ActionResult NextLesson()
        {
            String        time       = DateTime.Now.Hour + ":" + DateTime.Now.Minute;
            String        classNumer = PersonAccount.GetPupilFromAccountId().Class_Number;
            List <Lesson> lessons    = db.Lesson.Where(a => a.Class_Number.Equals(classNumer) && a.Day_Of_Week.Equals(3)).ToList();
            Lesson        ls         = lessons.Where(a => this.compareTimeStings(addMinutesToTime(time, 55), a)).ToList().ElementAtOrDefault(0);

            if (ls != null)
            {
                return(PartialView(ls));
            }
            int counter = 0;

            while (ls == null)
            {
                ls   = lessons.Where(a => this.compareTimeStings(time, a)).ToList().ElementAtOrDefault(0);
                time = addMinutesToTime(time, 45);
                counter++;
                if (counter > 100)
                {
                    return(PartialView(null));
                }
            }
            return(PartialView(ls));
        }
        public ActionResult TeacherNextLesson()
        {
            String        time       = DateTime.Now.Hour + ":" + DateTime.Now.Minute;
            int           employeeId = PersonAccount.GetEmployeeFromAccountId().Employee_Id;
            List <Lesson> lessons    = db.Lesson.Where(a => a.Employee_Id.Equals(employeeId) && a.Day_Of_Week.Equals(3)).ToList();
            Lesson        ls         = lessons.Where(a => this.compareTimeStings(addMinutesToTime(time, 55), a)).ToList().ElementAtOrDefault(0);

            if (ls != null)
            {
                return(PartialView(ls));
            }
            int counter = 0;

            while (ls == null)
            {
                ls   = lessons.Where(a => this.compareTimeStings(time, a)).ToList().ElementAtOrDefault(0);
                time = addMinutesToTime(time, 55);
                counter++;
                if (counter > 100)
                {
                    return(PartialView(null));
                }
            }
            return(PartialView(ls));
        }
Exemplo n.º 3
0
        // GET: Persons/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Person person = db.Persons.Find(id);

            if (person == null)
            {
                return(HttpNotFound());
            }
            else
            {
                var accounts = person.Accounts.ToList();

                var viewModel = new PersonAccount
                {
                    Person   = person,
                    Accounts = accounts
                };

                return(View(viewModel));
            }
            //return View(person);
        }
        public ActionResult TeacherLessonInDay()
        {
            Employee      teacher = PersonAccount.GetEmployeeFromAccountId();
            List <Lesson> lessons = teacher.Lesson.ToList();

            return(PartialView(lessons));
        }
        // GET: ParticalLesson
        public ActionResult LessonInDay()
        {
            String classNumer = PersonAccount.GetPupilFromAccountId().Class_Number;

            db.Lesson.Where(a => a.Class_Number.Equals(classNumer) && a.Day_Of_Week.Equals(3)).ToList(); //potem dowalić jeszcze w tym dniu
            return(PartialView(db.Lesson.Where(a => a.Class_Number.Equals(classNumer) && a.Day_Of_Week.Equals(3)).ToList()));
        }
Exemplo n.º 6
0
        public ActionResult DeleteConfirmed(string id)
        {
            PersonAccount personAccount = db.PersonAccounts.Find(id);

            db.PersonAccounts.Remove(personAccount);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
        // GET: ParticalEvents
        public ActionResult Index()
        {
            Pupil pupile = PersonAccount.GetPupilFromAccountId();

            Thread.CurrentThread.CurrentCulture = new CultureInfo("pl-PL");
            String type = PersonAccount.getInstance().AuthenticationType;

            return(PartialView(db.Event.ToList().Where(a => AccountGroupParserController.EventMatcher(a, type, pupile.Class_Number)).ToList()));
        }
Exemplo n.º 8
0
 public ActionResult Edit([Bind(Include = "id_number,account_number,surname,name")] PersonAccount personAccount)
 {
     if (ModelState.IsValid)
     {
         db.Entry(personAccount).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(personAccount));
 }
Exemplo n.º 9
0
 public ActionResult Index(String frm_login, String frm_password, String sel_type)
 {
     Thread.CurrentPrincipal = PersonAccount.getInstance();
     if (System.Web.HttpContext.Current != null)
     {
         System.Web.HttpContext.Current.User = PersonAccount.getInstance();;
     }
     ViewBag.hlp = new LoginHelper(db.Account.ToList(), frm_password, frm_login, sel_type);
     return(View(db.Account.ToList()));
 }
Exemplo n.º 10
0
        public ActionResult Create([Bind(Include = "id_number,account_number,surname,name")] PersonAccount personAccount)
        {
            if (ModelState.IsValid)
            {
                db.PersonAccounts.Add(personAccount);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(personAccount));
        }
Exemplo n.º 11
0
 public ActionResult LoginName()
 {
     using (MojDziennikEntities db = new MojDziennikEntities())
     {
         PersonAccount person = PersonAccount.getInstance();
         if (person.legalGuardianLog)
         {
             return(PartialView("_LoginPartial", db.Legal_Guardian.Where(a => a.Pupil.ToList().FirstOrDefault().Account_Id == person.accountId).ToList().FirstOrDefault()));
         }
         return(PartialView("_LoginPartial", Person.GetPerson()));
     }
 }
        //Adds in Database
        /// <summary>
        /// Adds in Database
        /// </summary>
        /// <param name="id"></param>
        public void Add(int id)
        {
            using (context)
            {
                PersonAccount UserAccountBookAdding = new PersonAccount()
                {
                    PersonBookTypesId = id
                };

                context.PersonAccounts.Add(UserAccountBookAdding);
                context.SaveChanges();
            }
        }
        public ActionResult CurrentLesson()
        {
            string        now        = DateTime.Now.Hour + ":" + DateTime.Now.Minute;
            String        classNumer = PersonAccount.GetPupilFromAccountId().Class_Number;
            List <Lesson> lessons    = db.Lesson.Where(a => a.Class_Number.Equals(classNumer) && a.Day_Of_Week.Equals(3)).ToList();

            var def = lessons.Where(a => this.compareTimeStings(now, a)).ToList().ElementAtOrDefault(0);

            if (def != null)
            {
                ParticalLessonController.currentLessonName = def.Subject.Subject_Name;
            }
            return(PartialView(lessons.Where(a => this.compareTimeStings(now, a)).ToList()));
        }
Exemplo n.º 14
0
        // GET: Persons/Delete/5
        public ActionResult Delete(string id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            PersonAccount personAccount = db.PersonAccounts.Find(id);

            if (personAccount == null)
            {
                return(HttpNotFound());
            }
            return(View(personAccount));
        }
        public ActionResult AddEvents([Bind(Include = "Event_Id,Employee_Id,Start_Time,Duration_In_Days,Describe,Account_Group")] Event @event)
        {
            @event.Employee_Id = db.Account.Find(PersonAccount.getInstance().accountId).Employee.ElementAtOrDefault(0).Employee_Id;
            LogManager.createlog("create", @event.ToString());
            if (ModelState.IsValid)
            {
                db.Event.Add(@event);
                db.SaveChanges();
                return(Redirect("/Home/AsTeacher"));
            }

            ViewBag.Employee_Id = new SelectList(db.Employee, "Employee_Id", "First_Name", @event.Employee_Id);
            return(View(@event));
        }
Exemplo n.º 16
0
        public static IPerson GetPerson()
        {
            MojDziennikEntities db = new MojDziennikEntities();

            switch (PersonAccount.getInstance().AuthenticationType)
            {
            case "Nauczyciel": return(PersonAccount.GetEmployeeFromAccountId());

            case "Uczen": return(PersonAccount.GetPupilFromAccountId());

            case "Opiekun": return(PersonAccount.GetLegal_GuardianFromAccountId());

            default: return(PersonAccount.GetEmployeeFromAccountId());
            }
        }
 public ActionResult AddNotes([Bind(Include = "Note_Id,Pupil_Id,Employee_Id,Note_Date,Positve,Describe")] Note note)
 {
     note.Employee_Id = db.Account.Find(PersonAccount.getInstance().accountId).Employee.ElementAt(0).Employee_Id;
     if (note.Note_Date == null)
     {
         note.Note_Date = DateTime.Now;
     }
     LogManager.createlog("create", note.ToString());
     if (ModelState.IsValid)
     {
         db.Note.Add(note);
         db.SaveChanges();
         return(Redirect("/Home/AsTeacher"));
     }
     return(View());
 }
Exemplo n.º 18
0
        public ActionResult Index(String message)
        {
            try {
                ViewBag.hlp = new LoginHelper(db.Account.ToList(), "", "", "Unknow");
            }
            catch (Exception e)
            {
                throw new Exception("Nie podłączono bazy danych");
            }
            if (message == "logout")
            {
                PersonAccount.getInstance().reset();
                Session.Clear();
            }

            return(View(db.Account.ToList()));
        }
Exemplo n.º 19
0
        public static List <PersonAccount> WithAccount(int amount = 10, int minAccountsPerPerson = 1, int maxAccountsPerPerson = 5)
        {
            if (amount <= 0)
            {
                throw new ArgumentOutOfRangeException("Must request at least one person with account.");
            }

            if (maxAccountsPerPerson < minAccountsPerPerson || minAccountsPerPerson < 0)
            {
                throw new ArgumentOutOfRangeException("min amount of accounts per person must be greater than zero and max amount must be greater than or equal to min amount.");
            }

            var crowd     = RandomData(amount, 0);
            var accounted = new List <PersonAccount>();
            var rng       = new Random();
            var refDate   = new DateTime(2011, 1, 1);
            var dateRange = (DateTime.Today - refDate).Days;

            int           i, accCount;
            PersonAccount account = null;

            foreach (var person in crowd)
            {
                accCount = rng.Next(maxAccountsPerPerson - minAccountsPerPerson + 1) + minAccountsPerPerson;
                account  = new PersonAccount()
                {
                    FirstName = person.FirstName,
                    LastName  = person.LastName,
                    Accounts  = new List <Account>()
                };

                for (i = 0; i <= accCount; i++)
                {
                    account.Accounts.Add(new Account()
                    {
                        Created    = refDate.AddDays(rng.Next(dateRange)),
                        AccountKey = randString(ref rng, 4)
                    });
                }

                accounted.Add(account);
            }

            return(accounted);
        }
Exemplo n.º 20
0
 public static PedestriansInfo SaveDtoToDb(PedestrianDTO pedestrianDTO)
 {
     using (DatabaseModel dbContext = new DatabaseModel())
     {
         PedestriansInfo existingInfo = dbContext.Set <PedestriansInfo>().First(i => i.PersonsInfo.PersonId == Guid.Parse(pedestrianDTO.Id));
         if (existingInfo != null)
         {
             return(existingInfo);
         }
         PersonAccount account = new PersonAccount
         {
             Id          = Guid.Parse(pedestrianDTO.Id),
             PhoneNumber = pedestrianDTO.PhoneNumber,
             SkypeNumber = pedestrianDTO.SkypeNumber
         };
         dbContext.Set <PersonAccount>().Attach(account);
         dbContext.Set <PersonAccount>().Add(account);
         PersonsInfo personInfo = new PersonsInfo
         {
             Altitude  = pedestrianDTO.Altitude,
             Longitude = pedestrianDTO.Longitude,
             Latitude  = pedestrianDTO.Latitude,
             CityId    = pedestrianDTO.CityId,
             PersonId  = account.Id
         };
         dbContext.Set <PersonsInfo>().Attach(personInfo);
         dbContext.Set <PersonsInfo>().Add(personInfo);
         PedestrianAccount pedestrianAccount = new PedestrianAccount
         {
             PersonId = account.Id
         };
         dbContext.Set <PedestrianAccount>().Attach(pedestrianAccount);
         dbContext.Set <PedestrianAccount>().Add(pedestrianAccount);
         PedestriansInfo pedestrianInfo = new PedestriansInfo
         {
             PersonInfo = personInfo.Id
         };
         dbContext.Set <PedestriansInfo>().Attach(pedestrianInfo);
         dbContext.Set <PedestriansInfo>().Add(pedestrianInfo);
         dbContext.SaveChanges();
         return(pedestrianInfo);
     }
 }
        public void CreatePersonAccount_Saves_In_Database()
        {
            var PersonAccount = new PersonAccount()
            {
                PersonBookTypesId = 1, PersonRegistersId = 1
            };

            var MockSet = new Mock <DbSet <PersonAccount> >();

            var MockContext = new Mock <ApplicationContexts>();

            MockContext.Setup(x => x.PersonAccounts).Returns(MockSet.Object);

            var service = new PersonAccountController(MockContext.Object);

            service.Add(PersonAccount.PersonBookTypesId);

            MockSet.Verify(x => x.Add(It.IsAny <PersonAccount>()), Times.Once());
            MockContext.Verify(x => x.SaveChanges(), Times.Once());
        }
        public ActionResult TeacherEvents()
        {
            events.Clear();
            Employee teacher = PersonAccount.GetEmployeeFromAccountId();

            foreach (var eve in db.Event.ToList())
            {
                ap.accountGroup = eve.Account_Group;
                ap.init();
                var    temp       = teacher.School_Class.ToList().ElementAtOrDefault(0);
                String classNumer = "";
                if (temp != null)
                {
                    classNumer = temp.Class_Number;
                }
                if (ap.exists(person.AuthenticationType, classNumer))
                {
                    events.Add(eve);
                }
            }
            return(PartialView("TeacherEvents", events));
        }
 public ActionResult AddMarks(int[] Id, String[] Value, String[] Weight, String[] Description, String Subject1)
 {
     if (Id == null && Subject1 == null)
     {
         sub = null;
     }
     if (Subject1 != null)
     {
         sub = Subject1;
     }
     Console.WriteLine();
     if (Id == null)
     {
         Id = new int[0];
     }
     for (int i = 0; i < Id.Length; i++)
     {
         if (sub != null && Value[i] != "" && Weight[i] != "")
         {
             Mark mark = new Mark();
             mark.Describe    = Description[i];
             mark.Value       = int.Parse(Value[i]);
             mark.Weight      = decimal.Parse(Weight[i].Replace('.', ','));
             mark.Pupil_Id    = Id[i];
             mark.Mark_Date   = DateTime.Now;
             mark.Employee_Id = PersonAccount.GetEmployeeFromAccountId().Employee_Id;
             mark.Subject_Id  = db.Subject.Where(a => a.Subject_Name.Equals(sub)).ToList().ElementAt(0).Subject_Id;
             db.Mark.Add(mark);
             db.SaveChanges();
             LogManager.createlog("create", mark.ToString());
         }
     }
     ViewBag.Class_Name = db.School_Class.ToList();
     ViewBag.Subjects   = db.Subject.Select(a => a.Subject_Name).ToList();
     return(View());
 }
Exemplo n.º 24
0
 public void Create(PersonAccount perAcc)
 {
     db.PersonAccounts.Add(perAcc);
     db.SaveChanges();
 }
Exemplo n.º 25
0
        static void Main(string[] args)
        {
            using (var dbContext = new NeoShopDbContextFactory().CreateDbContext(new string[] { }))
            {
                DbInitializer.Initialize(dbContext);
            }

            var alexGuid = Guid.NewGuid();

            using (var unitOfWork = UnitOfWorkFactory.Create())
            {
                var alexAccount = new PersonAccount()
                {
                    Id           = Guid.NewGuid(),
                    Login        = "******",
                    PasswordHash = "alex_PasswordHash",
                    PasswordSalt = "alex_Salt",
                };
                var alex = new Person()
                {
                    Id        = alexGuid,
                    FirstName = "Alex",
                    LastName  = "Popov",
                    BirthDate = DateTime.Parse("01.02.2001"),
                    Account   = alexAccount,
                };

                var maryAccount = new PersonAccount()
                {
                    Id           = Guid.NewGuid(),
                    Login        = "******",
                    PasswordHash = "mary_PasswordHash",
                    PasswordSalt = "mary_Salt",
                };
                var mary = new Person()
                {
                    Id        = Guid.NewGuid(),
                    FirstName = "Mary",
                    LastName  = "Isaeva",
                    BirthDate = DateTime.Parse("02.03.2002"),
                    Account   = maryAccount,
                };

                unitOfWork.Persons.Insert(alex);
                unitOfWork.Persons.Insert(mary);

                unitOfWork.SaveChanges();
            }

            using (var unitOfWork = UnitOfWorkFactory.Create())
            {
                Console.WriteLine("Persons:");
                foreach (var person in unitOfWork.Persons.GetAll())
                {
                    Console.WriteLine($"\n{person.FirstName} {person.LastName} {person.BirthDate.ToShortDateString()}");
                    Console.WriteLine($"{person.Account.Login} {person.Account.PasswordHash} {person.Account.PasswordSalt}");
                }
                Console.WriteLine($"\nAccounts: {unitOfWork.PersonAccounts.GetAll().Count()}");
            }

            using (var unitOfWork = UnitOfWorkFactory.Create())
            {
                Console.WriteLine("\nDeleting alex...");
                unitOfWork.Persons.Delete(alexGuid);
                unitOfWork.SaveChanges();
                Console.WriteLine($"Accounts: {unitOfWork.PersonAccounts.GetAll().Count()}");
            }

            using (var unitOfWork = UnitOfWorkFactory.Create())
            {
                var customerBobAccount = new PersonAccount()
                {
                    Id           = Guid.NewGuid(),
                    Login        = "******",
                    PasswordHash = "bob_ph",
                    PasswordSalt = "bob_ps",
                };
                var customerBob = new Customer()
                {
                    AccountNumber = "111",
                    BirthDate     = DateTime.Today,
                    FirstName     = "Bob",
                    LastName      = "McBob",
                    Account       = customerBobAccount,
                };

                unitOfWork.Customers.Insert(customerBob);
                unitOfWork.SaveChanges();

                unitOfWork.Customers.Delete(customerBob);
                unitOfWork.SaveChanges();
            }

            Console.WriteLine("\nPress Enter to exit.");
            Console.ReadLine();
        }
Exemplo n.º 26
0
        private static async void UpdateAvatar(PersonAccount person, Image image)
        {
            if (image.Dispatcher != System.Windows.Threading.Dispatcher.CurrentDispatcher)
            {
                await image.Dispatcher.InvokeAsync(() => UpdateAvatar(person, image));

                return;
            }

            if (!person.IsConnected)
            {
                image.Source = null;
                return;
            }

            var value = person.Picture;

            var path = value?.ToString();

            if (string.IsNullOrWhiteSpace(path))
            {
                var avatarCode = person.IsMale ? "m" : "f";

                var defaultImage = new BitmapImage();
                defaultImage.BeginInit();
                defaultImage.UriSource = new Uri($"pack://application:,,,/SIGame;component/Resources/avatar-{avatarCode}.png");
                defaultImage.EndInit();

                image.Source = defaultImage;
                return;
            }

            if (!Uri.TryCreate(path, UriKind.RelativeOrAbsolute, out Uri uri))
            {
                return;
            }

            if (!uri.IsAbsoluteUri)
            {
                return;
            }

            var isLocalFile = uri.Scheme == "file";

            if (isLocalFile && !File.Exists(uri.LocalPath))
            {
                return;
            }

            if (isLocalFile)
            {
                try
                {
                    var decoder = BitmapDecoder.Create(uri, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); // Лучше эти два параметра не трогать, так как в противном случае в некоторых ситуациях изображения могут перестать отображаться
                    if (decoder.Frames.Count == 0)
                    {
                        return;
                    }

                    var frame = decoder.Frames[0];
                    image.Source = frame.CanFreeze ? (BitmapSource)frame.GetAsFrozen() : frame;
                }
                catch
                {
                }

                return;
            }

            try
            {
                var stream = await Task.Run(() => LoadImage(uri));

                var decoder = BitmapDecoder.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.Default); // Лучше эти два параметра не трогать, так как в противном случае в некоторых ситуациях изображения могут перестать отображаться
                if (decoder.Frames.Count == 0)
                {
                    return;
                }

                var frame = decoder.Frames[0];
                image.Source = frame.CanFreeze ? (BitmapSource)frame.GetAsFrozen() : frame;
            }
            catch
            {
            }
        }
Exemplo n.º 27
0
 public static void createdeletelog(String item)
 {
     LogManager.SaveLog("delete" + ',' + DateTime.Now.Ticks + ',' + PersonAccount.getInstance().accountId + ',' + item);
 }
Exemplo n.º 28
0
        private string AddNewAccount(RegisterModel model)
        {
            string result = string.Empty;

            if (!WebSecurity.UserExists(model.UserName))
            {
                WebSecurity.CreateUserAndAccount(model.UserName, model.Password);

                if (model.View1Role)
                {
                    RoleAddToUser(RoleNames.view1Role, model.UserName);
                }

                if (model.View2Role)
                {
                    RoleAddToUser(RoleNames.view2Role, model.UserName);
                }

                if (model.View3Role)
                {
                    RoleAddToUser(RoleNames.view3Role, model.UserName);
                }

                if (model.EditRole)
                {
                    RoleAddToUser(RoleNames.editRole, model.UserName);
                }

                if (model.DeleteRole)
                {
                    RoleAddToUser(RoleNames.deleteRole, model.UserName);
                }

                if (model.AdminRole)
                {
                    RoleAddToUser(RoleNames.adminRole, model.UserName);
                }

                PersonAccount pa = new PersonAccount()
                {
                    UserId = WebSecurity.GetUserId(model.UserName),
                    Person = unitOfWork.PersonRepository.GetByID(model.PersonId)
                };

                unitOfWork.PersonAccountRepository.Insert(pa);
                unitOfWork.Save();
            }
            else
                result = "User này đã có trong cơ sở dữ liệu rồi.";

            return result;
        }
Exemplo n.º 29
0
        public string Update(int id, string value, int? rowId, int? columnPosition, int? columnId, string columnName)
        {
            switch (columnPosition)
            {
                case 0:
                    var ctx = new UsersContext();

                    var queryUser = ctx.UserProfiles.Where(m => m.UserName.Equals(value));
                    if (queryUser.FirstOrDefault() == null)
                    {
                        queryUser = ctx.UserProfiles.Where(m => m.UserId == id);
                        queryUser.FirstOrDefault().UserName = value;
                        ctx.SaveChanges();
                    }

                    break;

                case 1:
                    PersonAccount querypa = unitOfWork.PersonAccountRepository.Get(m => m.UserId == id).FirstOrDefault();
                    if (querypa != null)
                    {
                        querypa.Person = unitOfWork.PersonRepository.GetByID(Convert.ToInt32(value.Trim()));
                        querypa.ModifiedDate = System.DateTime.Now;
                        unitOfWork.Save();
                    }
                    else
                    {
                        PersonAccount personAccount = new PersonAccount()
                        {
                            UserId = id,
                            Person = unitOfWork.PersonRepository.GetByID(Convert.ToInt32(value.Trim()))
                        };

                        unitOfWork.PersonAccountRepository.Insert(personAccount);
                        unitOfWork.Save();
                    }

                    break;

                case 2:
                    ctx = new UsersContext();

                    if (value == "true")
                    {
                        if (Roles.FindUsersInRole(RoleNames.view1Role, ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName).FirstOrDefault() == null)
                        {
                            Roles.AddUserToRole(ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName, RoleNames.view1Role);
                        }
                    }

                    if (value == "false")
                    {
                        if (Roles.FindUsersInRole(RoleNames.view1Role, ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName).FirstOrDefault() != null)
                        {
                            Roles.RemoveUserFromRole(ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName, RoleNames.view1Role);
                        }
                    }

                    break;

                case 3:
                    ctx = new UsersContext();

                    if (value == "true")
                    {
                        if (Roles.FindUsersInRole(RoleNames.view2Role, ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName).FirstOrDefault() == null)
                        {
                            Roles.AddUserToRole(ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName, RoleNames.view2Role);
                        }
                    }

                    if (value == "false")
                    {
                        if (Roles.FindUsersInRole(RoleNames.view2Role, ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName).FirstOrDefault() != null)
                        {
                            Roles.RemoveUserFromRole(ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName, RoleNames.view2Role);
                        }
                    }

                    break;

                case 4:
                    ctx = new UsersContext();

                    if (value == "true")
                    {
                        if (Roles.FindUsersInRole(RoleNames.view3Role, ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName).FirstOrDefault() == null)
                        {
                            Roles.AddUserToRole(ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName, RoleNames.view3Role);
                        }
                    }

                    if (value == "false")
                    {
                        if (Roles.FindUsersInRole(RoleNames.view3Role, ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName).FirstOrDefault() != null)
                        {
                            Roles.RemoveUserFromRole(ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName, RoleNames.view3Role);
                        }
                    }

                    break;

                case 5:
                    ctx = new UsersContext();

                    if (value == "true")
                    {
                        if (Roles.FindUsersInRole(RoleNames.editRole, ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName).FirstOrDefault() == null)
                        {
                            Roles.AddUserToRole(ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName, RoleNames.editRole);
                        }
                    }

                    if (value == "false")
                    {
                        if (Roles.FindUsersInRole(RoleNames.editRole, ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName).FirstOrDefault() != null)
                        {
                            Roles.RemoveUserFromRole(ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName, RoleNames.editRole);
                        }
                    }

                    break;

                case 6:
                    ctx = new UsersContext();
                    if (value == "true")
                    {
                        if (Roles.FindUsersInRole(RoleNames.deleteRole, ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName).FirstOrDefault() == null)
                        {
                            Roles.AddUserToRole(ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName, RoleNames.deleteRole);
                        }
                    }

                    if (value == "false")
                    {
                        if (Roles.FindUsersInRole(RoleNames.deleteRole, ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName).FirstOrDefault() != null)
                        {
                            Roles.RemoveUserFromRole(ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName, RoleNames.deleteRole);
                        }
                    }

                    break;

                case 7:
                    ctx = new UsersContext();
                    if (value == "true")
                    {
                        if (Roles.FindUsersInRole(RoleNames.adminRole, ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName).FirstOrDefault() == null)
                        {
                            Roles.AddUserToRole(ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName, RoleNames.adminRole);
                        }
                    }

                    if (value == "false")
                    {
                        if (Roles.FindUsersInRole(RoleNames.adminRole, ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName).FirstOrDefault() != null)
                        {
                            Roles.RemoveUserFromRole(ctx.UserProfiles.Where(m => m.UserId == id).FirstOrDefault().UserName, RoleNames.adminRole);
                        }
                    }

                    break;

                default:
                    break;
            }

            return value;
        }
Exemplo n.º 30
0
 public static void SetImageSource(DependencyObject obj, PersonAccount value)
 {
     obj.SetValue(ImageSourceProperty, value);
 }
Exemplo n.º 31
0
        private static async void UpdateAvatar(PersonAccount person, Image image)
        {
            if (image.Dispatcher != System.Windows.Threading.Dispatcher.CurrentDispatcher)
            {
                await image.Dispatcher.InvokeAsync(() => UpdateAvatar(person, image));

                return;
            }

            if (!person.IsConnected)
            {
                image.Source = null;
                return;
            }

            var value = person.Picture;

            var path = value?.ToString();

            if (string.IsNullOrWhiteSpace(path))
            {
                var avatarCode = person.IsMale ? "m" : "f";

                var defaultImage = new BitmapImage();
                defaultImage.BeginInit();
                defaultImage.UriSource = new Uri($"pack://application:,,,/SIGame;component/Resources/avatar-{avatarCode}.png");
                defaultImage.EndInit();

                image.Source = defaultImage;
                return;
            }

            if (!Uri.TryCreate(path, UriKind.RelativeOrAbsolute, out Uri uri))
            {
                return;
            }

            if (!uri.IsAbsoluteUri)
            {
                return;
            }

            var isLocalFile = uri.Scheme == "file";

            if (isLocalFile && !File.Exists(uri.LocalPath))
            {
                return;
            }

            if (isLocalFile)
            {
                try
                {
                    var decoder = BitmapDecoder.Create(uri, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); // Лучше эти два параметра не трогать, так как в противном случае в некоторых ситуациях изображения могут перестать отображаться
                    if (decoder.Frames.Count == 0)
                    {
                        return;
                    }

                    var frame = decoder.Frames[0];
                    image.Source = frame.CanFreeze ? (BitmapSource)frame.GetAsFrozen() : frame;
                }
                catch
                {
                }

                return;
            }

            try
            {
                using var response = await HttpClient.GetAsync(uri);

                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception(await response.Content.ReadAsStringAsync());
                }

                using var stream = await response.Content.ReadAsStreamAsync();

                // It's better not to touch these options because their incorrect values could lead to images load errors
                var decoder = BitmapDecoder.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                if (decoder.Frames.Count == 0)
                {
                    return;
                }

                var frame = decoder.Frames[0];
                image.Source = frame.CanFreeze ? (BitmapSource)frame.GetAsFrozen() : frame;
            }
            catch (Exception exc)
            {
                Trace.TraceError($"Image {uri} load error: {exc}");
            }
        }
Exemplo n.º 32
0
 public void Update(PersonAccount perAcc)
 {
     db.Entry(perAcc).State = EntityState.Modified;
     db.SaveChanges();
 }