Ejemplo n.º 1
0
        /// <summary>
        /// Optimizely constructor for managing Full Stack .NET projects.
        /// </summary>
        /// <param name="datafile">string JSON string representing the project</param>
        /// <param name="eventDispatcher">EventDispatcherInterface</param>
        /// <param name="logger">LoggerInterface</param>
        /// <param name="errorHandler">ErrorHandlerInterface</param>
        /// <param name="skipJsonValidation">boolean representing whether JSON schema validation needs to be performed</param>
        public Optimizely(string datafile,
                          IEventDispatcher eventDispatcher = null,
                          ILogger logger                        = null,
                          IErrorHandler errorHandler            = null,
                          UserProfileService userProfileService = null,
                          bool skipJsonValidation               = false)
        {
            IsValid            = false; // invalid until proven valid
            Logger             = logger ?? new NoOpLogger();
            EventDispatcher    = eventDispatcher ?? new DefaultEventDispatcher(Logger);
            ErrorHandler       = errorHandler ?? new NoOpErrorHandler();
            Bucketer           = new Bucketer(Logger);
            EventBuilder       = new EventBuilder(Bucketer, Logger);
            UserProfileService = userProfileService;
            NotificationCenter = new NotificationCenter(Logger);

            try
            {
                if (!ValidateInputs(datafile, skipJsonValidation))
                {
                    Logger.Log(LogLevel.ERROR, "Provided 'datafile' has invalid schema.");
                    return;
                }

                Config          = ProjectConfig.Create(datafile, Logger, ErrorHandler);
                IsValid         = true;
                DecisionService = new DecisionService(Bucketer, ErrorHandler, Config, userProfileService, Logger);
            }
            catch (Exception ex)
            {
                Logger.Log(LogLevel.ERROR, "Provided 'datafile' is in an invalid format. " + ex.Message);
            }
        }
        public void Update_ValidModel(int id)
        {
            //arrange
            var updatedItem = new UserProfile
            {
                Id        = id,
                FirstName = "John",
                LastName  = "Doe Jr."
            };

            var currentTime = DateTime.UtcNow;

            //act
            var service = new UserProfileService(_userProfileRepository.Object, _logger.Object);

            service.Update(updatedItem);

            var updatedData = _data.FirstOrDefault(d => d.Id == id);

            //assert
            if (updatedData != null)
            {
                Assert.Equal(updatedData.LastName, updatedItem.LastName);
                Assert.True(updatedData.Updated >= currentTime);
            }
        }
Ejemplo n.º 3
0
        public void Login_ShouldReturnToken(string userName, string password)
        {
            // arrange
            var dto = new LoginDto
            {
                UserName = userName,
                Password = password
            };

            var encodedPassword = PasswordHelper.EncodePassword(password);

            var baseRepositoryMock = new Mock <IBaseRepository>();

            baseRepositoryMock
            .Setup(m => m.Get <User>(x => x.UserName == dto.UserName))
            .Returns(() => new User
            {
                UserName     = userName,
                Password     = encodedPassword.PasswordHash,
                PasswordSalt = encodedPassword.PasswordSalt
            });

            var jwtService         = new JwtService();
            var userService        = new UserService(null, null, null, null);
            var userProfileService = new UserProfileService(baseRepositoryMock.Object, null, userService);
            var service            = new AuthService(baseRepositoryMock.Object, jwtService, userProfileService);

            // act
            var result = service.Login(dto);

            // assert
            Assert.IsNotEmpty(result.Token);
            Assert.IsNotNull(result.Token);
        }
Ejemplo n.º 4
0
        public void Login_ShouldNotReturnToken(string userName, string password)
        {
            // arrange
            var dto = new LoginDto
            {
                UserName = userName,
                Password = password
            };

            var baseRepositoryMock = new Mock <IBaseRepository>();

            baseRepositoryMock
            .Setup(m => m.Get <User>(x => x.UserName == dto.UserName))
            .Returns(() => new User
            {
                UserName     = userName,
                Password     = PasswordHelper.EncodePassword(password).PasswordHash,
                PasswordSalt = PasswordHelper.EncodePassword(password).PasswordSalt
            });

            var jwtService         = new JwtService();
            var userService        = new UserService(null, null, null, null);
            var userProfileService = new UserProfileService(baseRepositoryMock.Object, null, userService);
            var service            = new AuthService(baseRepositoryMock.Object, jwtService, userProfileService);

            // act

            // assert
            Assert.That(Assert.Throws <UnauthorizedAccessException>(() => service.Login(dto))?.Message == AuthExceptionMessages.INVALID_USERNAME_OR_PASSWORD);
        }
Ejemplo n.º 5
0
        public IHttpActionResult EditProfile()
        {
            // Passing information from form to DTO
            ProfileDTO obj = new ProfileDTO();

            obj.UserName       = HttpContext.Current.Request.Params["UserName"];
            obj.FirstName      = HttpContext.Current.Request.Params["FirstName"];
            obj.LastName       = HttpContext.Current.Request.Params["LastName"];
            obj.Email          = HttpContext.Current.Request.Params["Email"];
            obj.Description    = HttpContext.Current.Request.Params["Description"];
            obj.SkillLevel     = HttpContext.Current.Request.Params["SkillLevel"];
            obj.Gender         = HttpContext.Current.Request.Params["Gender"];
            obj.ProfilePicture = HttpContext.Current.Request.Params["ProfilePicture"];
            // Checking if profile image is being updated
            obj.IsUpdatingProfileImage = HttpContext.Current.Request.Params["IsThereImage"];
            HttpPostedFile imageFile = null;
            // Creates service to handle request
            UserProfileService service = new UserProfileService();

            // Get image if being updated
            if (obj.IsUpdatingProfileImage == "true")
            {
                imageFile = HttpContext.Current.Request.Files[0];
            }
            // Pressing request
            var response = service.EditProfile(obj, imageFile);

            // Was it successful?
            if (!response.IsSuccessful)
            {
                return(Content(HttpStatusCode.BadRequest, "Error: " + response.Messages));
            }
            return(Content(HttpStatusCode.OK, "Operation was successful? " + response.IsSuccessful));
        }
Ejemplo n.º 6
0
 internal static object SetMultipleProfileProperties(UserProfileService userProfileService, string UserName, string[] PropertyName, string[] PropertyValue)
 {
     LogMessage("Setting multiple SPO user profile properties for " + UserName, EventLogEntryType.Information, ServiceEventID.ProfileImageUploaderFailure);
     try
     {
         int            arrayCount = PropertyName.Count();
         PropertyData[] data       = new PropertyData[arrayCount];
         for (int x = 0; x < arrayCount; x++)
         {
             data[x] = new PropertyData
             {
                 Name           = PropertyName[x],
                 IsValueChanged = true,
                 Values         = new ValueData[1]
             };
             data[x].Values[0] = new ValueData
             {
                 Value = PropertyValue[x]
             };
         }
         userProfileService.ModifyUserPropertyByAccountName(UserName, data);
         return(true);
     }
     catch (Exception ex)
     {
         return(ex);
     }
 }
Ejemplo n.º 7
0
        public void GetUserProfile()
        {
            UserProfileService   ups    = new UserProfileService();
            Result <UserProfile> result = ups.GetUserProfile("*****@*****.**");

            Console.WriteLine(result.message);
        }
Ejemplo n.º 8
0
        public IHttpActionResult GetAllProfiles()
        {
            UserProfileService         userProfileService = CreateUserProfileService();
            List <UserProfileListItem> userProfiles       = userProfileService.GetAllUserProfiles();

            return(Ok(userProfiles));
        }
Ejemplo n.º 9
0
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            return(Task.Factory.StartNew(() =>
            {
                var userName = context.UserName;
                var password = context.Password;
                IUserProfileService userService = new UserProfileService(); // our created one
                var user = userService.ValidateUser(userName, password);
                if (user != null)
                {
                    var claims = new List <Claim>()
                    {
                        new Claim(ClaimTypes.Sid, Convert.ToString(user.UserId)),
                        new Claim(ClaimTypes.Name, user.FirstName + user.LastName),
                        new Claim(ClaimTypes.Email, user.Email),
                        new Claim(ClaimTypes.Role, user.RoleName)
                    };
                    ClaimsIdentity oAuthIdentity = new ClaimsIdentity(claims,
                                                                      Startup.OAuthOptions.AuthenticationType);

                    var properties = CreateProperties(Convert.ToString(user.UserId), Convert.ToString(user.SchoolInfoId), user.Email, user.RoleName);
                    var ticket = new AuthenticationTicket(oAuthIdentity, properties);
                    context.Validated(ticket);
                }
                else
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect");
                }
            }));
        }
        public void ItIsAController()
        {
            var service    = new UserProfileService(new FakeRepository <UserProfileDto>());
            var controller = new UserProfileController(service);

            Assert.IsAssignableFrom <Controller>(controller);
        }
Ejemplo n.º 11
0
        public async Task GetUserProfileByAccountId_CorrectAccountId_ReturnsWebUserProfileModel(int profileId,
                                                                                                string firstName, string surname, string dateOfBirth, int accountId)
        {
            // Arrange
            // Setting up each dependency of UserProfileService
            IDataGateway           dataGateway           = new SQLServerGateway();
            IConnectionStringData  connectionString      = new ConnectionStringData();
            IUserProfileRepository userProfileRepository = new UserProfileRepository(dataGateway, connectionString);

            var expectedResult = new WebUserProfileModel();

            expectedResult.Id            = profileId;
            expectedResult.FirstName     = firstName;
            expectedResult.Surname       = surname;
            expectedResult.DateOfBirth   = DateTimeOffset.Parse(dateOfBirth);
            expectedResult.UserAccountId = accountId;

            // Finally, instantiate the actual class being tested and pass in the dependencies
            IUserProfileService userProfileService = new UserProfileService(userProfileRepository);

            // Arrange
            var actualResult = await userProfileService.GetUserProfileByAccountId(accountId);

            // Act
            Assert.IsTrue
            (
                actualResult.Id == expectedResult.Id &&
                actualResult.UserAccountId == expectedResult.UserAccountId
            );
        }
Ejemplo n.º 12
0
 public AccountController(
     UserManager <User> userManager,
     SignInManager <User> signInManager,
     IIdentityServerInteractionService interaction,
     IClientStore clientStore,
     IAuthenticationSchemeProvider schemeProvider,
     IEventService events,
     IdentityServerTools tools,
     //ConfigurationDbContext configurationDbContext,
     IConfiguration configuration,
     INotificationHelper notificationHelper,
     UserProfileService userProfileService,
     OtpKey otpKey,
     TssIdentityDbContext tssIdentityDbContext)
 {
     _userManager    = userManager;
     _signInManager  = signInManager;
     _interaction    = interaction;
     _clientStore    = clientStore;
     _schemeProvider = schemeProvider;
     _events         = events;
     _tools          = tools;
     //_configurationDbContext = configurationDbContext;
     _configurationRoot    = (IConfigurationRoot)configuration;
     _notificationHelper   = notificationHelper;
     _userProfileService   = userProfileService;
     _otpKey               = otpKey;
     _tssIdentityDbContext = tssIdentityDbContext;
 }
Ejemplo n.º 13
0
        // GET api/values/5
        public UserProfile Get(long id)
        {
            var obj  = new UserProfileService();
            var data = obj.GetUserProfile(id);

            return(data);
        }
        private object GetUserProfileInformation(string userPrincipalName)
        {
            using (var ups = new UserProfileService(this.ClientContext, this.ClientContext.Url))
            {
                var personProperties = ups.OWService.GetUserProfileByName(userPrincipalName);
                if (personProperties != null)
                {
                    LogVerbose("User Profile Web Service");
                    LogVerbose("UserName: {0}", personProperties.RetrieveUserProperty("UserName"));
                    LogVerbose("FirstName: {0}", personProperties.RetrieveUserProperty("FirstName"));
                    LogVerbose("LastName: {0}", personProperties.RetrieveUserProperty("LastName"));
                    LogVerbose("PreferredName: {0}", personProperties.RetrieveUserProperty("PreferredName"));
                    LogVerbose("Manager: {0}", personProperties.RetrieveUserProperty("Manager"));
                    LogVerbose("Department: {0}", personProperties.RetrieveUserProperty("Department"));
                    LogVerbose("SPS-Department: {0}", personProperties.RetrieveUserProperty("SPS-Department"));
                    LogVerbose("WorkPhone {0}", personProperties.RetrieveUserProperty("WorkPhone"));
                    LogVerbose("OfficeCubicalLocation {0}", personProperties.RetrieveUserProperty("OfficeCubicalLocation"));
                    LogVerbose("BuldingLocation {0}", personProperties.RetrieveUserProperty("BuldingLocation"));

                    foreach (var userProp in personProperties)
                    {
                        LogVerbose("Property:{0} with value:{1}", userProp.Name, personProperties.RetrieveUserProperty(userProp.Name));
                    }
                }
            }

            return(null);
        }
Ejemplo n.º 15
0
        public void GetUserRatingForAllSessions()
        {
            UserProfileService ups = new UserProfileService();
            Result <List <SessionRatingView> > result = ups.GetUserRatingForAllSessions(2);

            Console.WriteLine(result.message);
        }
Ejemplo n.º 16
0
        public async Task TrackFriendNumber_FriendRequest_GivenDay()
        {
            //arrange
            IDataGateway           dataGateway           = new SQLServerGateway();
            IConnectionStringData  connectionString      = new ConnectionStringData();
            IFriendListRepo        friendListRepo        = new FriendListRepo(dataGateway, connectionString);
            IFriendRequestListRepo friendRequestListRepo = new FriendRequestListRepo(dataGateway, connectionString);
            IUserAccountRepository userAccountRepository = new UserAccountRepository(dataGateway, connectionString);
            IFriendBlockListRepo   friendBlockListRepo   = new FriendBlockListRepo(dataGateway, connectionString);
            IPublicUserProfileRepo publicUserProfileRepo = new PublicUserProfileRepo(dataGateway, connectionString);
            IListingRepository     listingRepository     = new ListingRepository(dataGateway, connectionString);
            ILoginTrackerRepo      loginTrackerRepo      = new LoginTrackerRepo(dataGateway, connectionString);
            IPageVisitTrackerRepo  pageVisitTrackerRepo  = new PageVisitTrackerRepo(dataGateway, connectionString);
            ISearchTrackerRepo     searchTrackerRepo     = new SearchTrackerRepo(dataGateway, connectionString);
            IUserAnalysisService   userAnalysisService   = new UserAnalysisService(friendListRepo, listingRepository, userAccountRepository,
                                                                                   loginTrackerRepo, pageVisitTrackerRepo, friendRequestListRepo, searchTrackerRepo);
            IUserReportsRepo        userReportsRepo        = new UserReportsRepo(dataGateway, connectionString);
            IUserProfileRepository  userProfileRepository  = new UserProfileRepository(dataGateway, connectionString);
            IUserProfileService     userProfileService     = new UserProfileService(userProfileRepository);
            IUserAccountService     userAccountService     = new UserAccountService(userAccountRepository);
            IValidationService      validationService      = new ValidationService(userAccountService, userProfileService);
            IUserInteractionService userInteractionService = new UserInteractionService(friendBlockListRepo, friendListRepo, friendRequestListRepo, userReportsRepo, validationService);

            await userInteractionService.CreateFriendRequestAsync(1, 2);

            int avarageFriends = await userAnalysisService.FriendRequest_GivenDay(DateTimeOffset.UtcNow);

            if (avarageFriends != 1)
            {
                Assert.IsTrue(false);
            }
            Assert.IsTrue(true);
        }
Ejemplo n.º 17
0
        internal static UserProfileService GetUserProfileService(string profileSiteUrl, string sPoAuthUserName, string sPoAuthPassword)
        {
            try
            {
                string webServiceExt      = "_vti_bin/userprofileservice.asmx";
                string adminWebServiceUrl = string.Empty;

                adminWebServiceUrl = $"{profileSiteUrl.TrimEnd('/')}/{webServiceExt}";

                LogMessage("Initializing SPO web service " + adminWebServiceUrl, EventLogEntryType.Information, ServiceEventID.SharePointOnlineError);

                SecureString securePassword            = GetSecurePassword(sPoAuthPassword);
                SharePointOnlineCredentials onlineCred = new SharePointOnlineCredentials(sPoAuthUserName, securePassword);
                string          authCookie             = onlineCred.GetAuthenticationCookie(new Uri(profileSiteUrl));
                CookieContainer authContainer          = new CookieContainer();
                authContainer.SetCookies(new Uri(profileSiteUrl), authCookie);
                var userProfileService = new UserProfileService();
                userProfileService.Url             = adminWebServiceUrl;
                userProfileService.CookieContainer = authContainer;
                return(userProfileService);
            }
            catch (Exception ex)
            {
                LogMessage("Error initiating connection to profile web service in SPO " + ex.Message, EventLogEntryType.Error, ServiceEventID.SharePointOnlineError);
                return(null);
            }
        }
Ejemplo n.º 18
0
        public IHttpActionResult GetUserByUserId()
        {
            UserProfileService userProfileService = CreateUserProfileService();
            UserProfileDisplay profileDisplay     = userProfileService.GetUserByUserId();

            return(Ok(profileDisplay));
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Optimizely constructor for managing Full Stack .NET projects.
        /// </summary>
        /// <param name="datafile">string JSON string representing the project</param>
        /// <param name="eventDispatcher">EventDispatcherInterface</param>
        /// <param name="logger">LoggerInterface</param>
        /// <param name="errorHandler">ErrorHandlerInterface</param>
        /// <param name="skipJsonValidation">boolean representing whether JSON schema validation needs to be performed</param>
        /// <param name="eventProcessor">EventProcessor</param>
        public Optimizely(string datafile,
                          IEventDispatcher eventDispatcher = null,
                          ILogger logger                        = null,
                          IErrorHandler errorHandler            = null,
                          UserProfileService userProfileService = null,
                          bool skipJsonValidation               = false,
                          EventProcessor eventProcessor         = null)
        {
            try {
                InitializeComponents(eventDispatcher, logger, errorHandler, userProfileService, null, eventProcessor);

                if (ValidateInputs(datafile, skipJsonValidation))
                {
                    var config = DatafileProjectConfig.Create(datafile, Logger, ErrorHandler);
                    ProjectConfigManager = new FallbackProjectConfigManager(config);
                }
                else
                {
                    Logger.Log(LogLevel.ERROR, "Provided 'datafile' has invalid schema.");
                }
            } catch (Exception ex) {
                string error = String.Empty;
                if (ex.GetType() == typeof(ConfigParseException))
                {
                    error = ex.Message;
                }
                else
                {
                    error = "Provided 'datafile' is in an invalid format. " + ex.Message;
                }

                Logger.Log(LogLevel.ERROR, error);
                ErrorHandler.HandleError(ex);
            }
        }
Ejemplo n.º 20
0
 public Randomator()
 {
     _dataManager           = new DataManager();
     _addressService        = new AddressService(_dataManager, _randomNumberGenerator);
     _userProfileService    = new UserProfileService();
     _randomNumberGenerator = new RandomNumberGenerator();
 }
Ejemplo n.º 21
0
        protected async override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            SetContentView(Resource.Layout.activity_home);

            toolbar = FindViewById <Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(toolbar);
            SupportActionBar.Title = "User List";

            setDialog();
            _recyclerView = FindViewById <RecyclerView>(Resource.Id.usersProfileRecyclerView);
            users         = await UserProfileService.GetUsersProfile();

            _adapter = new UserAdapter(users);
            _adapter.iItemClickListner = this;

            _recyclerView.SetLayoutManager(new LinearLayoutManager(Application.Context));
            _recyclerView.SetAdapter(_adapter);

            if (users != null)
            {
                dialog.Dismiss();
            }
        }
Ejemplo n.º 22
0
        private UserProfileService CreateUserProfileService()
        {
            var userId  = Guid.Parse(User.Identity.GetUserId());
            var service = new UserProfileService(userId);

            return(service);
        }
        public async Task ChangeProfilePictureAsync_EditPhoto_PhotoSuccessfullyEdited(int userId, string photo)
        {
            IDataGateway              dataGateway              = new SQLServerGateway();
            IConnectionStringData     connectionString         = new ConnectionStringData();
            IPublicUserProfileRepo    publicUserProfileRepo    = new PublicUserProfileRepo(dataGateway, connectionString);
            IUserAccountRepository    userAccountRepository    = new UserAccountRepository(dataGateway, connectionString);
            IUserProfileRepository    userProfileRepository    = new UserProfileRepository(dataGateway, connectionString);
            IUserProfileService       userProfileService       = new UserProfileService(userProfileRepository);
            IUserAccountService       userAccountService       = new UserAccountService(userAccountRepository);
            IValidationService        validationService        = new ValidationService(userAccountService, userProfileService);
            IPublicUserProfileService publicUserProfileService = new PublicUserProfileService(publicUserProfileRepo, validationService);
            PublicUserProfileModel    model = new PublicUserProfileModel();


            try
            {
                model.UserId = userId;
                await publicUserProfileService.CeatePublicUserProfileAsync(model);

                model.Photo = photo;
                await publicUserProfileService.ChangeProfilePictureAsync(model);

                Assert.IsTrue(true);
            }
            catch
            {
                Assert.IsTrue(false);
            }
        }
Ejemplo n.º 24
0
 public SitesController()
 {
     areasService       = new AreasService();
     groupService       = new GroupService();
     userProfileService = new UserProfileService();
     sitesService       = new SitesService();
 }
        public async Task GetUserProfileAsync_UserProfileGot_SuccessfulRecieved(int userId)
        {
            IDataGateway              dataGateway              = new SQLServerGateway();
            IConnectionStringData     connectionString         = new ConnectionStringData();
            IPublicUserProfileRepo    publicUserProfileRepo    = new PublicUserProfileRepo(dataGateway, connectionString);
            IUserAccountRepository    userAccountRepository    = new UserAccountRepository(dataGateway, connectionString);
            IUserProfileRepository    userProfileRepository    = new UserProfileRepository(dataGateway, connectionString);
            IUserProfileService       userProfileService       = new UserProfileService(userProfileRepository);
            IUserAccountService       userAccountService       = new UserAccountService(userAccountRepository);
            IValidationService        validationService        = new ValidationService(userAccountService, userProfileService);
            IPublicUserProfileService publicUserProfileService = new PublicUserProfileService(publicUserProfileRepo, validationService);

            PublicUserProfileModel model = new PublicUserProfileModel();

            model.UserId = userId;

            try
            {
                await publicUserProfileService.CeatePublicUserProfileAsync(model);

                Assert.IsTrue(true);
            }
            catch
            {
                Assert.IsTrue(false);
            }
        }
        public async Task UpdateProfileAgeAsync_UpdateValue_ValueUpdated(int userId, int age)
        {
            IDataGateway              dataGateway              = new SQLServerGateway();
            IConnectionStringData     connectionString         = new ConnectionStringData();
            IPublicUserProfileRepo    publicUserProfileRepo    = new PublicUserProfileRepo(dataGateway, connectionString);
            IUserAccountRepository    userAccountRepository    = new UserAccountRepository(dataGateway, connectionString);
            IUserProfileRepository    userProfileRepository    = new UserProfileRepository(dataGateway, connectionString);
            IUserProfileService       userProfileService       = new UserProfileService(userProfileRepository);
            IUserAccountService       userAccountService       = new UserAccountService(userAccountRepository);
            IValidationService        validationService        = new ValidationService(userAccountService, userProfileService);
            IPublicUserProfileService publicUserProfileService = new PublicUserProfileService(publicUserProfileRepo, validationService);
            PublicUserProfileModel    model = new PublicUserProfileModel();

            model.UserId = userId;
            try
            {
                await publicUserProfileService.CeatePublicUserProfileAsync(model);

                model.Age = age;

                await publicUserProfileService.UpdateProfileAgeAsync(model);

                Assert.IsTrue(true);
            }
            catch
            {
                Assert.IsTrue(false);
            }
        }
        // GET
        public IHttpActionResult GetUserProfilesById(int id)
        {
            UserProfileService userProfileService = CreateUserProfileService();
            var profiles = userProfileService.GetUserProfilesById(id);

            return(Ok(profiles));
        }
        private async Task <Tuple <RequestResult <UserProfileModel>, UserProfileModel> > ExecuteInsertUserProfile(Database.Constants.DBStatusCode dbResultStatus, string registrationStatus, MessagingVerification messagingVerification = null)
        {
            UserProfile userProfile = new UserProfile
            {
                HdId = hdid,
                AcceptedTermsOfService = true,
                Email = "*****@*****.**"
            };

            UserProfileModel expected = UserProfileModel.CreateFromDbModel(userProfile);

            Mock <IUserProfileDelegate> profileDelegateMock = new Mock <IUserProfileDelegate>();

            profileDelegateMock.Setup(s => s.InsertUserProfile(It.Is <UserProfile>(x => x.HdId == userProfile.HdId))).Returns(new DBResult <UserProfile>
            {
                Payload = userProfile,
                Status  = DBStatusCode.Created
            });

            Mock <IConfigurationService> configServiceMock = new Mock <IConfigurationService>();

            configServiceMock.Setup(s => s.GetConfiguration()).Returns(new ExternalConfiguration()
            {
                WebClient = new WebClientConfiguration()
                {
                    RegistrationStatus = registrationStatus
                }
            });

            Mock <ICryptoDelegate> cryptoDelegateMock = new Mock <ICryptoDelegate>();

            cryptoDelegateMock.Setup(s => s.GenerateKey()).Returns("abc");

            Mock <INotificationSettingsService> notificationServiceMock = new Mock <INotificationSettingsService>();

            notificationServiceMock.Setup(s => s.QueueNotificationSettings(It.IsAny <NotificationSettingsRequest>()));

            IUserProfileService service = new UserProfileService(
                new Mock <ILogger <UserProfileService> >().Object,
                new Mock <IPatientService>().Object,
                new Mock <IUserEmailService>().Object,
                new Mock <IUserSMSService>().Object,
                configServiceMock.Object,
                new Mock <IEmailQueueService>().Object,
                notificationServiceMock.Object,
                profileDelegateMock.Object,
                new Mock <IUserPreferenceDelegate>().Object,
                new Mock <ILegalAgreementDelegate>().Object,
                new Mock <IMessagingVerificationDelegate>().Object,
                cryptoDelegateMock.Object,
                new Mock <IHttpContextAccessor>().Object);

            RequestResult <UserProfileModel> actualResult = await service.CreateUserProfile(new CreateUserRequest()
            {
                Profile = userProfile
            }, DateTime.Today);

            return(new Tuple <RequestResult <UserProfileModel>, UserProfileModel>(actualResult, expected));
        }
Ejemplo n.º 29
0
        public async Task GetUserProfile_GetsProfile_ProfileGetSuccess(int userId, string description, string job, string goals, int age, string gender, string ethnicity, string sexualOrientation, string height, string visibility, string status, string photo, string intrests, string hobbies)
        {
            IDataGateway              dataGateway              = new SQLServerGateway();
            IConnectionStringData     connectionString         = new ConnectionStringData();
            IPublicUserProfileRepo    publicUserProfileRepo    = new PublicUserProfileRepo(dataGateway, connectionString);
            IUserAccountRepository    userAccountRepository    = new UserAccountRepository(dataGateway, connectionString);
            IUserProfileRepository    userProfileRepository    = new UserProfileRepository(dataGateway, connectionString);
            IUserProfileService       userProfileService       = new UserProfileService(userProfileRepository);
            IUserAccountService       userAccountService       = new UserAccountService(userAccountRepository);
            IValidationService        validationService        = new ValidationService(userAccountService, userProfileService);
            IPublicUserProfileService publicUserProfileService = new PublicUserProfileService(publicUserProfileRepo, validationService);

            PublicUserProfileManager publicUserProfileManager = new PublicUserProfileManager(publicUserProfileService);

            PublicUserProfileModel model = new PublicUserProfileModel();

            model.UserId = userId;

            try
            {
                await publicUserProfileManager.CeatePublicUserProfileAsync(model);

                model.Description       = description;
                model.Jobs              = job;
                model.Goals             = goals;
                model.Age               = age;
                model.Gender            = gender;
                model.Ethnicity         = ethnicity;
                model.SexualOrientation = sexualOrientation;
                model.Height            = height;
                model.Status            = status;
                model.Photo             = photo;
                model.Intrests          = intrests;
                model.Hobbies           = hobbies;

                await publicUserProfileManager.EditPublicUserProfileAsync(model);


                PublicUserProfileModel profile = await publicUserProfileManager.GetUserProfileAsync(userId);

                if (profile == null)
                {
                    Assert.IsTrue(false);
                }

                if (profile.Description == description && profile.Hobbies == hobbies && profile.Jobs == job && profile.Goals == goals && profile.Age == age && profile.Gender == gender && profile.Ethnicity == ethnicity && profile.SexualOrientation == sexualOrientation && profile.Height == height && profile.Visibility == visibility && profile.Intrests == intrests)
                {
                    Assert.IsTrue(true);
                }
                else
                {
                    Assert.IsTrue(false);
                }
            }
            catch
            {
                Assert.IsTrue(false);
            }
        }
Ejemplo n.º 30
0
 /// <summary>
 ///  Initialize a decision service for the Optimizely client.
 /// </summary>
 /// <param name = "bucketer" > Base bucketer to allocate new users to an experiment.</param>
 /// <param name = "errorHandler" > The error handler of the Optimizely client.</param>
 /// <param name = "projectConfig" > Optimizely Project Config representing the datafile.</param>
 /// <param name = "userProfileService" ></ param >
 /// < param name= "logger" > UserProfileService implementation for storing user info.</param>
 public DecisionService(Bucketer bucketer, IErrorHandler errorHandler, ProjectConfig projectConfig, UserProfileService userProfileService, ILogger logger)
 {
     Bucketer           = bucketer;
     ErrorHandler       = errorHandler;
     ProjectConfig      = projectConfig;
     UserProfileService = userProfileService;
     Logger             = logger;
 }
Ejemplo n.º 31
0
        public int DeleteProfiles(List<UserProfile> Profiles)
        {
            IUserProfileService _service = new UserProfileService(_SessionFactoryConfigPath);
            int ret = 0;
            foreach (UserProfile _profile in Profiles)
            {
                if (_profile.ProfileID > 0)
                {
                    try
                    {
                        _service.Delete(_profile);
                        ret++;
                    }
                    catch (Exception ex) { }
                }
            }

            _service.CommitChanges();
            return ret;
        }
Ejemplo n.º 32
0
 public UserController(LookupService lookupService, UserProfileService userProfileService)
 {
     _lookupService = lookupService;
     _userProfileService = userProfileService;
 }
 public ServiceProviderController(LookupService lookupService, UserProfileService userProfileService, ServiceProviderService serviceProviderService)
 {
     _lookupService = lookupService;
     _serviceProviderService = serviceProviderService;
     _userProfileService = userProfileService;
 }