Ejemplo n.º 1
0
        /// <summary>
        /// Deserializes the saved users.
        /// </summary>
        private void DeserializeUsers()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(User), typeof(User).GetNestedTypes());

            string[] files = null;

            try
            {
                files = Directory.GetFiles(USERSFOLDER).Where(i => i.EndsWith("xml")).ToArray();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Fatal error while deserializing users: " + ex.Message);
                return;
            }

            foreach (var file in files)
            {
                try
                {
                    using (StreamReader reader = new StreamReader(file))
                    {
                        User usr = (User)serializer.Deserialize(reader);
                        AvailableUsers.Add(usr);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(string.Format("Error deserializing {0}: {1}", file, ex.Message));
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        ///     Periodically requests the client statuses for all shown users in the buffer.
        /// </summary>
        private void PeriodicallyRequestClientStatuses()
        {
            if (GameBase.Game.TimeRunning - LastStatusRequestTime < 15000)
            {
                return;
            }

            // Get all the users in the buffer.
            var userIds = new List <int>();

            for (var i = 0; i < UserBuffer.Count; i++)
            {
                var user = UserBuffer.ElementAt(i);

                if (user.User != null && AvailableUsers.Contains(user.User) && !userIds.Contains(user.User.OnlineUser.Id))
                {
                    userIds.Add(user.User.OnlineUser.Id);
                }
            }

            LastStatusRequestTime = GameBase.Game.TimeRunning;

            if (userIds.Count == 0)
            {
                return;
            }

            OnlineManager.Client?.RequestUserStatuses(userIds);
        }
 /// <summary>
 /// Deserializes the saved users.
 /// </summary>
 private void DeserializeUsers()
 {
     try
     {
         foreach (var file in _directoryOperator.GetFiles(USERSFOLDER).Where(i => i.EndsWith("xml")))
         {
             try
             {
                 User usr = _userSerializer.Deserialize(file);
                 // connect and disconnect to serialize if recent scrobbles are different
                 usr.RecentScrobblesChanged += User_RecentScrobblesChanged;
                 usr.UpdateRecentScrobbles();
                 usr.RecentScrobblesChanged -= User_RecentScrobblesChanged;
                 AvailableUsers.Add(usr);
             }
             catch (Exception ex)
             {
                 Debug.WriteLine(string.Format("Error deserializing {0}: {1}", file, ex.Message));
             }
         }
     }
     catch (Exception ex)
     {
         Debug.WriteLine("Fatal error while deserializing users: " + ex.Message);
         return;
     }
 }
Ejemplo n.º 4
0
        /// <summary>
        ///     Updates all the user info for the current buffer.
        /// </summary>
        public void UpdateUserInfo(User user)
        {
            lock (UserBuffer)
            {
                for (var i = 0; i < UserBuffer.Count; i++)
                {
                    var item = UserBuffer.ElementAt(i);

                    if (item.User == null || item.User.OnlineUser.Id != user.OnlineUser.Id)
                    {
                        continue;
                    }

                    item.UpdateUser(OnlineManager.OnlineUsers[user.OnlineUser.Id]);

                    var index = AvailableUsers.FindIndex(x => x.OnlineUser.Id == item.User.OnlineUser.Id);

                    if (index == -1)
                    {
                        continue;
                    }

                    AvailableUsers[index] = item.User;

                    SortUsers();
                    RecalculateContainerHeight();
                    UpdateBufferUsers();
                }
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        ///     Updates all of the current buffer users.
        /// </summary>
        public void UpdateBufferUsers()
        {
            for (var i = 0; i < UserBuffer.Count; i++)
            {
                var bufferObject = UserBuffer.ElementAt(i);

                // In the event that there aren't any available users left, we want to remove these unused
                // contained drawable objects.
                if (AvailableUsers.ElementAtOrDefault(PoolStartingIndex + i) == null)
                {
                    RemoveContainedDrawable(bufferObject);
                    UserBufferObjectsUsed--;
                    continue;
                }

                bufferObject.Y = (PoolStartingIndex + i) * DrawableOnlineUser.HEIGHT;
                bufferObject.UpdateUser(AvailableUsers[PoolStartingIndex + i]);

                // Make sure the object is contained if it isn't already.
                if (bufferObject.Parent != ContentContainer)
                {
                    AddContainedDrawable(bufferObject);
                }
            }
        }
Ejemplo n.º 6
0
 /// <summary>
 ///     Orders the available users in the list.
 /// </summary>
 private void SortUsers()
 {
     // ReSharper disable once ArrangeMethodOrOperatorBody
     AvailableUsers = AvailableUsers
                      .OrderBy(x => !x.HasUserInfo)
                      .ThenBy(x => x.OnlineUser.Username)
                      .ToList();
 }
Ejemplo n.º 7
0
        /// <summary>
        ///     Handles when a user disconnects from the server.
        /// </summary>
        public void HandleDisconnectingUser(int userId)
        {
            AvailableUsers.RemoveAll(x => x.OnlineUser.Id == userId);

            SortUsers();
            RecalculateContainerHeight();
            UpdateBufferUsers();
        }
Ejemplo n.º 8
0
        /// <summary>
        ///     Clears every single user in the list - used when successfully logging into the server.
        /// </summary>
        public void ClearAllUsers()
        {
            AvailableUsers.Clear();

            SortUsers();
            RecalculateContainerHeight();
            UpdateBufferUsers();
        }
Ejemplo n.º 9
0
        public void Initialize(Person connectedPerson)
        {
            // Reset all information
            ConnectedPerson = connectedPerson;
            AvailableUserTypes.Clear();
            AvailableUsers.Clear();
            AvailableClasses.Clear();
            AvailableParents.Clear();
            AvailableStudents.Clear();
            AvailableCourses.Clear();
            AvailableCoursesMustChoose.Clear();
            AvailableHomeroomClasses.Clear();

            if (HasRequiredPermissions)
            {
                _schoolData = new SchoolEntities();

                // Create a list of all the editable user types
                if (!CanEditManagement)
                {
                    AvailableUserTypes.AddRange(new List <string>()
                    {
                        Globals.USER_TYPE_STUDENT, Globals.USER_TYPE_TEACHERS, Globals.USER_TYPE_PARENTS
                    });
                }
                else
                {
                    AvailableUserTypes.AddRange(new List <string>()
                    {
                        Globals.USER_TYPE_STUDENT, Globals.USER_TYPE_TEACHERS, Globals.USER_TYPE_PARENTS,
                        Globals.USER_TYPE_SECRETARIES, Globals.USER_TYPE_PRINCIPAL
                    });
                }
                SelectedUserType = AvailableUserTypes[0];

                // Create a list of all the classes in the school
                _schoolData.Classes.ToList().ForEach(currClass => AvailableClasses.Add(currClass.classID, currClass.className));

                AvailableHomeroomClasses.Add(FIELD_NOT_SET, "לא מוגדר");
                _schoolData.Classes.Where(currClass => currClass.Teachers.Count() == 0).ToList()
                .ForEach(currClass => AvailableHomeroomClasses.Add(currClass.classID, currClass.className));

                // Create a list of all the parents in the school
                AvailableParents.Add(FIELD_NOT_SET, "לא מוגדר");
                _schoolData.Persons.Where(p => p.isParent).ToList()
                .ForEach(parent => AvailableParents.Add(parent.personID, parent.firstName + " " + parent.lastName));

                // Create a list of all the students in the school
                _schoolData.Persons.Where(p => p.isStudent).ToList()
                .ForEach(student => AvailableStudents.Add(student.personID, student.firstName + " " + student.lastName));

                // Create a list of all the courses in the school
                _schoolData.Courses.Where(course => course.isHomeroomTeacherOnly == false).ToList()
                .ForEach(course => AvailableCoursesMustChoose.Add(course.courseID, course.courseName));
                AvailableCourses.Add(FIELD_NOT_SET, "לא מוגדר");
                AvailableCoursesMustChoose.ToList().ForEach(course => AvailableCourses.Add(course.Key, course.Value));
            }
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Add a user to the list.
 /// </summary>
 public void AddUser()
 {
     if (_windowManager.ShowDialog(new LoginViewModel()).Value)
     {
         User usr = new User(MainViewModel.Client.Auth.UserSession.Username, MainViewModel.Client.Auth.UserSession.Token, MainViewModel.Client.Auth.UserSession.IsSubscriber);
         AvailableUsers.Add(usr);
         ActiveUser = usr;
         SerializeUsers();
     }
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Add a user to the list.
 /// </summary>
 public void AddUser()
 {
     if (_windowManager.ShowDialog(new LoginViewModel(_lastAuth, _windowManager.MessageBoxService)).Value)
     {
         User usr = new User(_lastAuth.UserSession.Username, _lastAuth.UserSession.Token, _lastAuth.UserSession.IsSubscriber);
         AvailableUsers.Add(usr);
         ActiveUser = usr;
         SerializeUsers();
     }
 }
Ejemplo n.º 12
0
 /// <summary>
 /// Loads the user that was last logged in.
 /// </summary>
 private void LoadLastUser()
 {
     if (!string.IsNullOrEmpty(Settings.Default.Username))
     {
         User usr = AvailableUsers.Where(i => i.Username == Settings.Default.Username).FirstOrDefault();
         if (usr != null)
         {
             LoginUser(usr);
         }
     }
 }
Ejemplo n.º 13
0
 /// <summary>
 /// Loads the user that was last logged in.
 /// </summary>
 public void LoadLastUser()
 {
     if (Settings.Default.Username != string.Empty)
     {
         User usr = AvailableUsers.Where(i => i.Username == Settings.Default.Username).FirstOrDefault();
         if (usr != null)
         {
             LoginUser(usr);
         }
     }
 }
        private void NewUserAvailable(UserViewModel user)
        {
            Guard.Against.Null(user, nameof(user));

            user.UserSelectedCommand = UserSelectedCommand;

            Device.BeginInvokeOnMainThread(() =>
            {
                AvailableUsers.Add(user);
                RaisePropertyChanged(nameof(UsersCount));
            });
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Allow choosing users that are from the specific selectedUserType
        /// </summary>
        /// <param name="selectedUserType">User type of available users. Expected values per const USER_TYPE_X fields</param>
        private void ChangeAvailableUsers(string selectedUserType)
        {
            // Clean the available users from the previous choice of user types
            AvailableUsers.Clear();

            // Create a query all the editable users in the school from the specified type
            IQueryable <Person> usersQuery;

            switch (selectedUserType)
            {
            case Globals.USER_TYPE_STUDENT:
            {
                usersQuery = _schoolData.Persons.Where(person => person.isStudent);
                break;
            }

            case Globals.USER_TYPE_PARENTS:
            {
                usersQuery = _schoolData.Persons.Where(person => person.isParent);
                break;
            }

            case Globals.USER_TYPE_TEACHERS:
            {
                usersQuery = _schoolData.Persons.Where(person => person.isTeacher);
                break;
            }

            case Globals.USER_TYPE_SECRETARIES:
            {
                usersQuery = _schoolData.Persons.Where(person => person.isSecretary);
                break;
            }

            case Globals.USER_TYPE_PRINCIPAL:
            {
                usersQuery = _schoolData.Persons.Where(person => person.isPrincipal);
                break;
            }

            default:
            {
                usersQuery = Enumerable.Empty <Person>().AsQueryable();
                break;
            }
            }

            // Create a list of all the editable users in the school
            usersQuery.Where(person => !person.User.isDisabled).ToList().
            ForEach(person => AvailableUsers.Add(person.personID, person.firstName + " " + person.lastName));
        }
Ejemplo n.º 16
0
        public bool IsExistUser(string login)
        {
            if (string.IsNullOrEmpty(login))
            {
                return(false);
            }

            if (CurrentUser.Login == login &&
                CurrentUser.IsTemporary())
            {
                return(true);
            }

            return(AvailableUsers.ContainsKey(login));
        }
        private void UpdateConnectedUser(List <UserViewModel> connectedUsers)
        {
            Guard.Against.Null(connectedUsers, nameof(connectedUsers));

            Device.BeginInvokeOnMainThread(() =>
            {
                IsProcessing = true;
                foreach (var user in connectedUsers)
                {
                    user.UserSelectedCommand = UserSelectedCommand;

                    AvailableUsers.Add(user);
                }
                RaisePropertyChanged(nameof(UsersCount));
                IsProcessing = false;
            });
        }
        private void UserNotAvailable(Guid userId)
        {
            Guard.Against.Default(userId, nameof(userId));

            var user = AvailableUsers.FirstOrDefault(x => x.UserId == userId);

            if (user is null)
            {
                return;
            }

            Device.BeginInvokeOnMainThread(() =>
            {
                AvailableUsers.Remove(user);
                RaisePropertyChanged(nameof(UsersCount));
            });
        }
        private void UpdateUnreadMessages(Guid userId)
        {
            Guard.Against.Default(userId, nameof(userId));

            var user = AvailableUsers.FirstOrDefault(x => x.UserId == userId);

            if (user is null || user.Equals(_selectedUser))
            {
                return;
            }

            Device.BeginInvokeOnMainThread(() =>
            {
                user.MessageCount++;
            });

            _audioPlayer.PlayNotificationSound();
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Removes the <see cref="SelectedUser"/> from the <see cref="AvailableUsers"/>
        /// and deleted its xml file.
        /// </summary>
        public void RemoveUser()
        {
            try
            {
                if (SelectedUser == ActiveUser)
                {
                    ActiveUser = null;
                }

                // remove xml file
                _fileOperator.Delete(Path.Combine(USERSFOLDER, SelectedUser.Username) + ".xml");
                AvailableUsers.Remove(SelectedUser);
            }
            catch (Exception ex)
            {
                _windowManager.MessageBoxService.ShowDialog("Could not remove user from list: " + ex.Message);
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Removes the <see cref="SelectedUser"/> from the <see cref="AvailableUsers"/>
        /// and deleted its xml file.
        /// </summary>
        public void RemoveUser()
        {
            try
            {
                if (SelectedUser == ActiveUser)
                {
                    ActiveUser = null;
                }

                // remove xml file
                File.Delete(USERSFOLDER + "\\" + SelectedUser.Username + ".xml");
                AvailableUsers.Remove(SelectedUser);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not remove user from list: " + ex.Message);
            }
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Deserializes the saved users.
 /// </summary>
 private void DeserializeUsers()
 {
     try
     {
         foreach (var file in _directoryOperator.GetFiles(USERSFOLDER).Where(i => i.EndsWith("xml")))
         {
             try
             {
                 User usr = _userSerializer.Deserialize(file);
                 AvailableUsers.Add(usr);
             }
             catch (Exception ex)
             {
                 Debug.WriteLine(string.Format("Error deserializing {0}: {1}", file, ex.Message));
             }
         }
     }
     catch (Exception ex)
     {
         Debug.WriteLine("Fatal error while deserializing users: " + ex.Message);
         return;
     }
 }
Ejemplo n.º 23
0
        /// <summary>
        ///     Handles shifting the pool whenever the container is scrolled.
        ///     Also initializing any new objects that need it.
        /// </summary>
        /// <param name="direction"></param>
        private void HandlePoolShifting(Direction direction)
        {
            switch (direction)
            {
            case Direction.Forward:
                // If there are no available users then there's no need to do anything.
                if (AvailableUsers.ElementAtOrDefault(PoolStartingIndex) == null ||
                    AvailableUsers.ElementAtOrDefault(PoolStartingIndex + MAX_USERS_SHOWN) == null)
                {
                    return;
                }

                var firstUser = UserBuffer.First();

                // Check if the object is in the rect of the ScrollContainer.
                // If it is, then there's no updating that needs to happen.
                if (!Rectangle.Intersect(firstUser.ScreenRectangle, ScreenRectangle).IsEmpty)
                {
                    return;
                }

                // Update the user's information and y position.
                firstUser.Y = (PoolStartingIndex + MAX_USERS_SHOWN) * DrawableOnlineUser.HEIGHT;

                lock (AvailableUsers)
                    firstUser.UpdateUser(AvailableUsers[PoolStartingIndex + MAX_USERS_SHOWN]);

                // Circuluarly Shift the list forward one.
                UserBuffer.RemoveFirst();
                UserBuffer.AddLast(firstUser);

                // Take this user, and place them at the bottom.
                PoolStartingIndex++;
                break;

            case Direction.Backward:
                // If there are no previous available user then there's no need to shift.
                if (AvailableUsers.ElementAtOrDefault(PoolStartingIndex - 1) == null)
                {
                    return;
                }

                var lastUser = UserBuffer.Last();

                // Check if the object is in the rect of the ScrollContainer.
                // If it is, then there's no updating that needs to happen.
                if (!Rectangle.Intersect(lastUser.ScreenRectangle, ScreenRectangle).IsEmpty)
                {
                    return;
                }

                lastUser.Y = (PoolStartingIndex - 1) * DrawableOnlineUser.HEIGHT;

                lock (AvailableUsers)
                    lastUser.UpdateUser(AvailableUsers[PoolStartingIndex - 1]);

                UserBuffer.RemoveLast();
                UserBuffer.AddFirst(lastUser);

                PoolStartingIndex--;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(direction), direction, null);
            }
        }
Ejemplo n.º 24
0
        private void OnApplicationStateChanged(ApplicationState applicationState)
        {
            if (applicationState == ApplicationState.DisconnectedFromServer)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    AvailableUsers.Clear();
                    AreConnectionSettingsVisible = true;
                    SelectedUser        = null;
                    IsUserListAvailable = false;
                });
            }

            if (applicationState == ApplicationState.ConnectedButNotLoggedIn)
            {
                AreConnectionSettingsVisible = false;

                session.RequestUserList(
                    userList =>
                {
                    Application.Current.Dispatcher.Invoke(async() =>
                    {
                        AvailableUsers.Clear();
                        userList.Do(userData => AvailableUsers.Add(userData));
                        IsUserListAvailable = true;

                        if (AvailableUsers.Count > 0)
                        {
                            SelectedUser = AvailableUsers.Any(user => user.Id == localSettingsRepository.LastLoggedInUserId)
                                                                                                        ? AvailableUsers.First(user => user.Id == localSettingsRepository.LastLoggedInUserId)
                                                                                                        : AvailableUsers.First();
                        }
                        else
                        {
                            var dialog = new UserDialogBox("",
                                                           "Es sind keine verfügbaren User vorhanden\n" +
                                                           "Die Verbindung wird getrennt!",
                                                           MessageBoxButton.OK);
                            await dialog.ShowMahAppsDialog();
                            Disconnect.Execute(null);
                        }
                    });
                },
                    errorMessage =>
                {
                    Application.Current.Dispatcher.Invoke(async() =>
                    {
                        var dialog = new UserDialogBox("",
                                                       "Die Userliste kann nicht vom Server abgefragt werden:\n" +
                                                       $">> {errorMessage} <<\n" +
                                                       "Die Verbindung wird getrennt - versuchen Sie es erneut",
                                                       MessageBoxButton.OK);
                        await dialog.ShowMahAppsDialog();
                        Disconnect.Execute(null);
                    });
                }
                    );
            }


            Application.Current.Dispatcher.Invoke(() =>
            {
                ((ParameterrizedCommand <PasswordBox>)Login).RaiseCanExecuteChanged();
                ((Command)Connect).RaiseCanExecuteChanged();
                ((Command)DebugConnect).RaiseCanExecuteChanged();
                ((Command)Disconnect).RaiseCanExecuteChanged();
            });
        }