Exemplo n.º 1
0
        public IActionResult Add(UserViewModelNPINotRequired pUser)
        {
            pUser.Type = ConstantsVar.Installer;
            User _user = lIUserRepository.getUser(pUser.UserId);
            //User _user2 = lIUserRepository.getUserNpi(pUser.Npi);
            User _userNew = UserExtension.UserViewModelToUserNPINotRequired(pUser);

            if ((_user == null))
            {
                _userNew.Phone = RemoveSpecialChars(_userNew.Phone);
                string _User = lIUserRepository.InsertUser(_userNew);
                if (_User == "Username already exists")
                {
                    TempData["Installer"] = JsonConvert.SerializeObject(_userNew);
                    TempData["msg"]       = "<script>Helpers.ShowMessage('User with same Installer Id is already registered, please use different one', 1);</script>";
                    pUser.UserId          = null;
                    return(View(pUser));
                }
            }
            else
            {
                if (_user.UserId == _userNew.UserId)
                {
                    TempData["Installer"] = JsonConvert.SerializeObject(_userNew);
                    TempData["msg"]       = "<script>Helpers.ShowMessage('User with same Installer Id is already registered, please use different one', 1);</script>";
                    pUser.UserId          = null;
                    return(View(pUser));
                }
            }
            return(RedirectToAction("Index"));
        }
Exemplo n.º 2
0
        public IActionResult Profile(UserViewModelNPINotRequired pUser)
        {
            pUser.Type = ConstantsVar.Installer;
            if (pUser != null && !string.IsNullOrEmpty(pUser.UserId))
            {
                User luser = lIUserRepository.getUser(pUser.UserId);
                if (luser != null)
                {
                    {
                        User _user = UserExtension.UserViewModelToUserNPINotRequired(pUser);
                        _user.Phone = RemoveSpecialChars(_user.Phone);
                        string _result = lIUserRepository.UpdateUser(_user);
                    }
                }

                else
                {
                    User _user = UserExtension.UserViewModelToUserNPINotRequired(pUser);
                    _user.Phone = RemoveSpecialChars(_user.Phone);
                    string _result = lIUserRepository.UpdateUser(_user);
                }
            }

            //string _result = lIUserRepository.UpdateUser(_user);
            if (HttpContext.Session.GetString("UserType") != null && HttpContext.Session.GetString("UserType").ToString() == ConstantsVar.Installer.ToString())
            {
                return(RedirectToAction("Profile", new { id = pUser.UserId }));
            }
            return(RedirectToAction("Index"));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Call when client Message is created. Logs all Messages to Database.
        /// </summary>
        /// <param name="e">The Message Event Args.</param>
        /// <returns>A <see cref="Task"/>.</returns>
        private async Task ClientMessageCreated(MessageCreateEventArgs e)
        {
            var context = new DiscordContext();

            if (context.Messages.Any(msg => msg.MessageId == Convert.ToInt64(e.Message.Id)))
            {
                return;
            }

            var user = await UserExtension.GetUser(e.Message.Author.Id, context);

            var cMsg = new Messages()
            {
                AuthorId     = Convert.ToInt64(user.UserId),
                MessageText  = e.Message.Content,
                ChannelId    = Convert.ToInt64(e.Message.Channel.Id),
                CreationDate = e.Message.CreationTimestamp.DateTime,
                MessageId    = Convert.ToInt64(e.Message.Id)
            };

            try
            {
                user = await UserExtension.GetUser(e.Message.Author.Id, context);

                await _context.Messages.AddAsync(cMsg);

                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error trying to enter Message into Database");
                Console.WriteLine(ex.Message);
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Invoked, when user logs into the master server
        /// </summary>
        /// <param name="session"></param>
        /// <param name="accountData"></param>
        private void OnLoggedIn(UserExtension user)
        {
            user.Peer.Disconnected += OnPeerPlayerDisconnected;

            // Create a profile
            ObservableServerProfile profile;

            if (profiles.ContainsKey(user.Username))
            {
                // There's a profile from before, which we can use
                profile            = profiles[user.Username];
                profile.ClientPeer = user.Peer;
            }
            else
            {
                // We need to create a new one
                profile = CreateProfile(user.Username, user.Peer);
                profiles.Add(user.Username, profile);
            }

            // Restore profile data from database (only if not a guest)
            if (!user.AccountData.IsGuest)
            {
                database.RestoreProfile(profile);
            }

            // Save profile property
            user.Peer.AddExtension(new ProfileExtension(profile, user.Peer));

            // Listen to profile events
            profile.ModifiedInServer += OnProfileChanged;
        }
        public IActionResult GetByID([FromBody] IdIntModel model)
        {
            if (model == null)
            {
                _logger.LogWarning($"ProfileTypeDefinitionController|GetByID|Invalid model (null)");
                return(BadRequest($"Invalid model (null)"));
            }

            var result = this.GetItem(model.ID);

            if (result == null)
            {
                _logger.LogWarning($"ProfileTypeDefinitionController|GetById|No records found matching this ID: {model.ID}");
                return(BadRequest($"No records found matching this ID: {model.ID}"));
            }

            //increment page visit count for this item
            var userToken = UserExtension.DalUserToken(User);
            var analytic  = _dalAnalytics.Where(x => x.ProfileTypeDefinitionId == model.ID, userToken, null, null, false).Data.FirstOrDefault();

            if (analytic == null)
            {
                _dalAnalytics.Add(new ProfileTypeDefinitionAnalyticModel()
                {
                    ProfileTypeDefinitionId = model.ID, PageVisitCount = 1
                }, userToken);
            }
            else
            {
                analytic.PageVisitCount += 1;
                _dalAnalytics.Update(analytic, null);
            }

            return(Ok(result));
        }
Exemplo n.º 6
0
        public IActionResult Profile(UserViewModel pUser)
        {
            pUser.Type = ConstantsVar.PatientAdministrator;
            User _user2 = lIUserRepository.getUserNpi(pUser.Npi);
            User _user  = UserExtension.UserViewModelToUser(pUser);

            _user.Phone = RemoveSpecialChars(_user.Phone);
            if (_user2 == null)
            {
                string _result = lIUserRepository.UpdateUser(_user);
            }
            else
            {
                TempData["PatientAdministrator"] = JsonConvert.SerializeObject(_user);
                TempData["msg"] = "<script>Helpers.ShowMessage('User with same Npi is already registered, please use different one', 1);</script>";
                pUser.Npi       = null;
                return(View(pUser));
            }
            //string _result = lIUserRepository.UpdateUser(_user);
            if (HttpContext.Session.GetString("UserType") != null && HttpContext.Session.GetString("UserType").ToString() == ConstantsVar.PatientAdministrator.ToString())
            {
                return(RedirectToAction("Profile", new { id = pUser.UserId }));
            }
            return(RedirectToAction("Index"));
        }
Exemplo n.º 7
0
        public IActionResult Profile(ProtocolView pProtocol)
        {
            Protocol _protocol = UserExtension.ProtocolViewToProtocol(pProtocol);
            string   _result   = lIProtocolInterface.UpdateProtocol(_protocol);

            return(RedirectToAction("Index", new { id = pProtocol.PatientId.Trim(), Username = HttpContext.Session.GetString("PatientName").ToString() }));
        }
Exemplo n.º 8
0
        public IActionResult Search([FromBody] PagerFilterSimpleModel model)
        {
            if (model == null)
            {
                return(BadRequest("User|Search|Invalid model"));
            }

            var userToken = UserExtension.DalUserToken(User);

            if (string.IsNullOrEmpty(model.Query))
            {
                return(Ok(_dal.GetAllPaged(userToken, model.Skip, model.Take, true)));
            }

            model.Query = model.Query.ToLower();
            var result = _dal.Where(s =>
                                    //string query section
                                    //s.IsActive &&
                                    (s.UserName.ToLower().Contains(model.Query) ||
                                     (s.FirstName.ToLower() + s.LastName.ToLower()).Contains(
                                         model.Query.Replace(" ", "").Replace("-", ""))), //in case they search for code and name in one string.
                                    userToken, model.Skip, model.Take, true);

            return(Ok(result));
        }
        public IActionResult GetLibrary([FromBody] ProfileTypeDefFilterModel model)
        {
            if (model == null)
            {
                _logger.LogWarning("ProfileTypeDefinitionController|GetLibrary|Invalid model");
                return(BadRequest("ProfileTypeDefinitionController|Library|Invalid model"));
            }
            var userToken = UserExtension.DalUserToken(User); // { UserId = User.GetUserID() };

            //search on some pre-determined fields
            var orderByExprs = _profileUtils.BuildSearchOrderByExpressions(User.GetUserID(), (SearchCriteriaSortByEnum)model.SortByEnum);
            var result       = _dal.Where(BuildPredicate(model, userToken), userToken, model.Skip, model.Take, true, false, orderByExprs.ToArray());

            //TBD - come back to this -
            //This is used when user clicks on View Type Defs for a single profile.
            //Add support to return list or profiles if the front end begins to support filtering by multiple profiles
            var profileCategory = model.Filters == null ? null : model.Filters.Find(c => c.ID.Value == (int)SearchCriteriaCategoryEnum.Profile);
            var profileFilters  = profileCategory == null ? null : profileCategory.Items.Where(x => x.Selected).Select(x => x.ID.Value).ToList();

            return(Ok(new ProfileTypeDefinitionSearchResult <ProfileTypeDefinitionModel>()
            {
                Count = result.Count,
                Data = result.Data,
                SummaryData = result.SummaryData,
                //return the profiles used in the filter -null, one or many
                Profiles = profileFilters == null ? null :
                           _dalProfile.Where(x => profileFilters.Contains(x.ID.Value), userToken).Data
            }));
        }
Exemplo n.º 10
0
        public async Task <IActionResult> Update([FromBody] UserModel model)
        {
            var userToken = UserExtension.DalUserToken(User);

            ValidateModel(model, userToken);

            if (!ModelState.IsValid)
            {
                return(Ok(new ResultMessageModel()
                {
                    IsSuccess = false,
                    Message = ExtractModelStateErrors().ToString()
                }));;
            }

            var result = await _dal.Update(model, userToken);

            if (result < 0)
            {
                _logger.LogWarning($"Could not update user. Invalid id:{model.ID}.");
                return(Ok(new ResultMessageModel()
                {
                    IsSuccess = false,
                    Message = "Could not update user. Invalid id."
                }));;
            }
            _logger.LogInformation($"Updated user. Id:{model.ID}.");

            //return success message object
            return(Ok(new ResultMessageModel()
            {
                IsSuccess = true, Message = "Item was updated."
            }));
        }
Exemplo n.º 11
0
        public IActionResult CopyUser([FromBody] IdIntModel model)
        {
            var userToken = UserExtension.DalUserToken(User);

            //get existing user, wipe out certain pieces of info, add new user
            //update new user's password,
            var result = _dal.GetById(model.ID, userToken);

            if (result == null)
            {
                //var errors = ExtractModelStateErrors();
                return(BadRequest("Original user not found."));
            }

            //keep permissions and organization same
            result.ID                   = null;
            result.Created              = DateTime.UtcNow;
            result.Email                = null;
            result.FirstName            = null;
            result.LastName             = null;
            result.UserName             = null;
            result.LastLogin            = null;
            result.RegistrationComplete = null;

            return(Ok(result));
        }
Exemplo n.º 12
0
        public async Task <IActionResult> Add([FromBody] UserModel model)
        {
            if (!ModelState.IsValid)
            {
                return(Ok(new ResultMessageModel()
                {
                    IsSuccess = false,
                    Message = ExtractModelStateErrors().ToString()
                }));;
            }
            var userToken = UserExtension.DalUserToken(User);

            var result = await _dal.Add(model, userToken);

            model.ID = result;
            if (result == 0)
            {
                _logger.LogWarning($"Could not add user: {model.FirstName} {model.LastName}.");
                return(Ok(new ResultMessageModel()
                {
                    IsSuccess = false,
                    Message = "Could not add user. "
                }));;
            }
            _logger.LogInformation($"Added user item. Id:{result}.");

            //return success message object
            return(Ok(new ResultMessageModel()
            {
                IsSuccess = true, Message = "Item was added."
            }));
        }
        public IActionResult GetProfileExplorer([FromBody] IdIntModel model)
        {
            if (model == null)
            {
                _logger.LogWarning($"ProfileTypeDefinitionController|GetProfileExplorer|Invalid model (null)");
                return(BadRequest($"Invalid model (null)"));
            }
            var userToken = UserExtension.DalUserToken(User);

            var profile = _dal.GetById(model.ID, userToken);

            if (profile == null)
            {
                _logger.LogWarning($"ProfileTypeDefinitionController|GetProfileExplorer|No records found matching this ID: {model.ID}");
                return(BadRequest($"No records found matching this ID: {model.ID}"));
            }

            //Build the explorer...
            var dependencies = _profileUtils.GenerateDependencies(profile, userToken);

            //Build the explorer inheritance tree...
            var treeview = _profileUtils.GenerateAncestoryTree(profile, userToken, true);

            // note interfaces, compositions already accounted for in profile object
            var result = new ProfileExplorerModel()
            {
                Profile      = profile,
                Dependencies = dependencies,
                Tree         = treeview
            };

            return(Ok(result));
        }
Exemplo n.º 14
0
        public async Task DisplayEdges(CommandContext ctx)
        {
            var user = await UserExtension.GetUser(Convert.ToInt64(Convert.ToInt64(ctx.Message.Author.Id)));

            await ctx.RespondAsync(
                $"Your Edge Balance is {user.WalletEdges} edges.");
        }
        public Task <ResultMessageWithDataModel> Export([FromBody] IdIntModel model, [FromServices] OpcUaImporter exporter)
        {
            var userToken   = UserExtension.DalUserToken(User);
            var profileItem = _dal.GetById(model.ID, userToken);

            if (profileItem == null /* || !(profileItem.AuthorId == null || profileItem.AuthorId == userToken)*/)
            {
                return(Task.FromResult(new ResultMessageWithDataModel()
                {
                    IsSuccess = false,
                    Message = $"Item {model?.ID} not found",
                }));
            }

            // Populate the OPC model into a new importer instance

            string xmlNodeSet = null;

            using (var xmlNodeSetStream = new MemoryStream())
            {
                if (exporter.ExportProfileItem(profileItem, xmlNodeSetStream, userToken, null))
                {
                    xmlNodeSet = Encoding.UTF8.GetString(xmlNodeSetStream.ToArray());

                    // TODO read and include the required models in a ZIP file, optionally?
                }
            }
            return(Task.FromResult(new ResultMessageWithDataModel()
            {
                IsSuccess = true,
                Message = "Type definition was exported.",
                Data = xmlNodeSet,
            }));
        }
Exemplo n.º 16
0
        public bool RevealUserFor(string requestingUser, string revealUser)
        {
            AffiliateUnlock lookup = GetUnlockedAffiliates(requestingUser).Where(u => u.RevealedUser == revealUser).FirstOrDefault();

            if (null == lookup)
            {
                AffiliateUnlock newUnlock = new AffiliateUnlock();
                newUnlock.PayingUser   = requestingUser;
                newUnlock.RevealedUser = revealUser;
                try
                {
                    UserExtension requestingUserDetails = Context.UserExtensions.Where(u => u.UserId == requestingUser).FirstOrDefault();
                    if (null == requestingUserDetails || requestingUserDetails.Credits == 0)
                    {
                        return(false);
                    }

                    AddUnlockedAffiliate(revealUser, requestingUser);
                    requestingUserDetails.Credits--;
                    Update();
                }
                catch
                {
                    return(false);
                }
            }

            return(true);
        }
Exemplo n.º 17
0
        public bool RevealProgramFor(string requestingUser, string revealProgram)
        {
            ProgramUnlock lookup = GetUnlockedPrograms(requestingUser).Where(u => u.ProgramName == revealProgram).FirstOrDefault();

            if (null == lookup)
            {
                ProgramUnlock newUnlock = new ProgramUnlock();
                newUnlock.PayingUser  = requestingUser;
                newUnlock.ProgramName = revealProgram;
                try
                {
                    UserExtension requestingUserDetails = Context.UserExtensions.Where(u => u.UserId == requestingUser).FirstOrDefault();
                    if (null == requestingUserDetails || requestingUserDetails.Credits == 0)
                    {
                        return(false);
                    }

                    AddUnlockedProgram(revealProgram, requestingUser);
                    requestingUserDetails.Credits--;
                    Update();
                }
                catch
                {
                    return(false);
                }
            }

            return(true);
        }
Exemplo n.º 18
0
        public IActionResult ValidateModel([FromBody] ProfileModel model)
        {
            if (model == null)
            {
                _logger.LogWarning($"ProfileController|ValidateModel|Invalid model (null)");
                return(BadRequest($"Invalid model (null). Check Publish Date formatting."));
            }
            var userToken = UserExtension.DalUserToken(User);

            //test for unique namespace/owner id/publish date combo
            if (!IsValidModel(model, userToken))
            {
                return(Ok(new ResultMessageWithDataModel()
                {
                    IsSuccess = false,
                    Message = "There is already a profile with this namespace and publish date combination. Enter a different namespace or publish date.",
                    Data = null
                }));
            }

            //if we get here, passed
            return(Ok(new ResultMessageWithDataModel()
            {
                IsSuccess = true,
                Message = "Valid",
                Data = null
            }));
        }
Exemplo n.º 19
0
        public async Task <IActionResult> DeleteMany([FromBody] List <IdIntModel> model)
        {
            var userToken = UserExtension.DalUserToken(User);

            //check that this user is author of all the items they are trying to delete
            var ids = model.Select(x => x.ID).ToList();

            //This also deletes all associated type defs, attributes, custom data types, compositions, interfaces
            //associated with this nodeset and its profiles
            try
            {
                var result = await _dal.DeleteMany(model.Select(x => x.ID).ToList(), userToken);

                if (result < 0)
                {
                    _logger.LogWarning($"ProfileController|DeleteMany|Could not delete item(s). Invalid model:{string.Join(", ", ids)}.");
                    return(BadRequest("Could not delete item(s). Invalid id(s)."));
                }
                else
                {
                    _logger.LogInformation($"ProfileController|Delete|Deleted nodeset item(s). Id:{string.Join(", ", model)}.");
                    //return success message object
                    return(Ok(new ResultMessageModel()
                    {
                        IsSuccess = true, Message = model.Count == 1 ? "Item was deleted." : $"{model.Count} Items were deleted."
                    }));
                }
            }
            catch (Exception ex)
            {
                _logger.LogCritical(ex, ex.Message);
                return(BadRequest("Could not delete item(s). Invalid id(s)."));
            }
        }
Exemplo n.º 20
0
        public void GetWorstSkill_Flow_Skill()
        {
            var skill = new Skill
            {
                Id = 1
            };

            var user = new User
            {
                UserSkills = new List <UserSkill>
                {
                    new UserSkill
                    {
                        Ratings = new List <Rating>
                        {
                            new Rating {
                                Mark = 8.0
                            }
                        },
                        Skill = skill
                    }
                }
            };

            var result = UserExtension.GetWorstSkill(user);

            Assert.AreEqual(skill, result);
        }
Exemplo n.º 21
0
 protected void LogIn(object sender, EventArgs e)
 {
     if (IsValid)
     {
         // Validate the user password
         var             manager = new UserManager();
         ApplicationUser user    = manager.Find(UserName.Text, Password.Text);
         if (user != null)
         {
             Session["userId"] = user.Id;
             ApplicationDbContext context = new ApplicationDbContext();
             var userMgr = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));
             IdentityHelper.SignIn(manager, user, RememberMe.Checked);
             if (UserExtension.IsInRole(user.Id, "Administrator"))
             {
                 Response.Redirect("~/Admin/AdminHome.aspx");
             }
             else if (UserExtension.IsInRole(user.Id, "Customer"))
             {
                 Response.Redirect("~/User/UserHome.aspx");
             }
         }
         else
         {
             FailureText.Text     = "Invalid username or password.";
             ErrorMessage.Visible = true;
         }
     }
 }
        public async Task <IActionResult> Delete([FromBody] IdIntModel model)
        {
            var userToken = UserExtension.DalUserToken(User);

            //return Ok(new ResultMessageModel() { IsSuccess = false, Message = "Under Construction." });
            //check for dependencies - if other profile types depend on this, it cannot be deleted.
            var item = GetItem(model.ID);

            if (item.Dependencies != null && item.Dependencies.Count > 0)
            {
                _logger.LogWarning($"ProfileTypeDefinitionController|Delete|Could not delete type definition because other type definitions depend on it. Id:{model.ID}.");
                return(Ok(new ResultMessageModel()
                {
                    IsSuccess = false, Message = "This item cannot be deleted because other type definitions depend on this item."
                }));
            }


            var result = await _dal.Delete(model.ID, userToken);

            if (result < 0)
            {
                _logger.LogWarning($"ProfileTypeDefinitionController|Delete|Could not delete profile type definition. Invalid id:{model.ID}.");
                return(BadRequest("Could not delete item. Invalid id."));
            }
            _logger.LogInformation($"ProfileTypeDefinitionController|Delete|Deleted profile type definition. Id:{model.ID}.");

            //return success message object
            return(Ok(new ResultMessageModel()
            {
                IsSuccess = true, Message = "Item was deleted."
            }));
        }
Exemplo n.º 23
0
        public BlackJackGame(int betEdges, CommandContext ctx)
        {
            _context  = new DiscordContext();
            this.user = UserExtension.GetUser(ctx.Message.Author.Id).GetAwaiter().GetResult();
            this.ctx  = ctx;

            // 2 Decks
            for (var i = 0; i < 2; i++)
            {
                // Iterate through each Card Variant
                foreach (Card.CardVariation variation in Enum.GetValues(typeof(Card.CardVariation)))
                {
                    foreach (Card.CardValue cardValue in Enum.GetValues(typeof(Card.CardValue)))
                    {
                        this.Deck.Add(new Card {
                            Variation = variation, Value = cardValue
                        });
                    }
                }
            }

            this.BetEdges = betEdges;
            for (var i = 0; i < 2; i++)
            {
                this.DrawCardHouse();
                this.DrawCardPlayer();
            }
        }
        public async Task AddRangeAsync()
        {
            var list = UserExtension.List();

            await _userRepository.AddRangeAsync(list);

            await _userRepository.SaveChangeAsync();
        }
        public async Task <IActionResult> ToggleFavorite([FromBody] IdIntModel model)
        {
            var userToken = UserExtension.DalUserToken(User);
            var item      = _dal.GetById(model.ID, userToken);

            item.IsFavorite = !item.IsFavorite;
            return(await UpdateInternal(item, false));
        }
Exemplo n.º 26
0
        protected virtual void OnUserLoggedOut(UserExtension account)
        {
            var chatExt = account.Peer.GetExtension <ChatUserExtension>();

            if (chatExt != null)
            {
                RemoveChatUser(chatExt);
            }
        }
        public IActionResult LookupFavorites()
        {
            var userToken = UserExtension.DalUserToken(User); // { UserId = User.GetUserID() };

            //search on some pre-determined fields
            var result = _dal.Where(x => x.Favorite != null && x.Favorite.IsFavorite, userToken, null, null, false, false);

            return(Ok(result));
        }
Exemplo n.º 28
0
        protected virtual void OnUserLoggedIn(UserExtension account)
        {
            var chatUser = CreateChatUser(account.Peer, account.Username);

            AddChatUser(chatUser);

            // Add the extension
            account.Peer.AddExtension(chatUser);
        }
        public IActionResult LookupProfileRelatedExtend([FromBody] IdIntModel model)
        {
            var userToken = UserExtension.DalUserToken(User);
            var parent    = _dal.GetById(model.ID, userToken);
            var result    = new ProfileLookupModel();

            result.Compositions = _profileUtils.BuildCompositionLookupExtend(parent, userToken);
            result.Interfaces   = _profileUtils.BuildInterfaceLookup(null, userToken);
            return(Ok(result));
        }
Exemplo n.º 30
0
        public IActionResult Add(ProtocolView pProtocol)
        {
            Protocol _protocol = UserExtension.ProtocolViewToProtocol(pProtocol);

            pProtocol.ProtocolId = Guid.NewGuid().ToString();
            pProtocol.Time       = DateTime.Now;
            string _User = lIProtocolInterface.InsertProtocol(_protocol);

            return(RedirectToAction("Index", new { id = pProtocol.PatientId.Trim(), Username = HttpContext.Session.GetString("PatientName").ToString() }));
        }
Exemplo n.º 31
0
        public async Task<IHttpActionResult> CreateUser(CreateUserBindingModel createUserModel)
        {

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            bool IsMarketer = false;
            if (null != createUserModel.Marketer && !bool.TryParse(createUserModel.Marketer, out IsMarketer))
            {
                return BadRequest();
            }

            bool IsAffiliate = false;
            if (null != createUserModel.Affiliate && !bool.TryParse(createUserModel.Affiliate, out IsAffiliate))
            {
                return BadRequest();
            }

            if (!IsMarketer && !IsAffiliate)
            {
                return BadRequest("Affiliate or Marketer must be selected");
            }

            if (IsAffiliate)
            {
                string error = ValidateCreateModel(createUserModel, Role.Affiliate);
                if (!String.IsNullOrEmpty(error))
                {
                    return BadRequest(ModelState);
                }
            }

            // check if the user created a program
            if (IsMarketer)
            {
                string error = ValidateCreateModel(createUserModel, Role.Vendor);
                if (!String.IsNullOrEmpty(error))
                {
                    return BadRequest(ModelState);
                }
            }

            var user = new ApplicationUser()
            {
                UserName = createUserModel.Username,
                Email = createUserModel.Email,
                FirstName = createUserModel.FirstName,
                LastName = createUserModel.LastName,
                Level = 3,
                JoinDate = DateTime.Now.Date
            };

            IdentityResult addUserResult = await this.AppUserManager.CreateAsync(user, createUserModel.Password);

            if (!addUserResult.Succeeded)
            {
                return GetErrorResult(addUserResult);
            }

            // extend the user with specific information
            var userExt = new UserExtension()
            {
                SkypeHandle = createUserModel.SkypeHandle,
                UserId = user.Id,
                IndividualDescription = createUserModel.IndividualDescription,
                FirstName = createUserModel.FirstName,
                LastName = createUserModel.LastName,
                PhoneNumber = createUserModel.PhoneNumber,
                Category = Convert.ToInt32(createUserModel.UserCategory)
            };

            UserExtManager.UserExtensions.Add(userExt);

            try
            {
                int resultCount = await UserExtManager.Update();
            }
            catch (Exception ex)
            {
                // todo delete user here
                try
                {
                    await AppUserManager.DeleteAsync(user);
                }
                catch
                {
                    // do our best to not create secondary errors
                }

                return InternalServerError();
            }

            // check if the user created a program
            if (IsMarketer)
            {
                AppUserManager.AddToRole(user.Id, "Vendor");

                Program newProgram = new Program()
                {
                    CreatedDate = DateTime.Now,
                    CreatorId = user.Id,
                    Description = createUserModel.ProgramDescription,
                    Url = createUserModel.ProgramUrl,
                    Name = createUserModel.ProgramName,
                    Category = Convert.ToInt32(createUserModel.ProgramCategory)
                };

                MarketManager.Programs.Add(newProgram);
                await MarketManager.Update();
            }

            if (IsAffiliate)
            {
                AppUserManager.AddToRole(user.Id, "Affiliate");
            }

            Uri locationHeader = await SendConfirm(user);

            return Created(locationHeader, TheModelFactory.Create(user, userExt));
        }
Exemplo n.º 32
0
 public AffiliateReturnModel CreateAffiliate(ApplicationUser appUser, UserExtension extension)
 {
     return new AffiliateReturnModel
     {
         Email = appUser.Email,
         FirstName = appUser.FirstName,
         LastName = appUser.LastName,
         PhoneNumber = appUser.PhoneNumber,
         Username = appUser.UserName,
         IndividualDescription = extension.IndividualDescription,
         SkypeHandle = extension.SkypeHandle
     };
 }
Exemplo n.º 33
0
 public ExtendedUserReturnModel Create(ApplicationUser appUser, UserExtension extension)
 {
     return new ExtendedUserReturnModel
     {
         Url = _UrlHelper.Link("GetUserById", new { id = appUser.Id }),
         Id = appUser.Id,
         UserName = appUser.UserName,
         FullName = string.Format("{0} {1}", extension.FirstName, extension.LastName),
         FirstName = extension.FirstName,
         LastName = extension.LastName,
         Email = appUser.Email,
         EmailConfirmed = appUser.EmailConfirmed,
         Level = appUser.Level,
         Credits = extension.Credits.ToString(),
         IndividualDescription = extension.IndividualDescription,
         PhoneNumber = extension.PhoneNumber,
         SkypeHandle = extension.SkypeHandle,
         JoinDate = appUser.JoinDate,
         Roles = _AppUserManager.GetRolesAsync(appUser.Id).Result,
         Claims = _AppUserManager.GetClaimsAsync(appUser.Id).Result
     };
 }