Пример #1
0
        /// <summary>
        /// Adds user and returns reference it. If the user already exists
        /// return the reference to the existing user instead.
        /// </summary>
        /// <param name="user"> The user. </param>
        /// <returns> Added User. </returns>
        public User Add(User user)
        {
            // Check if the collection contains the user.
            if (!_users.Values.Any(x => x.Id == user.Id && x.Name == user.Name && x.DateOfBirth == user.DateOfBirth))
            {
                int lastId = _users.Count == 0
                    ? 0
                    : _users.Keys.Max();

                user.Id = lastId + 1;

                _users.Add(user.Id, user);

                foreach (int awardId in UsersAwardsDao.GetByUserId(user.Id))
                {
                    user.Awards.Add(AwardDao._awards[awardId]);
                }

                ExportListToFile();

                return(user);
            }
            else
            {
                return(_users.Values.FirstOrDefault(x => x.Equals(user)));
            }
        }
Пример #2
0
        /// <summary>
        /// Initializes the dictionary of users.
        /// </summary>
        static UserDao()
        {
            // Check if containing users file exists.
            if (File.Exists(_usersFileName))
            {
                string temp = string.Empty;

                using (var sr = new StreamReader(_usersFileName))
                {
                    temp = sr.ReadToEnd();
                }
                _users = JsonConvert.DeserializeObject <Dictionary <int, User> >(temp);
                if (_users == null)
                {
                    _users = new Dictionary <int, User>();
                }
                else
                {
                    using (var sw = new StreamWriter(_usersFileName))
                    {
                        sw.WriteLine(JsonConvert.SerializeObject(_users));
                    }
                }
            }
            else
            {
                // Create new dictionary of users.
                _users = new Dictionary <int, User>();
            }
            // Add all users awards.
            foreach (var user in _users.Values)
            {
                foreach (int awardId in UsersAwardsDao.GetByUserId(user.Id))
                {
                    user.Awards.Add(AwardDao._awards[awardId]);
                }
            }
        }