Exemple #1
0
 public UserLoginViewModel()
 {
     User     = new Models.User();
     DataUser = new DataAccessLayer.User();
     CheckUserAuthentication = new RelayCommand(UserAuthentication);
     userDataAccess          = new UserDataAccess();
 }
Exemple #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public DAL.User[] GetUsers(string[] phoneNumbers)
        {
            DAL.User sender = this.GetAuthenticatedUser();

            if (sender == null)
            {
                return(null);
            }

            List <string> normalizedPhoneNumbers = new List <string>();

            for (int i = 0; i < phoneNumbers.Length; i++)
            {
                string normalizedPhone = DAL.PhoneNumberUtils.ValidatePhoneNumber(phoneNumbers[i]);
                if (!string.IsNullOrEmpty(normalizedPhone))
                {
                    normalizedPhoneNumbers.Add(normalizedPhone);
                }
            }

            if (normalizedPhoneNumbers.Count == 0)
            {
                return(new List <DAL.User>().ToArray());
            }

            List <DAL.User> users = DAL.UserService.Instance.GetUsersFromPhones(normalizedPhoneNumbers);

            return(users.ToArray());
        }
Exemple #3
0
 protected UserCookie(User user, string deviceId, long expiryDate, string hash)
 {
     this.User = user;
     this.DeviceId = deviceId;
     this.ExpiryDate = expiryDate;
     this.SignedHash = hash ?? SecureSigningService.Instance.SignAuthCookieV1(this.CookieWithoutHash);
     this.AuthCookie = string.Format(UserCookie.CookieFormatString, UserCookie.CurrentCookieVersion, this.User.Id, this.DeviceId, this.ExpiryDate, this.SignedHash);
 }
Exemple #4
0
        public JsonResult <Models.User> GetUser(int id)
        {
            DataAccessLayer.User UserEntitiesUser = UserEntities.GetUsers(id);
            var Users = new Models.User();

            Models.User obj = Mapper.Map <DataAccessLayer.User, Models.User>(UserEntitiesUser);
            return(Json <Models.User>(obj));
        }
Exemple #5
0
        public void Save(User user)
        {
            if (string.IsNullOrEmpty(this.ExceptionString) ||
                string.IsNullOrEmpty(this.Version))
            {
                return;
            }

            DateTime time = DateTime.UtcNow;

            // Create and open the connection in a using block. This
            // ensures that all resources will be closed and disposed
            // when the code exits.
            using (SqlConnection connection = new SqlConnection(Globals.SqlConnectionString))
            {
                connection.Open();

                // Create or update the conversation object
                using (SqlTransaction sqlTransaction = connection.BeginTransaction())
                {
                    // Open the connection in a try/catch block.
                    // Create and execute the DataReader, writing the result
                    // set to the console window.
                    try
                    {
                        if (user.Id != this.UserId)
                        {
                            throw new Exception("Invalid exception details");
                        }

                        // Create the Command and Parameter objects.
                        SqlCommand command = new SqlCommand(ExceptionDetails.InsertExceptionCommandString, connection, sqlTransaction);
                        command.Parameters.AddWithValue("@userId", user.Id);
                        command.Parameters.AddWithValue("@exceptionString", this.ExceptionString.Count<char>() > 2000 ? this.ExceptionString.Substring(0, 2000) : this.ExceptionString);
                        command.Parameters.AddWithValue("@exceptionDate", this.ExceptionDate);
                        command.Parameters.AddWithValue("@version", this.Version);

                        SqlParameter outParameter = new SqlParameter("@Id", SqlDbType.Int);
                        outParameter.Direction = ParameterDirection.Output;
                        command.Parameters.Add(outParameter);

                        int identity = (int)(decimal)command.ExecuteScalar();

                        sqlTransaction.Commit();
                        this.Id = identity;
                    }
                    catch (Exception)
                    {
                        sqlTransaction.Rollback();
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
            }
        }
Exemple #6
0
        /// <summary>
        /// API to subscribe to push notifications
        /// </summary>
        /// <param name="deviceid"></param>
        /// <param name="subscriptionType"></param>
        /// <param name="subscriptionUrl"></param>
        public void SubscribeToNotification(string deviceid, DAL.SubscriptionType subscriptionType, string subscriptionUrl)
        {
            DAL.User user = this.GetAuthenticatedUser();

            if (user == null)
            {
                throw new Exception("User not authenticated");
            }

            DAL.Subscription subscription = DAL.Subscription.UpdateOrInsertSubscription(deviceid, subscriptionType, subscriptionUrl, user.Id);
        }
Exemple #7
0
        /// <summary>
        /// API to unsubscribe from notifications
        /// </summary>
        /// <param name="deviceid"></param>
        /// <param name="subscriptionType"></param>
        public void UnSubscribeToNotification(string deviceid, DAL.SubscriptionType subscriptionType)
        {
            DAL.User user = this.GetAuthenticatedUser();

            if (user == null)
            {
                throw new Exception("User not authenticated");
            }

            DAL.Subscription.Unsubscribe(deviceid, subscriptionType, user.Id);
        }
Exemple #8
0
        public List <DAL.Group> GetGroups()
        {
            DAL.User sender = this.GetAuthenticatedUser();

            if (sender == null)
            {
                return(null);
            }

            return(DAL.Group.GetGroupsForUser(sender.Id));
        }
Exemple #9
0
        public void UploadException(DAL.ExceptionDetails exception)
        {
            DAL.User user = this.GetAuthenticatedUser();

            if (user == null)
            {
                throw new Exception("User not authenticated");
            }

            exception.Save(user);
        }
Exemple #10
0
        /// <summary>
        /// API to get the list of messages from ids
        /// </summary>
        /// <param name="Array of message ids"></param>
        /// <returns>Array of messages.</returns>
        public MessageLayer.Message GetFullMessageForMessageId(Guid conversationId, Guid messageId)
        {
            DAL.User user = this.GetAuthenticatedUser();

            if (user == null)
            {
                throw new Exception("User not authenticated");
            }

            MessageLayer.Message message = MessageStore.MessageStore.Instance.GetMessage(conversationId, messageId);

            return(message);
        }
Exemple #11
0
        /// <summary>
        /// Update last sync time from the client.
        /// </summary>
        /// <param name="LastSyncDateTime"></param>
        public void  SetLastSyncDateTime(long clientticks)
        {
            DAL.User user = this.GetAuthenticatedUser();

            DateTime LastSyncDateTime = new DateTime(clientticks);

            if (user == null)
            {
                throw new Exception("User not authenticated");
            }

            DAL.UserService.UpdateUserLastSyncTime(user.Id, LastSyncDateTime);
        }
Exemple #12
0
        private void SendSmsWithConfirmationCode(DAL.User user)
        {
//            Task.Factory.StartNew(() =>
            {
                Authenticator.TOTP oneTimePasswordValidator = new Authenticator.TOTP(user.Secret, 30, 6);

                int code = oneTimePasswordValidator.Now();

                Authenticator.SmsSender sender = new Authenticator.SmsSender();

                sender.SendSMS(user.PhoneNumber, code);
            }//);
        }
Exemple #13
0
        protected override void AdjustContext()
        {
            base.AdjustContext();

            _userToCreate = new User
            {
                Id = 1,
                FirstName = "Created",
                LastName = "User",
                UserName = "******",
                Password = "******",
            };
        }
Exemple #14
0
        internal static bool AddGroupMember(User caller, Group group, User member)
        {
            if (group.Owner.Id != caller.Id)
            {
                return false;
            }

            // Create and open the connection in a using block. This
            // ensures that all resources will be closed and disposed
            // when the code exits.
            using (SqlConnection connection = new SqlConnection(Globals.SqlConnectionString))
            {
                connection.Open();
                using (SqlTransaction sqlTransaction = connection.BeginTransaction())
                {
                    // Open the connection in a try/catch block.
                    // Create and execute the DataReader, writing the result
                    // set to the console window.
                    try
                    {
                        using (SqlCommand command = new SqlCommand(Group.InsertGroupMemberCommand, connection, sqlTransaction))
                        {
                            command.Parameters.AddWithValue("@groupId", group.Id);
                            command.Parameters.AddWithValue("@userId", member.Id);

                            command.ExecuteNonQuery();

                            // Remove the user from cache so that
                            // the correct set of group will be loaded
                            // next time
                            UserService.Instance.RemoveUserFromCache(member);
                            UserService.Instance.RemoveUserFromCache(group);

                            sqlTransaction.Commit();

                            return true;
                        }
                    }
                    catch (Exception)
                    {
                        sqlTransaction.Rollback();
                    }
                    finally
                    {
                        connection.Close();
                    }

                    return false;
                }
            }
        }
Exemple #15
0
        public DAL.Group CreateGroup(DAL.Group newGroup)
        {
            DAL.User sender = this.GetAuthenticatedUser();

            if (newGroup.Members == null)
            {
                throw new Exception("Invalid member list");
            }

            Dictionary <int, DAL.User> uniqueUsers = new Dictionary <int, DAL.User>();

            for (int i = 0; i < newGroup.Members.Count; i++)
            {
                if (string.Compare(DAL.UserService.Instance.GetUserFromId(newGroup.Members[i].Id).PhoneNumber, newGroup.Members[i].PhoneNumber, StringComparison.OrdinalIgnoreCase) != 0)
                {
                    throw new Exception("Invalid user specified");
                }

                uniqueUsers.Add(newGroup.Members[i].Id, newGroup.Members[i]);
            }

            if (!uniqueUsers.ContainsKey(sender.Id))
            {
                uniqueUsers.Add(sender.Id, sender);
            }

            DAL.Group createdGroup = DAL.Group.CreateGroup(sender, newGroup.Name, uniqueUsers.Values.ToList());

            MessageLayer.Message newGroupMessage = new MessageLayer.Message()
            {
                SenderId = sender.Id, RecipientId = createdGroup.Id, MessageFlags = MessageLayer.MessageFlags.GroupCreatedMessage, TextMessage = sender.Name + " has created the group"
            };

            MessageStore.MessageStore.Instance.SaveMessage(sender, newGroupMessage);

            if (newGroupMessage.RecipientId != sender.Id)
            {
                this.SendPushNotifications(
                    DAL.Subscription.GetSubscriptions(newGroupMessage.RecipientId, sender),
                    newGroupMessage.MessageId,
                    newGroupMessage.ConversationId,
                    sender,
                    newGroupMessage.PostDateTimeUtcTicks,
                    newGroupMessage.TextMessage,
                    createdGroup,
                    newGroupMessage.IsEncrypted);
            }
            return(createdGroup);
        }
Exemple #16
0
        // Ideally do this in transactional behavior, however not important for this demo.
        public void Execute(int sourceUserId)
        {
            var sourceUser = _userRepository.Get(sourceUserId);

            // Ideally a copy constructor or a helper would do this. For now, keeping it here to make code readable.
            var copiedUser = new User
            {
                FirstName = sourceUser.FirstName,
                LastName = sourceUser.LastName,
                Id = sourceUser.Id + 1,
                UserName = sourceUser.UserName,
                Password = sourceUser.Password,
            };

            _userRepository.CreateUser(copiedUser);
        }
Exemple #17
0
 public PushNotification(
     List<Tuple<User, string>> urls,
     Guid messageId,
     Guid conversationId,
     User sender,
     long postDate,
     string message,
     Group group)
 {
     this.Urls = urls;
     this.MessageId = messageId;
     this.ConversationId = conversationId;
     this.Sender = sender;
     this.PostDate = postDate;
     this.MessageId = messageId;
     this.Message = message;
     this.Group = group;
 }
Exemple #18
0
 public ActionResult Create(DataAccessLayer.User user)
 {
     if (ModelState.IsValid)
     {
         user.CreateAt = DateTime.Now;
         user.IsAdmin  = false;
         user.Password = SecurityUtility.PasswordHash(user.Password);
         user.Status   = SystemStaticData.LookUpUserStatusId(SystemStaticData.UserDictionary.Normal);
         db.User.Add(user);
         db.SaveChanges();
         var account = new UserAccount {
             UserId = user.UserId
         };
         db.UserAccount.Add(account);
         db.SaveChanges();
     }
     return(RedirectToAction("UserList", "User"));
 }
Exemple #19
0
        /// <summary>
        /// API to get the list of messages in a conversation
        /// </summary>
        /// <param name="LastSyncDateTime"></param>
        /// <returns></returns>
        public MessageLayer.Message[] GetAllMessagesSincLastSync(DateTime LastSyncDateTime)
        {
            DAL.User user = this.GetAuthenticatedUser();

            if (user == null)
            {
                throw new Exception("User not authenticated");
            }

            List <MessageLayer.Message> messages = MessageStore.MessageStore.Instance.GetAllMessagesForUser(user, LastSyncDateTime);

            if (messages == null)
            {
                return(null);
            }
            else
            {
                return(messages.ToArray());
            }
        }
Exemple #20
0
 /// <summary>
 /// Method to post push notifications for windows phones
 /// </summary>
 /// <param name="urls"></param>
 /// <param name="messageId"></param>
 /// <param name="conversationId"></param>
 /// <param name="senderId"></param>
 /// <param name="postDate"></param>
 /// <param name="message"></param>
 /// <param name="sender"></param>
 private void SendPushNotifications(
     List <Tuple <DAL.User, string> > urls,
     Guid messageId,
     Guid conversationId,
     DAL.User sender,
     long postDate,
     string message,
     DAL.Group group,
     bool isEncrypted)
 {
     PushNotificationQueue.Instance.SchedulePush(
         new PushNotification(
             urls,
             messageId,
             conversationId,
             sender,
             postDate,
             isEncrypted ? "Message content is encrypted! Please open Yapper to view this message." : message,
             group));
 }
        protected override void AdjustContext()
        {
            base.AdjustContext();

            var randomGenerator= new Random();
            SourceUserId = randomGenerator.Next();
            var firstName = "FirstName" + randomGenerator.Next();
            var lastName = "LastName" + randomGenerator.Next();
            var userName = "******" + randomGenerator.Next();
            var password = "******" + randomGenerator.Next();

            var id = randomGenerator.Next();
            _sourceUser = new User
            {
                FirstName = firstName,
                LastName = lastName,
                UserName = userName,
                Password = password,
                Id = id,
            };
        }
Exemple #22
0
        public bool AddUserToGroup(int groupId, string userPhone)
        {
            DAL.User sender = this.GetAuthenticatedUser();

            DAL.Group group = (DAL.Group)DAL.UserService.Instance.GetUserFromId(groupId);

            DAL.User member = DAL.UserService.Instance.GetUserFromPhone(userPhone);

            bool success = DAL.Group.AddGroupMember(sender, group, member);

            if (!success)
            {
                return(false);
            }

            // Read the group again
            group = (DAL.Group)DAL.UserService.Instance.GetUserFromId(groupId);

            MessageLayer.Message newGroupMessage = new MessageLayer.Message()
            {
                SenderId = sender.Id, RecipientId = group.Id, MessageFlags = MessageLayer.MessageFlags.GroupJoinMessage, TextMessage = sender.Name + " has added " + member.Name + " to the group"
            };

            MessageStore.MessageStore.Instance.SaveMessage(sender, newGroupMessage);

            if (newGroupMessage.RecipientId != sender.Id)
            {
                this.SendPushNotifications(
                    DAL.Subscription.GetSubscriptions(newGroupMessage.RecipientId, sender),
                    newGroupMessage.MessageId,
                    newGroupMessage.ConversationId,
                    sender,
                    newGroupMessage.PostDateTimeUtcTicks,
                    newGroupMessage.TextMessage,
                    group,
                    newGroupMessage.IsEncrypted);
            }

            return(success);
        }
Exemple #23
0
        /// <summary>
        /// Validates the one-time password for the user
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <param name="cookie"></param>
        /// <returns></returns>
        public DAL.UserCookie ValidateUser(string phoneNumber, int oneTimePassword, string deviceId, string random)
        {
            string normalizedPhone = DAL.PhoneNumberUtils.ValidatePhoneNumber(phoneNumber);

            DAL.User existingUser = DAL.UserService.Instance.GetUserFromPhone(normalizedPhone);
            if (existingUser == null)
            {
                throw new Exception("User not registered");
            }

            Authenticator.TOTP oneTimePasswordValidator = new Authenticator.TOTP(existingUser.Secret, 30, 6);
            if (!oneTimePasswordValidator.Verify(oneTimePassword))
            {
                throw new Exception("Invalid one-time password");
            }

            DAL.UserService.Instance.UpdateDeviceId(existingUser, deviceId);

            DAL.UserCookie cookie = new DAL.UserCookie(existingUser, deviceId);

            return(cookie);
        }
Exemple #24
0
        /// <summary>
        /// Adds a new user.
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public DAL.UserCookie AddUser(string phoneNumber, string name, string deviceId)
        {
            string normalizedPhone = DAL.PhoneNumberUtils.ValidatePhoneNumber(phoneNumber);

            if (string.IsNullOrEmpty(normalizedPhone))
            {
                return(null);
            }

            DAL.User user = DAL.UserService.Instance.GetUserFromPhone(normalizedPhone);
            if (user == null)
            {
                user = DAL.UserService.Register(normalizedPhone, name);
            }
            else
            {
                DAL.UserService.Instance.UpdateName(user, name);
            }

            DateTime syncTime = DateTime.Now - new TimeSpan(7, 0, 0, 0);

            DataAccessLayer.UserService.UpdateUserLastSyncTime((int)user.Id, syncTime);

            if (DAL.PhoneNumberUtils.IsDebugPhoneNumber(normalizedPhone))
            {
                DAL.UserService.Instance.UpdateDeviceId(user, deviceId);

                DAL.UserCookie cookie = new DAL.UserCookie(user, deviceId);

                return(cookie);
            }

            this.SendSmsWithConfirmationCode(user);

            return(null);
        }
Exemple #25
0
        /// <summary>
        /// API to send a new message
        /// </summary>
        /// <param name="recipientPhoneNumber"></param>
        /// <param name="message"></param>
        /// <param name="UtcPostTime"></param>
        /// <returns></returns>
        public MessageLayer.Message SendMessage(MessageLayer.Message message)
        {
            Stopwatch watch               = new Stopwatch();
            long      authTime            = 0;
            long      messageCreationTime = 0;
            long      pushNotification    = 0;

            watch.Start();
            DAL.User sender = this.GetAuthenticatedUser();

            authTime = watch.ElapsedMilliseconds;

            if (sender == null)
            {
                throw new Exception("User not authenticated");
            }

            try
            {
                if (sender.Id != message.SenderId)
                {
                    throw new Exception("Invalid senderId");
                }

                if (sender.Id == message.RecipientId)
                {
                    throw new Exception("Invalid recipientId");
                }

                DAL.User recipient = DAL.UserService.Instance.GetUserFromId(message.RecipientId);
                if (recipient == null)
                {
                    throw new Exception("recipient not found");
                }

                if (!recipient.CanSendMessage(sender))
                {
                    throw new Exception("Cannot send message to recipient");
                }

                message.Recipient = recipient;

                MessageStore.MessageStore.Instance.SaveMessage(sender, message);
                messageCreationTime = watch.ElapsedMilliseconds - authTime;

                if (message != null)
                {
                    if (message.RecipientId != sender.Id)
                    {
                        this.SendPushNotifications(
                            DAL.Subscription.GetSubscriptions(message.RecipientId, sender),
                            message.MessageId,
                            message.ConversationId,
                            sender,
                            message.PostDateTimeUtcTicks,
                            message.TextMessage,
                            message.Recipient.UserType == DAL.UserType.Group ? (DAL.Group)message.Recipient : null,
                            message.IsEncrypted);

                        pushNotification = watch.ElapsedMilliseconds - messageCreationTime - authTime;
                    }
                }

                return(message);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
 partial void InsertUser(User instance);
Exemple #27
0
 protected override void Execute()
 {
     var userRespository = new UserRepository();
     Result = userRespository.Get(1);
 }
 partial void UpdateUser(User instance);
 /// <summary>
 /// Create a new User object.
 /// </summary>
 /// <param name="userId">Initial value of the UserId property.</param>
 /// <param name="contactInfoId">Initial value of the ContactInfoId property.</param>
 /// <param name="userName">Initial value of the UserName property.</param>
 public static User CreateUser(global::System.Int32 userId, global::System.Int32 contactInfoId, global::System.String userName)
 {
     User user = new User();
     user.UserId = userId;
     user.ContactInfoId = contactInfoId;
     user.UserName = userName;
     return user;
 }
Exemple #30
0
        private static void AddGroupMember(int identity, User member, SqlConnection connection, SqlTransaction transaction)
        {
            using (SqlCommand command = new SqlCommand(Group.InsertGroupMemberCommand, connection, transaction))
            {
                command.Parameters.AddWithValue("@groupId", identity);
                command.Parameters.AddWithValue("@userId", member.Id);

                command.ExecuteNonQuery();
            }
        }
Exemple #31
0
        internal override bool CanSendMessage(User sender)
        {
            foreach (User m in this.Members)
            {
                if (m.Id == sender.Id)
                {
                    return true;
                }
            }

            return false;
        }
Exemple #32
0
        public void UpdateName(User user, string name)
        {
            Stopwatch watch = new Stopwatch();
            long connectionTime = 0;
            long transctionTime = 0;
            long executionTime = 0;
            long commitTime = 0;

            watch.Start();
            using (SqlConnection connection = new SqlConnection(Globals.SqlConnectionString))
            {
                connection.Open();
                connectionTime = watch.ElapsedMilliseconds;
                watch.Restart();
                using (SqlTransaction sqlTransaction = connection.BeginTransaction())
                {
                    transctionTime = watch.ElapsedMilliseconds;
                    watch.Restart();

                    // Open the connection in a try/catch block.
                    // Create and execute the DataReader, writing the result
                    // set to the console window.
                    try
                    {
                        // Create the Command and Parameter objects.
                        using (SqlCommand command = new SqlCommand(UserService.UpdateUserNameCommandString, connection, sqlTransaction))
                        {
                            command.Parameters.AddWithValue("@name", name);
                            command.Parameters.AddWithValue("@userId", user.Id);
                            command.Parameters.AddWithValue("@userType", UserType.User);

                            int result = command.ExecuteNonQuery();

                            executionTime = watch.ElapsedMilliseconds;
                            watch.Restart();

                            if (result > 0)
                            {
                                user.Name = name;
                                sqlTransaction.Commit();
                            }
                            else
                            {
                                sqlTransaction.Rollback();
                            }

                            commitTime = watch.ElapsedMilliseconds;
                            watch.Restart();
                        }
                    }
                    catch (Exception)
                    {
                        sqlTransaction.Rollback();
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
            }
        }
Exemple #33
0
 protected UserCookie(User user, string deviceId, long expiryDate)
     : this(user, deviceId, expiryDate, null)
 {
 }
Exemple #34
0
 internal virtual bool CanSendMessage(User sender)
 {
     return true;
 }
 partial void DeleteUser(User instance);
Exemple #36
0
        /// <summary>
        /// Update public key of the user
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="publicKey"></param>
        public void UpdateUserPublicKey(DAL.User user)
        {
            DAL.User serverSideUser = DAL.UserService.Instance.GetUserFromId(user.Id);

            DAL.UserService.UpdateUserPublicKey(serverSideUser, user.PublicKey);
        }
Exemple #37
0
 public UserCookie(User user, string deviceId)
     : this(user, deviceId, DateTime.UtcNow.AddYears(1).Ticks)
 {
 }
Exemple #38
0
        /// <summary>
        /// Registers a new user
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <param name="name"></param>
        /// <remarks>
        /// Note that because the table is not locked and phonenumber is not the primary key,
        /// another instance of the webapp could register with the same phone number.
        /// </remarks>
        /// <returns>the registered user</returns>
        internal static Group CreateGroup(User creator, string name, List<User> users)
        {
            // Create and open the connection in a using block. This
            // ensures that all resources will be closed and disposed
            // when the code exits.
            using (SqlConnection connection = new SqlConnection(Globals.SqlConnectionString))
            {
                connection.Open();
                using (SqlTransaction sqlTransaction = connection.BeginTransaction())
                {
                    // Open the connection in a try/catch block.
                    // Create and execute the DataReader, writing the result
                    // set to the console window.
                    try
                    {
                        // Create the Command and Parameter objects.
                        using (SqlCommand command = new SqlCommand(Group.InsertGroupCommand, connection, sqlTransaction))
                        {
                            // Create group
                            command.Parameters.AddWithValue("@name", name);
                            command.Parameters.AddWithValue("@phoneNumber", "NoPhone");
                            command.Parameters.AddWithValue("@userType", UserType.Group);
                            command.Parameters.AddWithValue("@groupOwner", creator.Id);

                            SqlParameter outParameter = new SqlParameter("@UserId", SqlDbType.Int);
                            outParameter.Direction = ParameterDirection.Output;
                            command.Parameters.Add(outParameter);

                            int identity = (int)(decimal)command.ExecuteScalar();

                            // Add members
                            for (int i = 0; i < users.Count; i++)
                            {
                                Group.AddGroupMember(identity, users[i], connection, sqlTransaction);
                            }

                            // For each user in the cache, update the list of groups in the user object
                            for (int i = 0; i < users.Count; i++)
                            {
                                // Remove the user from cache so that
                                // the correct set of group will be loaded
                                // next time
                                UserService.Instance.RemoveUserFromCache(users[i]);
                            }

                            sqlTransaction.Commit();

                            return new Group(identity, name, creator, users);
                        }
                    }
                    catch (Exception)
                    {
                        sqlTransaction.Rollback();
                    }
                    finally
                    {
                        connection.Close();
                    }

                    return null;
                }
            }
        }
Exemple #39
0
 public Group(int id, string name, User groupOwner)
     : this(id, name, groupOwner, Group.GetMembers(id))
 {
 }
Exemple #40
0
        internal static void UpdateUserPublicKey(User user, byte[] publicKey)
        {
            using (SqlConnection connection = new SqlConnection(Globals.SqlConnectionString))
            {
                connection.Open();
                using (SqlTransaction sqlTransaction = connection.BeginTransaction())
                {
                    // Open the connection in a try/catch block.
                    // Create and execute the DataReader, writing the result
                    // set to the console window.
                    try
                    {
                        // Create the Command and Parameter objects.
                        using (SqlCommand command = new SqlCommand(UserService.UpdateUserPublicKeyCommand, connection, sqlTransaction))
                        {
                            command.Parameters.AddWithValue("@userId", user.Id);
                            command.Parameters.AddWithValue("@publicKey", publicKey);

                            int result = command.ExecuteNonQuery();

                            if (result > 0)
                            {
                                sqlTransaction.Commit();
                            }
                            else
                            {
                                sqlTransaction.Rollback();
                            }
                        }

                        user.PublicKey = publicKey;
                    }
                    catch (Exception)
                    {
                        sqlTransaction.Rollback();
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
            }
        }
Exemple #41
0
 public Group(int id, string name, User groupOwner, List<User> users)
     : base(id, string.Empty, name, string.Empty)
 {
     this.Members = users;
     this.Owner = groupOwner;
 }
 protected override void Execute()
 {
     var command = new DuplicateUserCommand(UserRepository.Object);
     command.Execute(SourceUserId);
     Result = UserRepository.Object.Get(SourceUserId + 1);
 }
Exemple #43
0
 public void RemoveUserFromCache(User user)
 {
     this.RemoveUserFromCache(user.Id);
 }
Exemple #44
0
        /// <summary>
        /// Search for the phone based on the phone number
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <returns></returns>
        internal static List<Tuple<User, string>> GetSubscriptionsForUsers(List<User> users, User sender)
        {
            List<Tuple<User, string>> urls = new List<Tuple<User, string>>();

            for (int i = 0; i < users.Count; i++)
            {
                if (users[i].SubscriptionUrls != null)
                {
                    for (int subs = 0; subs < users[i].SubscriptionUrls.Count; subs++)
                    {
                        if (sender.Id != users[i].Id)
                        {
                            urls.Add(new Tuple<User, string>(users[i], users[i].SubscriptionUrls[subs]));
                        }
                    }
                }
            }

            return urls;
        }
Exemple #45
0
        /// <summary>
        /// Search for the phone based on the phone number
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <returns></returns>
        internal static List<Tuple<User, string>> GetSubscriptions(int recipientId, User sender)
        {
            User recipient = UserService.Instance.GetUserFromId(recipientId);
            List<Tuple<User, string>> urls = new List<Tuple<User, string>>();

            if (recipient.UserType == UserType.User)
            {
                if (recipient.SubscriptionUrls != null)
                {
                    for (int i = 0; i < recipient.SubscriptionUrls.Count; i++)
                    {
                        urls.Add(new Tuple<User, string>(recipient, recipient.SubscriptionUrls[i]));
                    }

                    return urls;
                }
            }

            if (recipient.UserType == UserType.Group)
            {
                Group group = (Group)recipient;

                return Subscription.GetSubscriptionsForUsers(group.Members, sender);
            }

            return null;
        }
 /// <summary>
 /// Deprecated Method for adding a new object to the Users EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.
 /// </summary>
 public void AddToUsers(User user)
 {
     base.AddObject("Users", user);
 }