Exemplo n.º 1
0
        public async Task <IActionResult> Edit(Guid id, [Bind("Email,PhoneNumber,Message,DateInvited,HasJoined,InvitorUserId,AppUserId,CreatedBy,CreatedAt,EditedBy,EditedAt,Id")] InvitedUser invitedUser)
        {
            if (id != invitedUser.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(invitedUser);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!InvitedUserExists(invitedUser.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["InvitorUserId"] = new SelectList(_context.Users, "Id", "FirstName", invitedUser.InvitorUserId);
            return(View(invitedUser));
        }
Exemplo n.º 2
0
        public Friend Create(string email, string firstName, string lastName, FriendProvider friendProvider)
        {
            // Validate if the user exists.
            IDictionary <string, object> propertyValues = new Dictionary <string, object>();

            propertyValues.Add("EmailAddress", email);
            BasicUser bu = basicUserRepository.FindOne(propertyValues);

            Friend f = new Friend();

            if (bu != null)
            {
                f.User = bu;
            }
            else
            {
                // If not, create as an invitation
                InvitedUser invited = new InvitedUser();
                invited.EmailAddress = email;
                invited.FirstName    = firstName;
                invited.LastName     = lastName;

                f.User = invited;
            }

            // Set Provider
            f.FriendProvider = friendProvider;
            return(f);
        }
Exemplo n.º 3
0
        public async Task <IActionResult> Create([Bind("Email,PhoneNumber,Message,DateInvited,HasJoined,InvitorUserId,AppUserId,CreatedBy,CreatedAt,EditedBy,EditedAt,Id")] InvitedUser invitedUser)
        {
            if (ModelState.IsValid)
            {
                invitedUser.Id = Guid.NewGuid();
                _context.Add(invitedUser);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["InvitorUserId"] = new SelectList(_context.Users, "Id", "FirstName", invitedUser.InvitorUserId);
            return(View(invitedUser));
        }
            public async Task <ValidateRegistrationResponse <ValidateRegistrationResult> > Handle(ValidateRegistrationCommand cmd, CancellationToken cancellationToken)
            {
                var mapper = new Mapper(_mapperConfiguration);

                InvitedUser invitedUser = await _mediator.Send(new GetUserInGatedRegistrationByEmailAddressQuery(cmd.EmailAddress));

                if (invitedUser != null)
                {
                    if (invitedUser.Invited)
                    {
                        if (invitedUser.Verify(cmd.EntryCode))
                        {
                            if (!invitedUser.Registered)
                            {
                                invitedUser.Register();
                                invitedUser.Log(true, 204, cmd.EntryCode);
                                return(await _mediator.Send(new UpdateUserInGatedRegistrationCommand(invitedUser, HttpStatusCode.NoContent, "User successfully registered")));
                            }
                            else
                            {
                                // user is in database and was invited and has already registered
                                // log entry attempt, return false
                                invitedUser.Log(false, 208, cmd.EntryCode);
                                return(await _mediator.Send(new UpdateUserInGatedRegistrationCommand(invitedUser, HttpStatusCode.AlreadyReported, "User has already registered")));
                            }
                        }
                        else
                        {
                            //user attempted to log in with invalid entry code
                            invitedUser.Log(false, 401, cmd.EntryCode);
                            return(await _mediator.Send(new UpdateUserInGatedRegistrationCommand(invitedUser, HttpStatusCode.Unauthorized, "User attempted to register with invalid entry code")));
                        }
                    }
                    else
                    {
                        // user is in database but is uninvited, capture email, log entry attempt, return false
                        invitedUser.Log(false, 302, cmd.EntryCode);
                        return(await _mediator.Send(new UpdateUserInGatedRegistrationCommand(invitedUser, HttpStatusCode.Found, "User is in database but is uninvited")));
                    }
                }
                else
                {
                    // add user to database as uninvited, capture email, log entry attempt return false
                    InvitedUser newUser = InvitedUser.Create(string.Empty, string.Empty, string.Empty, cmd.EmailAddress, string.Empty, string.Empty, "0F0F0F", false, false, DateTime.MinValue, new List <InvitedUserLogEntry>());
                    newUser.Log(false, 200, cmd.EntryCode);

                    return(await _mediator.Send(new AddUserToGatedRegistrationCommand(newUser, HttpStatusCode.OK, "User was added to database as uninvited")));
                }
            }
Exemplo n.º 5
0
        /// <summary>
        /// Save invited user
        /// </summary>
        /// <param name="invitedUser"></param>
        /// <returns></returns>
        public async Task <int> Save(InvitedUser invitedUser)
        {
            try
            {
                _context.InvitedUsers.Add(invitedUser);

                await _context.SaveChangesAsync();

                return(invitedUser.Id);
            }
            catch
            {
                throw;
            }
        }
Exemplo n.º 6
0
        public virtual void Rate(ClosetOutfit outfit, float ratingValue, InvitedUser f)
        {
            FriendRating fr = new FriendRating();

            fr.Friend       = f;
            fr.RatingValue  = ratingValue;
            fr.ClosetOutfit = outfit;
            this.friendRatings.Add(fr);
            float average = 0;

            foreach (FriendRating r in this.friendRatings)
            {
                average += (float)r.RatingValue;
            }
            average = average / this.friendRatings.Count;
            this.FriendRatingAverage = average;
        }
Exemplo n.º 7
0
        public string InviteUserToTeam(int teamId, string email)
        {
            var team = db.Teams.Find(teamId);

            bool isUserAlreadyInvited = team.InvitedUsers
                                        .Where(user => user.Email.ToLower() == email.ToLower()).
                                        Count() > 0;

            bool isUserAlreadyTeamMember = team.Users
                                           .Where(user => user.Email.ToLower() == email.ToLower())
                                           .Count() > 0;

            if (!isUserAlreadyInvited && !isUserAlreadyTeamMember)
            {
                var userCode = GenerateInvitationCode();

                var invitedUser = new InvitedUser()
                {
                    Email = email,
                    Code  = userCode,
                    TimeOfLastInvitation = DateTime.Now
                };

                team.InvitedUsers.Add(invitedUser);
                db.SaveChanges();

                string invitationLink = team.InvitationLink + invitedUser.Id.ToString();
                string emailMessage   = CreateInvitationEmailMessage(team.Name, invitationLink, userCode);

                SendInvitationEmail(email, emailMessage);

                return("");
            }

            if (isUserAlreadyInvited)
            {
                return("User with this email address is already invited to team.");
            }

            return("User with this email address is already in team.");
        }
Exemplo n.º 8
0
 public SendStudentInviteEmailCommand(InvitedUser user, string instructorName)
 {
     User           = user;
     InstructorName = instructorName;
 }
Exemplo n.º 9
0
        public bool RegisterMember(string email, string userName, string firstName, string lastName, string password,
                                   UserSize userSize, int membershipUserId, string zipCode,
                                   IList <UserFlavor> userFlavors, IList <EventType> eventTypes,
                                   IList <Garment> mygarments, IList <Garment> mywishlist,
                                   string validateUri, string channel,
                                   string invitationCode)
        {
            bool mustConfirmMail = true;

            try
            {
                IDictionary <string, object> propertyValues;
                bool invited = false;

                email    = email.ToLower().Trim();
                userName = userName.ToLower().Trim();

                basicUserRepository.DbContext.BeginTransaction();

                if (!string.IsNullOrEmpty(invitationCode))
                {
                    propertyValues = new Dictionary <string, object>();
                    propertyValues.Add("Code", invitationCode);
                    InvitationCode ic = invitationCodeRepository.FindOne(propertyValues);

                    if (!invitationValidatorService.IsValidCode(ic))
                    {
                        throw new InvalidInvitationCodeException();
                    }

                    mustConfirmMail = string.IsNullOrEmpty(ic.EmailAddress);
                    ic.MarkUsed();
                    invitationCodeRepository.SaveOrUpdate(ic);
                }

                RegisteredUser user = new RegisteredUser();
                user.UserName         = userName;
                user.FirstName        = firstName;
                user.LastName         = lastName;
                user.EmailAddress     = email.ToLower().Trim();
                user.Size             = userSize;
                user.PhoneNumber      = string.Empty;
                user.MembershipUserId = membershipUserId;
                user.RegistrationCode = Guid.NewGuid().ToString();  // Used for email verification purposes.
                user.ChangeZipCode(zipCode);
                user.SetFlavors(userFlavors);
                user.Channel = channel;

                if (eventTypes != null)
                {
                    foreach (EventType eventType in eventTypes)
                    {
                        user.AddEventType(eventType);
                    }
                }

                // Create Closet
                Closet closet = new Closet();
                closet.User         = user;
                closet.PrivacyLevel = PrivacyLevel.Private;
                closet.MarkAsProcessed();

                if (mygarments != null)
                {
                    foreach (Garment garment in mygarments)
                    {
                        closet.AddGarment(garment);
                    }
                }
                user.Closet = closet;

                // Check if the user does not exist with that mail
                propertyValues = new Dictionary <string, object>();
                propertyValues.Add("EmailAddress", email);
                BasicUser bu = basicUserRepository.FindOne(propertyValues);

                // HACK: We need to change the mail of the invited user to be able to add the new registered user.
                if (bu != null && bu is InvitedUser)
                {
                    InvitedUser iu = bu as InvitedUser;
                    iu.EmailAddressReplaced = iu.EmailAddress;
                    iu.EmailAddress        += new Random().Next().ToString();

                    basicUserRepository.SaveOrUpdate(iu);
                    basicUserRepository.DbContext.CommitTransaction();

                    basicUserRepository.DbContext.BeginTransaction();
                    closetRepository.SaveOrUpdate(closet);
                    basicUserRepository.SaveOrUpdate(user);

                    propertyValues = new Dictionary <string, object>();
                    propertyValues.Add("User", bu);
                    IList <Friend> lst = friendRepository.FindAll(propertyValues);
                    if (lst.Count > 0)
                    {
                        foreach (Friend f in lst)
                        {
                            Friend newFriend = new Friend();
                            newFriend.BasicUser = user;
                            newFriend.User      = f.BasicUser;
                            newFriend.Status    = FriendStatus.Pending;
                            friendRepository.SaveOrUpdate(newFriend);
                        }
                    }

                    invited = true;
                }
                else
                {
                    closetRepository.SaveOrUpdate(closet);
                    basicUserRepository.SaveOrUpdate(user);
                }

                // Create wishlist even if no items been selected for further use.
                WishList wl = new WishList();
                wl.User = user;

                // Save Wish List
                if (mywishlist != null && mywishlist.Count > 0)
                {
                    foreach (Garment wishlist in mywishlist)
                    {
                        wl.AddGarment(wishlist);
                    }
                }
                wishListRepository.SaveOrUpdate(wl);

                // Send Email Confirmation Mail
                if (mustConfirmMail)
                {
                    SendValidationCode(user, validateUri);
                }

                // Commit Transaction
                basicUserRepository.DbContext.CommitTransaction();

                new FashionAde.Utils.OutfitEngineService.OutfitEngineServiceClient().CreateOutfits(closet.Id);

                if (invited)
                {
                    basicUserRepository.MigrateInvited(bu as InvitedUser, user);
                }
            }
            catch
            {
                try { basicUserRepository.DbContext.RollbackTransaction(); }
                catch { }

                throw;
            }

            return(mustConfirmMail);
        }
Exemplo n.º 10
0
        public void MigrateInvited(InvitedUser user, RegisteredUser registeredUser)
        {
            IQuery q = NHibernateSession.Current.CreateSQLQuery("call uspMigrateInvitedUser(" + user.Id + "," + registeredUser.Id + ");");

            q.ExecuteUpdate();
        }
 public AddUserToGatedRegistrationCommand(InvitedUser user, HttpStatusCode code, string message)
 {
     User    = user;
     Code    = code;
     Message = message;
 }
Exemplo n.º 12
0
        public async Task <(CommandResult commandResult, Invite?invite)> GetInvite(string[] arguments, int numberOfPlayers, ulong?inviteRole = null, bool?isInviteRolePositive = null, bool removeFromList = true)
        {
            IAsyncEnumerable <UserInGuild> asyncList = guildData.GetSortedList().ToAsyncEnumerable();

            if (inviteRole is ulong roleId)
            {
                asyncList = asyncList.WhereAwait(async x =>
                {
                    var restGuildUser = await restClient.GetGuildUserAsync(guildId, x.UserId);

                    var hasRole = restGuildUser.RoleIds.Contains(roleId);

                    return(hasRole == isInviteRolePositive);
                });
            }

            var list = await asyncList.ToListAsync();

            if (list.Count < numberOfPlayers)
            {
                return(CommandResult.FromError($"Did not send invites. There are only {list.Count} players in the list."), null);
            }

            string message;

            try
            {
                message = string.Format(guildData.DMMessageFormat, arguments);
            }
            catch (Exception)
            {
                return(CommandResult.FromError("The arguments had the wrong format"), null);
            }

            var invite = new Invite
            {
                FormatData           = arguments,
                Guild                = guildData,
                InvitedUsers         = new List <InvitedUser>(),
                InviteTime           = DateTime.Now,
                NumberOfInvitedUsers = numberOfPlayers,
                InviteRole           = inviteRole,
                IsInviteRolePositive = isInviteRolePositive
            };

            dataContext.Invites.Add(invite);
            dataContext.SaveChanges();

            StringBuilder warnings = new StringBuilder();

            // Send invites
            for (int i = 0; i < numberOfPlayers; i++)
            {
                var player = list[i];

                player.IsInWaitingList = false;
                player.PlayCount++;

                dataContext.Update(player);
                dataContext.SaveChanges();

                var restGuildUser = await restClient.GetGuildUserAsync(guildId, player.UserId);

                try
                {
                    ComponentBuilder componentBuilder = new ComponentBuilder();
                    componentBuilder.WithButton("Yes", customId: $"joinYes;{invite.Id}");
                    componentBuilder.WithButton("No", customId: $"joinNo;{invite.Id}");


                    var userMessage = await restGuildUser.SendMessageAsync($"Are you ready to join? You have 1 minute to respond.", component : componentBuilder.Build());


                    InvitedUser invitedUser = new InvitedUser
                    {
                        Invite              = invite,
                        InviteTime          = DateTime.Now,
                        DmQuestionMessageId = userMessage.Id,
                        User = player
                    };

                    dataContext.InvitedUsers.Add(invitedUser);
                }
                catch (Exception ex)
                {
                    warnings.AppendLine($"Could not invite {restGuildUser?.Mention ?? player.Name}. Exception: {ex.Message}");
                }
            }

            this.dataContext.Update(invite);

            await this.dataContext.SaveChangesAsync();

            return(CommandResult.FromSuccess("Players have been invited." + (warnings.Length > 0 ? "\r\n" + warnings.ToString() : "")), invite);
        }