Exemple #1
0
        //Post call for userinformation save
        public async Task <string> APIPostCall(string endpointUri, PersonalizationRequsetDTO data)
        {
            UserProfileController userProfileObj = new UserProfileController();
            var result = string.Empty;

            try
            {
                //create object of client request
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
                    client.DefaultRequestHeaders.Add("ContentType", "application/json;odata=verbose");
                    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + await userProfileObj.GetTokenForApplication());
                    HttpResponseMessage responseMessage = await client.PutAsJsonAsync(endpointUri, data);

                    if ((HttpStatusCode.OK).ToString().Equals(responseMessage.ReasonPhrase))
                    {
                        result = responseMessage.ReasonPhrase.ToString();; //"Data has been successfully saved";
                    }
                    else
                    {
                        result = SettingsHelper.ErrorSavedataMsg; //"Error occurred while saving data";
                    }
                }
            }
            catch (Exception exception)
            {
                LoggerHelper.WriteToLog(exception, "Error While Connecting to an API." + exception.ToString());
                throw new DataAccessException("Error While Connecting to an API");
            }
            return(result);
        }
        public void ItIsAController()
        {
            var service    = new UserProfileService(new FakeRepository <UserProfileDto>());
            var controller = new UserProfileController(service);

            Assert.IsAssignableFrom <Controller>(controller);
        }
Exemple #3
0
        /// <summary>
        /// This method is exceuted to call the API endpoint URI
        /// </summary>
        /// <param name="endpointUri">endpoint URI to be called</param>
        /// <param name="credentials">credential needed to connect</param>
        /// <returns>result received from the API</returns>
        /// <exception cref="Exception">Error while connecting to API</exception>
        // Get API call for user details
        public async Task <string> APIGetCall(string endpointUri)
        {
            string result = string.Empty;

            try
            {
                UserProfileController userProfileObj = new UserProfileController();
                //create object of client request
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
                    client.DefaultRequestHeaders.Add("ContentType", "application/json;odata=verbose");
                    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + await userProfileObj.GetTokenForApplication());
                    result = await client.GetStringAsync(endpointUri);

                    //if(responseMessage.StatusCode.Equals(HttpStatusCode.NotFound))
                    //{
                    //    return responseMessage;
                    //}
                    return(result);
                }
            }
            catch (Exception exception)
            {
                LoggerHelper.WriteToLog(exception, "Error While Connecting to an API." + exception.ToString());
                throw new DataAccessException("Error While Connecting to an API");
            }
        }
        private IActionResult GetUserProfile(RequestResult <UserProfileModel> expected, Dictionary <string, UserPreferenceModel> userPreferencePayloadMock)
        {
            // Setup
            Mock <IHttpContextAccessor> httpContextAccessorMock = CreateValidHttpContext(token, userId, hdid);

            Mock <IUserProfileService> userProfileServiceMock = new Mock <IUserProfileService>();

            userProfileServiceMock.Setup(s => s.GetUserProfile(hdid, It.IsAny <DateTime>())).Returns(expected);
            userProfileServiceMock.Setup(s => s.GetActiveTermsOfService()).Returns(new RequestResult <TermsOfServiceModel>());
            userProfileServiceMock.Setup(s => s.GetUserPreferences(hdid)).Returns(new RequestResult <Dictionary <string, UserPreferenceModel> >()
            {
                ResourcePayload = userPreferencePayloadMock
            });

            Mock <IUserEmailService> emailServiceMock = new Mock <IUserEmailService>();
            Mock <IUserSMSService>   smsServiceMock   = new Mock <IUserSMSService>();

            UserProfileController service = new UserProfileController(
                new Mock <ILogger <UserProfileController> >().Object,
                userProfileServiceMock.Object,
                httpContextAccessorMock.Object,
                emailServiceMock.Object,
                smsServiceMock.Object
                );

            return(service.GetUserProfile(hdid));
        }
        public void If_set_as_inactive_fails_then_redirects_to_details_view()
        {
            #region Arrange
            UserProfileController.ControllerContext = TestHelper.MockControllerContext(UserProfileController)
                                                      .WithAuthenticatedUser("test");
            using (Mock.Record())
            {
                Expect.Call(ProfileService.SetAsInactiveByName("test")).Return(false);
            }

            #endregion

            #region Act

            RedirectToRouteResult redirect;
            using (Mock.Playback())
            {
                redirect = (RedirectToRouteResult)UserProfileController.Delete();
            }

            #endregion

            #region Assert
            redirect.AssertActionRedirect().ToAction("Details");
            #endregion
        }
        public void Put_Method_Updates_A_User()
        {
            //Arrange
            var testUserId = 99;
            var users      = CreateTestUsers(5);

            users[0].Id = testUserId; // Make sure we know the Id of one of the users

            var repo       = new InMemoryUserProfileRepository(users);
            var controller = new UserProfileController(repo);

            var userToUpdate = new UserProfile()
            {
                Id          = testUserId,
                Name        = "Updated!",
                Email       = "Updated!",
                Bio         = "Updated",
                DateCreated = DateTime.Today,
                ImageUrl    = "http://user.image.url",
            };

            //Act
            var result = controller.Put(testUserId, userToUpdate);

            //Assert
            var userFromDb = repo.InternalData.FirstOrDefault(u => u.Id == testUserId);

            Assert.NotNull(userFromDb);

            Assert.Equal(userToUpdate.Name, userFromDb.Name);
            Assert.Equal(userToUpdate.Email, userFromDb.Email);
            Assert.Equal(userToUpdate.Bio, userFromDb.Bio);
            Assert.Equal(userToUpdate.DateCreated, userFromDb.DateCreated);
            Assert.Equal(userToUpdate.ImageUrl, userFromDb.ImageUrl);
        }
        public void UserProfileControllerTest()
        {
            var controller = new UserProfileController(_mock.Object);

            Assert.IsNotNull(controller);
            Assert.IsInstanceOfType(controller, typeof(UserProfileController));
        }
        private IActionResult CreateUserPreference(UserPreferenceModel userPref)
        {
            // Setup
            Mock <IHttpContextAccessor> httpContextAccessorMock = CreateValidHttpContext(token, userId, hdid);

            Mock <IUserProfileService>          userProfileServiceMock = new Mock <IUserProfileService>();
            RequestResult <UserPreferenceModel> result = new RequestResult <UserPreferenceModel>()
            {
                ResourcePayload = userPref,
                ResultStatus    = ResultType.Success,
            };

            userProfileServiceMock.Setup(s => s.CreateUserPreference(userPref)).Returns(result);

            Mock <IUserEmailService> emailServiceMock = new Mock <IUserEmailService>();
            Mock <IUserSMSService>   smsServiceMock   = new Mock <IUserSMSService>();

            UserProfileController service = new UserProfileController(
                new Mock <ILogger <UserProfileController> >().Object,
                userProfileServiceMock.Object,
                httpContextAccessorMock.Object,
                emailServiceMock.Object,
                smsServiceMock.Object
                );

            return(service.CreateUserPreference(hdid, userPref));
        }
        public void Put_Method_Returns_BadRequest_When_Ids_Do_Not_Match()
        {
            // Arrange
            var testUserProfileId = 99;
            var userProfiles      = CreateTestUserProfiles(5);

            userProfiles[0].Id = testUserProfileId; // Make sure we know the Id of one of the posts

            var repo       = new InMemoryUserProfileRepository(userProfiles);
            var controller = new UserProfileController(repo);

            var userProfileToUpdate = new UserProfile()
            {
                Name           = "Updated",
                Id             = testUserProfileId,
                ImageUrl       = "Updated",
                FirebaseUserId = "Updated",
                Email          = "Updated",
                Bio            = "Updated",
                DateCreated    = DateTime.Today
            };
            var someOtherUserProfileId = testUserProfileId + 1; // make sure they aren't the same

            // Act
            var result = controller.Put(someOtherUserProfileId, userProfileToUpdate);

            // Assert
            Assert.IsType <BadRequestResult>(result);
        }
        public void Put_Method_Updates_A_Post()
        {
            var testUserProfileId = 99;
            var userProfiles      = CreateTestUserProfiles(5);

            userProfiles[0].Id = testUserProfileId;

            var repo       = new InMemoryUserProfileRepository(userProfiles);
            var controller = new UserProfileController(repo);

            var userToUpdate = new UserProfile()
            {
                Id             = testUserProfileId,
                Name           = "Name",
                Email          = "*****@*****.**",
                FirebaseUserId = "abcdefghijklmnopqrstuvwxyzaa",
                ImageUrl       = "http://user.image.com",
                Bio            = "I am the very model of a modern major general.",
                DateCreated    = DateTime.Today
            };

            controller.Put(testUserProfileId, userToUpdate);

            var userFromDb = repo.InternalData.FirstOrDefault(u => u.Id == testUserProfileId);

            Assert.NotNull(userFromDb);

            Assert.Equal(userToUpdate.Name, userFromDb.Name);
            Assert.Equal(userToUpdate.Email, userFromDb.Email);
            Assert.Equal(userToUpdate.FirebaseUserId, userFromDb.FirebaseUserId);
            Assert.Equal(userToUpdate.ImageUrl, userFromDb.ImageUrl);
            Assert.Equal(userToUpdate.Bio, userFromDb.Bio);
            Assert.Equal(userToUpdate.DateCreated, userFromDb.DateCreated);
        }
Exemple #11
0
        //Post call for approval api
        public async Task <string> ApprovalAPIPostCall(string endpointUri, ApprovalQuery ObjApprovalQuery)
        {
            UserProfileController userProfileObj = new UserProfileController();
            var result = string.Empty;

            try
            {
                //create object of client request
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
                    client.DefaultRequestHeaders.Add("ContentType", "application/json;odata=verbose");
                    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + await userProfileObj.GetTokenForApplication());

                    //get API endpoint and format

                    var request1 = new HttpRequestMessage(HttpMethod.Post, endpointUri);
                    request1.Content = new StringContent(JsonConvert.SerializeObject(ObjApprovalQuery), Encoding.UTF8, "application/json");
                    var result1 = client.SendAsync(request1).Result;
                    //if the api call returns successcode then return the result into string
                    if (result1.IsSuccessStatusCode)
                    {
                        result = result1.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                    }
                }
            }
            catch (Exception exception)
            {
                LoggerHelper.WriteToLog(exception, "Error While Connecting to an API." + exception.ToString());
                throw new DataAccessException("Error While Connecting to an API");
            }
            return(result);
        }
        public void Gets_profile_of_current_user_and_set_as_inactive_then_redirects_to_log_off_action()
        {
            #region Arrange
            UserProfileController.ControllerContext = TestHelper.MockControllerContext(UserProfileController)
                                                      .WithAuthenticatedUser("test");
            using (Mock.Record())
            {
                Expect.Call(ProfileService.SetAsInactiveByName("test")).Return(true);
            }

            #endregion

            #region Act

            RedirectToRouteResult redirect;
            using (Mock.Playback())
            {
                redirect = (RedirectToRouteResult)UserProfileController.Delete();
            }

            #endregion

            #region Assert
            redirect.AssertActionRedirect().ToAction("LogOff").ToController("Account");
            #endregion
        }
        public void UserProfile_Method_Adds_A_New_UserProfile()
        {
            // Arrange
            var userProfileCount = 20;
            var userProfiles     = CreateTestUserProfiles(userProfileCount);

            var repo       = new InMemoryUserProfileRepository(userProfiles);
            var controller = new UserProfileController(repo);

            // Act
            var newUserProfile = new UserProfile()
            {
                Name           = "Name",
                ImageUrl       = "ImageUrl",
                FirebaseUserId = "FirebaseUserId",
                Email          = "Email",
                Bio            = "Bio",
                DateCreated    = DateTime.Today
            };

            controller.Register(newUserProfile);

            // Assert
            Assert.Equal(userProfileCount + 1, repo.InternalData.Count);
        }
        public void If_update_to_db_fails_return_default_view()
        {
            #region Arrange

            UserProfileController.ControllerContext = TestHelper.MockControllerContext(UserProfileController).WithAuthenticatedUser("test");
            UserProfileController.ValueProvider     = new FormCollection().ToValueProvider();

            using (Mock.Record())
            {
                Expect.Call(ProfileService.GetByName("test")).Return(Profile);
                Expect.Call(ProfileService.UpdateProfile(Profile)).Return(false);
            }

            #endregion

            #region Act
            ViewResult view;
            using (Mock.Playback())
            {
                view = (ViewResult)UserProfileController.Edit(null);
            }

            #endregion

            #region Assert
            Assert.IsEmpty(view.ViewName);
            Assert.That(view.ViewData.Model, Is.InstanceOf(typeof(ProfileModelDto)));
            Assert.That(view.ViewData["Error"], Is.EqualTo("Problem Updating Profile"));

            #endregion
        }
        public void Gets_profile_by_name_then_returns_default_view()
        {
            #region Arrange
            UserProfileController.ControllerContext = TestHelper.MockControllerContext(UserProfileController)
                                                      .WithAuthenticatedUser("test");

            using (Mock.Record())
            {
                Expect.Call(ProfileService.GetByName("test")).Return(Profile);
            }

            #endregion

            #region Act

            ViewResult view;
            using (Mock.Playback())
            {
                view = (ViewResult)UserProfileController.Details();
            }

            #endregion

            #region Assert
            Assert.IsEmpty(view.ViewName);
            Assert.That(view.ViewData.Model, Is.EqualTo(Profile));
            #endregion
        }
Exemple #16
0
        public void Put_Method_Updates_User()
        {
            var testUserId = 999;
            var users      = CreateTestUsers(5);

            users[0].Id = testUserId;

            var repo       = new InMemoryUserProfileRepository(users);
            var controller = new UserProfileController(repo);

            var userToUpdate = new UserProfile()
            {
                Id          = testUserId,
                Name        = $"Updated",
                Email       = $"*****@*****.**",
                ImageUrl    = "http://post.image.url",
                DateCreated = DateTime.Today,
                Bio         = $"Bob really hates cheese",
            };

            controller.Put(testUserId, userToUpdate);

            var userFromDb = repo.InternalData.FirstOrDefault(user => user.Id == testUserId);

            Assert.NotNull(userFromDb);
            Assert.Equal(userToUpdate.Name, userFromDb.Name);
            Assert.Equal(userToUpdate.Email, userFromDb.Email);
            Assert.Equal(userToUpdate.ImageUrl, userFromDb.ImageUrl);
            Assert.Equal(userToUpdate.DateCreated, userFromDb.DateCreated);
            Assert.Equal(userToUpdate.Bio, userFromDb.Bio);
        }
        public void Post_updates_profile_then_redirects_to_details_view()
        {
            #region Arrange

            UserProfileController.ControllerContext = TestHelper.MockControllerContext(UserProfileController)
                                                      .WithAuthenticatedUser("test");
            UserProfileController.ValueProvider = new FormCollection().ToValueProvider();

            using (Mock.Record())
            {
                Expect.Call(ProfileService.GetByName("test")).Return(Profile);
                Expect.Call(ProfileService.UpdateProfile(Profile)).Return(true);
            }

            #endregion

            #region Act

            RedirectToRouteResult redirect;
            using (Mock.Playback())
            {
                redirect = (RedirectToRouteResult)UserProfileController.Edit(null);
            }

            #endregion

            #region Assert
            redirect.AssertActionRedirect().ToAction("Details").WithParameter("id", 1);
            #endregion
        }
        public void Put_Method_Returns_Bad_Request_When_Ids_Do_Not_Match()
        {
            var testUserProfileId = 99;
            var userProfiles      = CreateTestUserProfiles(5);

            userProfiles[0].Id = testUserProfileId;

            var repo       = new InMemoryUserProfileRepository(userProfiles);
            var controller = new UserProfileController(repo);

            var userToUpdate = new UserProfile()
            {
                Id             = testUserProfileId,
                Name           = "Name",
                Email          = "*****@*****.**",
                FirebaseUserId = "abcdefghijklmnopqrstuvwxyzaa",
                ImageUrl       = "http://user.image.com",
                Bio            = "I am the very model of a modern major general.",
                DateCreated    = DateTime.Today
            };
            var someOtherUserProfileId = testUserProfileId + 1;

            var result = controller.Put(someOtherUserProfileId, userToUpdate);

            Assert.IsType <BadRequestResult>(result);
        }
        public void InitializeLODController()
        {
            if (lodController == null)
            {
                return;
            }

            UserProfile userProfile = null;

            if (!string.IsNullOrEmpty(model?.id))
            {
                userProfile = UserProfileController.GetProfileByUserId(model.id);
            }

            if (userProfile != null)
            {
                bodySnapshotTexturePromise = new AssetPromise_Texture(userProfile.bodySnapshotURL);
                bodySnapshotTexturePromise.OnSuccessEvent += asset => lodController.SetImpostorTexture(asset.texture);
                bodySnapshotTexturePromise.OnFailEvent    += asset => lodController.RandomizeAndApplyGenericImpostor();
                AssetPromiseKeeper_Texture.i.Keep(bodySnapshotTexturePromise);
            }
            else
            {
                lodController.RandomizeAndApplyGenericImpostor();
            }

            Environment.i.platform.avatarsLODController.RegisterAvatar(lodController);
        }
Exemple #20
0
 protected void btnDeleteProfilePic_Click(object sender, EventArgs e)
 {
     try
     {
         UserProfileInfo objinfo = new UserProfileInfo();
         objinfo = UserProfileController.GetProfile(GetUsername, GetPortalID);
         if (objinfo.Image != "")
         {
             string imagePath = ResolveUrl(this.AppRelativeTemplateSourceDirectory) + "UserPic/" + objinfo.Image;
             string path      = Server.MapPath(imagePath);
             if (File.Exists(path))
             {
                 File.Delete(path);
             }
         }
         UserProfileController.DeleteProfilePic(GetUsername, GetPortalID);
         ShowHideProfile();
         GetUserDetails();
         LoadUserDetails();
         Session[SessionKeys.Profile_Image] = null;
     }
     catch (Exception)
     {
         throw;
     }
 }
        public async void ShouldValidateEmailWithEmailNotFound()
        {
            PrimitiveRequestResult <bool> primitiveRequestResult = new PrimitiveRequestResult <bool>()
            {
                ResourcePayload = false,
                ResultStatus    = ResultType.Error,
                ResultError     = null
            };
            Mock <IUserEmailService> emailServiceMock = new Mock <IUserEmailService>();

            emailServiceMock.Setup(s => s.ValidateEmail(It.IsAny <string>(), It.IsAny <Guid>())).Returns(primitiveRequestResult);

            Mock <IHttpContextAccessor> httpContextAccessorMock = CreateValidHttpContext(token, userId, hdid);
            UserProfileController       controller = new UserProfileController(
                new Mock <ILogger <UserProfileController> >().Object,
                null,
                httpContextAccessorMock.Object,
                emailServiceMock.Object,
                null
                );
            IActionResult actualResult = await controller.ValidateEmail(hdid, Guid.NewGuid());

            var result = ((JsonResult)actualResult).Value as PrimitiveRequestResult <bool>;

            Assert.Equal(ResultType.Error, result.ResultStatus);
        }
        public async Task ShouldValidateAge()
        {
            string hdid   = "1234567890123456789012345678901234567890123456789012";
            string token  = "Fake Access Token";
            string userId = "1001";

            UserProfile userProfile = new UserProfile
            {
                HdId = hdid,
                AcceptedTermsOfService = true
            };

            PrimitiveRequestResult <bool> expected = new PrimitiveRequestResult <bool>()
            {
                ResultStatus = ResultType.Success, ResourcePayload = true
            };
            Mock <IHttpContextAccessor> httpContextAccessorMock = CreateValidHttpContext(token, userId, hdid);

            Mock <IUserProfileService> userProfileServiceMock = new Mock <IUserProfileService>();

            userProfileServiceMock.Setup(s => s.ValidateMinimumAge(hdid)).ReturnsAsync(expected);


            UserProfileController controller = new UserProfileController(
                new Mock <ILogger <UserProfileController> >().Object,
                userProfileServiceMock.Object,
                httpContextAccessorMock.Object,
                new Mock <IUserEmailService>().Object,
                new Mock <IUserSMSService>().Object
                );
            IActionResult actualResult = await controller.Validate(hdid);

            Assert.IsType <JsonResult>(actualResult);
            Assert.Equal(expected, ((JsonResult)actualResult).Value);
        }
Exemple #23
0
        public async Task UpdatesExistingRecord_WhenUserProfile_DoesExist()
        {
            UserProfile actualUserProfile = null;

            var existingUserProfile = new UserProfile
            {
                UserId = "001",
                Id     = new Guid(),
                Weight = 10,
                Height = 20,
                Age    = 30
            };

            var mockUserProfileStore = Substitute.For <IUserProfileStore>();

            mockUserProfileStore.GetProfile(Arg.Any <string>()).Returns(Task.FromResult <UserProfile>(existingUserProfile));
            mockUserProfileStore.WhenForAnyArgs(x => x.SetProfile(null)).Do(x => actualUserProfile = x.ArgAt <UserProfile>(0));
            var controller = new UserProfileController(_mockUserContext, mockUserProfileStore);
            await controller.SetProfile(new SetUserProfileRequest
            {
                Weight = 3,
                Height = 2,
                Age    = 1
            });

            actualUserProfile.Should().NotBeNull();
            actualUserProfile.Weight.Should().Be(3);
            actualUserProfile.Height.Should().Be(2);
            actualUserProfile.Age.Should().Be(1);
            actualUserProfile.Id.Should().Be(existingUserProfile.Id);
            actualUserProfile.UserId.Should().Be("001");
        }
Exemple #24
0
        public static async Task GetADUser()
        {
            TimeSheetDb timesheetDb       = new TimeSheetDb();
            string      NTI_Staff_GroupID = ConfigurationManager.AppSettings["ida:NTI_Staff_GroupID"];
            var         userList          = new List <User>();

            try
            {
                ActiveDirectoryClient client = UserProfileController.GetActiveDirectoryClient();
                IGroup group = await client.Groups.GetByObjectId(NTI_Staff_GroupID).ExecuteAsync();

                IGroupFetcher groupFetcher = group as IGroupFetcher;
                IPagedCollection <IDirectoryObject> pagedCollection = await groupFetcher.Members.ExecuteAsync();

                if (pagedCollection != null)
                {
                    do
                    {
                        List <IDirectoryObject> directoryObjects = pagedCollection.CurrentPage.ToList();
                        foreach (IDirectoryObject directoryObject in directoryObjects)
                        {
                            if (directoryObject is User)
                            {
                                var user = (User)directoryObject;
                                userList.Add(user);
                            }
                        }
                        pagedCollection = await pagedCollection.GetNextPageAsync();
                    } while (pagedCollection != null);
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            if (userList != null)
            {
                List <ADUser> SystemUserList = timesheetDb.ADUsers.ToList();
                if (SystemUserList.Count != userList.Count)
                {
                    foreach (var item in userList)
                    {
                        if (timesheetDb.ADUsers.Find(item.Mail) == null)
                        {
                            timesheetDb.ADUsers.Add(new ADUser {
                                UserName   = item.DisplayName,
                                Email      = item.Mail,
                                JobCode    = item.JobTitle,
                                Department = item.Department
                            }
                                                    );
                        }
                    }

                    timesheetDb.SaveChanges();
                }
            }
        }
Exemple #25
0
    bool AlreadyFriends(string friendUserName)
    {
        var friendUserProfile = UserProfileController.GetProfileByName(friendUserName);

        return(friendUserProfile != null &&
               FriendsController.i.friends.ContainsKey(friendUserProfile.userId) &&
               FriendsController.i.friends[friendUserProfile.userId].friendshipStatus == FriendshipStatus.FRIEND);
    }
Exemple #26
0
    public void GetUserDetails()
    {
        try
        {
            UserProfileInfo objinfo = new UserProfileInfo();
            objinfo = UserProfileController.GetProfile(GetUsername, GetPortalID);
            string UserImage = Server.MapPath("~/Modules/Admin/UserManagement/UserPic/");
            if (!Directory.Exists(UserImage))
            {
                Directory.CreateDirectory(UserImage);
            }
            if (objinfo != null)
            {
                string[] Emails = objinfo.Email.Split(',');
                if (objinfo.Image != "")
                {
                    imgUser.ImageUrl                   = "~/Modules/Admin/UserManagement/UserPic/" + objinfo.Image;
                    imgUser.Visible                    = true;
                    imgProfileEdit.Visible             = true;
                    btnDeleteProfilePic.Visible        = true;
                    Session[SessionKeys.Profile_Image] = objinfo.Image;
                }
                else
                {
                    imgUser.Visible        = false;
                    imgProfileEdit.Visible = false;
                }
                lblDisplayUserName.Text = objinfo.UserName;
                txtFName.Text           = objinfo.FirstName;
                txtLName.Text           = objinfo.LastName;
                txtFullName.Text        = objinfo.FullName;
                txtLocation.Text        = objinfo.Location;
                txtAboutYou.Text        = objinfo.AboutYou;
                txtEmail1.Text          = Emails[0];
                txtBirthDate.Text       = (objinfo.BirthDate.ToShortDateString() == falseDate || objinfo.BirthDate.ToShortDateString() == defaultDate) ? "" : objinfo.BirthDate.ToShortDateString();
                rdbGender.SelectedIndex = objinfo.Gender;
                if (Emails.Length == 3)
                {
                    txtEmail2.Text = Emails[1];
                }
                if (Emails.Length == 4)
                {
                    txtEmail2.Text = Emails[1];
                    txtEmail3.Text = Emails[2];
                }
                txtResPhone.Text = objinfo.ResPhone;

                txtMobile.Text = objinfo.Mobile != string.Empty? objinfo.Mobile : txtMobile.Text = string.Empty;
                //txtMobile.Text = objinfo.Mobile;
                txtOthers.Text = objinfo.Others;
            }
        }
        catch (Exception)
        {
            throw;
        }
    }
Exemple #27
0
 void Start()
 {
     userProfileController         = this.gameObject.GetComponent <UserProfileController> ();
     this.slimePlayerManagerObject = GameObject.Find("SlimePlayerManager");
     if (slimePlayerManagerObject == null)
     {
         Debug.LogError("SlimePlayerManager GameObject not found in scene.");
     }
 }
Exemple #28
0
        public void UpdateProfile(int id)
        {
            User m = User.findById(id);

            UserProfileController.SaveProfile(m, ctx);
            db.update(m);
            db.update(m.Profile);
            echoRedirectPart(lang("opok"));
        }
 public void Setup()
 {
     _loggerMock      = new Mock <ILogger <UserProfileController> >();
     _claimsPrincipal = new ClaimsPrincipalBuilder()
                        .WithRole(AppRoles.QA)
                        .WithClaim(ClaimTypes.GivenName, UserData.FIRST_NAME)
                        .WithClaim(ClaimTypes.Surname, UserData.LAST_NAME)
                        .WithClaim("name", UserData.DISPLAY_NAME)
                        .Build();
     _controller = SetupControllerWithClaims();
 }
        public void Get_By_Id_Returns_Not_Found_For_Invalid_Id()
        {
            var userProfiles = new List <UserProfile>();

            var repo       = new InMemoryUserProfileRepository(userProfiles);
            var controller = new UserProfileController(repo);

            var result = controller.Get(1);

            Assert.IsType <NotFoundResult>(result);
        }
Exemple #31
0
        private bool SaveProfile()
        {
            if (CanEditMode())
            {
                DotNetNuke.Entities.Users.UserInfo objuser = DotNetNuke.Entities.Users.UserController.GetUser(PortalId, UID, true);
                UserProfileController upc = new UserProfileController();
                UserController uc = new UserController();
                UserProfileInfo upi = uc.GetUser(PortalId, ModuleId, UID).Profile;
                if (upi != null)
                {
                    upi.WebSite = Utilities.XSSFilter(txtWebSite.Text, true);
                    upi.Occupation = Utilities.XSSFilter(txtOccupation.Text, true);
                    upi.Location = Utilities.XSSFilter(txtLocation.Text, true);
                    upi.Interests = Utilities.XSSFilter(txtInterests.Text, true);
                    upi.Yahoo = Utilities.XSSFilter(txtYahoo.Text, true);
                    upi.MSN = Utilities.XSSFilter(txtMSN.Text, true);
                    upi.ICQ = Utilities.XSSFilter(txtICQ.Text, true);
                    upi.AOL = Utilities.XSSFilter(txtAOL.Text, true);
                    if (MainSettings.AllowSignatures == 1)
                    {
                        upi.Signature = Utilities.XSSFilter(txtSignature.Text, true);
                        upi.Signature = Utilities.StripHTMLTag(upi.Signature);
                        upi.Signature = Utilities.HTMLEncode(upi.Signature);
                    }
                    else if (MainSettings.AllowSignatures == 2)
                    {
                        upi.Signature = Utilities.XSSFilter(txtSignature.Text, false);
                    }



                    upc.Profiles_Save(upi);
                    bool blnSaveProfile = false;

                    DotNetNuke.Entities.Profile.ProfilePropertyDefinitionCollection profproperties = new DotNetNuke.Entities.Profile.ProfilePropertyDefinitionCollection();
                    profproperties = objuser.Profile.ProfileProperties;
                    foreach (DotNetNuke.Entities.Profile.ProfilePropertyDefinition profprop in profproperties)
                    {
                        Control ctl = RecursiveFind(this, "dnnctl" + profprop.PropertyName);
                        if (ctl != null)
                        {
                            if (ctl is TextBox)
                            {
                                TextBox txt = (TextBox)ctl;
                                if (txt.ID.Contains("dnnctl"))
                                {
                                    blnSaveProfile = true;
                                    string propName = txt.ID.Replace("dnnctl", string.Empty);
                                    objuser.Profile.GetProperty(propName).PropertyValue = txt.Text;
                                }

                            }
                        }
                    }

                    if (blnSaveProfile)
                    {
                        DotNetNuke.Entities.Users.UserController.UpdateUser(PortalId, objuser);
                    }
                }
            }
            return true;
        }
Exemple #32
0
        private void SaveQuickReply()
        {
            int iFloodInterval = MainSettings.FloodInterval;
            if (iFloodInterval > 0)
            {
                UserProfileController upc = new UserProfileController();
                UserProfileInfo upi = upc.Profiles_Get(SiteId, InstanceId, this.UserId);
                if (upi != null)
                {
                    if (SimulateDateDiff.DateDiff(SimulateDateDiff.DateInterval.Second, upi.DateLastPost, DateTime.Now) < iFloodInterval)
                    {
                        Controls.InfoMessage im = new Controls.InfoMessage();
                        im.Message = "<div class=\"afmessage\">" + string.Format(Utilities.GetSharedResource("[RESX:Error:FloodControl]"), iFloodInterval) + "</div>";
                        plhMessage.Controls.Add(im);
                        return;
                    }
                }
            }
            //TODO: Fix for anon
            //If Not Current.Request.IsAuthenticated Then
            //    If Not ctlCaptcha.IsValid Or txtUserName.Value = "" Then
            //        Exit Sub
            //    End If
            //End If
            //Dim ui As New UserProfileInfo
            //If UserId > 0 Then
            //    Dim upc As New UserProfileController
            //    ui = upc.Profiles_Get(PortalId, ForumModuleId, UserId)
            //Else
            //    ui.TopicCount = 0
            //    ui.ReplyCount = 0
            //    ui.RewardPoints = 0
            //    ui.IsMod = False
            //    ui.TrustLevel = -1

            //End If
            ForumController fc = new ForumController();
            Forum forumInfo = fc.Forums_Get(SiteId, InstanceId, ForumId, this.UserId, true, false, TopicId);
            bool UserIsTrusted = false;
            UserIsTrusted = Utilities.IsTrusted((int)forumInfo.DefaultTrustValue, ControlConfig.User.TrustLevel, Permissions.HasPerm(forumInfo.Security.Trust, ForumUser.UserRoles), forumInfo.AutoTrustLevel, ControlConfig.User.PostCount);
            bool isApproved = false;
            isApproved = Convert.ToBoolean(((forumInfo.IsModerated == true) ? false : true));
            if (UserIsTrusted || Permissions.HasPerm(forumInfo.Security.ModApprove, ForumUser.UserRoles))
            {
                isApproved = true;
            }
            ReplyInfo ri = new ReplyInfo();
            Data.Topics db = new Data.Topics();
            //im rc As New ReplyController
            int ReplyId = -1;
            string sUsername = string.Empty;
            if (HttpContext.Current.Request.IsAuthenticated)
            {
                sUsername = ControlConfig.User.DisplayName;
            }
            else
            {
                sUsername = Utilities.CleanString(SiteId, txtUserName.Value, false, EditorTypes.TEXTBOX, true, false, InstanceId, ThemePath, false);
            }

            string sBody = string.Empty;
            //TODO: Check for allowhtml
            bool allowHtml = false;
            //If forumInfo.AllowHTML Then
            //    allowHtml = isHTMLPermitted(forumInfo.EditorPermittedUsers, IsTrusted, forumInfo.Security.ModEdit)
            //End If
            sBody = Utilities.CleanString(SiteId, HttpContext.Current.Request.Form["txtBody"], allowHtml, EditorTypes.TEXTBOX, forumInfo.UseFilter, forumInfo.AllowScript, InstanceId, ThemePath, forumInfo.AllowEmoticons);
            DateTime createDate = DateTime.Now;
            ri.TopicId = TopicId;
            ri.ReplyToId = TopicId;
            ri.Content.AuthorId = UserId;
            ri.Content.AuthorName = sUsername;
            ri.Content.Body = sBody;
            ri.Content.DateCreated = createDate;
            ri.Content.DateUpdated = createDate;
            ri.Content.IsDeleted = false;
            ri.Content.Subject = Subject;
            ri.Content.Summary = string.Empty;
            ri.IsApproved = isApproved;
            ri.IsDeleted = false;
            ri.Content.IPAddress = HttpContext.Current.Request.UserHostAddress;
            ReplyId = db.Reply_Save(ri);
            //Check if is subscribed
            if (HttpContext.Current.Request.Params["chkSubscribe"] != null)
            {
                if (HttpContext.Current.Request.Params["chkSubscribe"] == "1" && UserId > 0)
                {
                    if (!(Subscriptions.IsSubscribed(SiteId, InstanceId, ForumId, TopicId, SubscriptionTypes.Instant, UserId)))
                    {
                        //TODO: Fix Subscriptions
                        //Dim sc As New Data.Tracking
                        //sc.Subscription_Update(SiteId, InstanceId, ForumId, TopicId, 1, UserId)
                    }
                }
            }
            if (isApproved)
            {
                //Send Subscriptions
                try
                {
                    string sURL = Utilities.NavigateUrl(PageId, "", new string[] { ParamKeys.ForumId + "=" + ForumId, ParamKeys.ViewType + "=" + Views.Topic, ParamKeys.TopicId + "=" + TopicId, ParamKeys.ContentJumpId + "=" + ReplyId });
                    Subscriptions.SendSubscriptions(SiteId, InstanceId, PageId, ForumId, TopicId, ReplyId, UserId);

#if !SKU_LITE
                    try
                    {
                        Social oSocial = new Social();
                        oSocial.AddForumItemToJournal(SiteId, InstanceId, UserId, "forumreply", sURL, Subject, sBody);
                    }
                    catch (Exception ex)
                    {
                        DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
                    }

#endif
                }
                catch (Exception ex)
                {
                    DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, ex);
                }
                //Redirect to show post
                string fullURL = Utilities.NavigateUrl(PageId, "", new string[] { ParamKeys.ForumId + "=" + ForumId, ParamKeys.ViewType + "=" + Views.Topic, ParamKeys.TopicId + "=" + TopicId, ParamKeys.ContentJumpId + "=" + ReplyId });
                HttpContext.Current.Response.Redirect(fullURL, false);
            }
            else if (isApproved == false)
            {
                Email.SendEmailToModerators(forumInfo.ModNotifyTemplateId, SiteId, ForumId, ri.TopicId, ReplyId, InstanceId, PageId, string.Empty);
                string[] Params = { ParamKeys.ForumId + "=" + ForumId, ParamKeys.ViewType + "=confirmaction", "afmsg=pendingmod", ParamKeys.TopicId + "=" + TopicId };
                HttpContext.Current.Response.Redirect(Utilities.NavigateUrl(PageId, "", Params), false);
            }
            else
            {
                string fullURL = Utilities.NavigateUrl(PageId, "", new string[] { ParamKeys.ForumId + "=" + ForumId, ParamKeys.ViewType + "=" + Views.Topic, ParamKeys.TopicId + "=" + TopicId, ParamKeys.ContentJumpId + "=" + ReplyId });

#if !SKU_LITE
                try
                {
                    Modules.ActiveForums.Social oSocial = new Modules.ActiveForums.Social();
                    oSocial.AddForumItemToJournal(SiteId, InstanceId, UserId, "forumreply", fullURL, Subject, sBody);
                }
                catch (Exception ex)
                {
                    DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
                }

#endif
                HttpContext.Current.Response.Redirect(fullURL, false);
            }

            //End If


        }