Пример #1
0
        public void Put(int profileId, ProfileDTO data, IFormFile avatar)
        {
            var path = "#";

            if (ModelState.IsValid || true)
            {
                if (avatar != null)
                {
                    path = Path.Combine(_env.WebRootPath, "avatars", avatar.FileName);
                    using (var stream = avatar.OpenReadStream())
                    {
                        var buffer = new byte[stream.Length];
                        stream.Read(buffer, 0, buffer.Length);
                        System.IO.File.WriteAllBytes(path, buffer);
                    }
                    if (System.IO.File.Exists(path))
                    {
                        data.AvatarSrc = "avatars/" + avatar.FileName;
                    }
                }

                var result = _profileService.UpdateProfile(profileId, data) != null;
                if (result)
                {
                    Response.StatusCode = 200;
                    return;
                }
                else
                {
                    Response.StatusCode = 500;
                    return;
                }
            }
            else
            {
                Response.StatusCode = 400;
                return;
            }
        }
Пример #2
0
        public void TestInviteAFriend_DuplicateInvitation()
        {
            ProfileDTO          inviter = (ProfileDTO)profiles[0].Tag;
            ProfileDTO          invited = (ProfileDTO)profiles[1].Tag;
            FriendInvitationDTO result  = null;

            SessionData data = CreateNewSession(inviter, ClientInformation);

            RunServiceMethod(delegate(InternalBodyArchitectService Service)
            {
                //result = Service.InviteFriendOperation(data.Token, invited, InviteFriendOperation.Invite);
                var arg       = new InviteFriendOperationData();
                arg.User      = invited;
                arg.Operation = InviteFriendOperation.Invite;
                result        = Service.InviteFriendOperation(data.Token, arg);
            });
            Assert.IsNotNull(result);
            Assert.AreEqual(InvitationType.Invite, result.InvitationType);
            int count = Session.QueryOver <FriendInvitation>().RowCount();

            Assert.AreEqual(1, count);
            //we send invitation second time - in the database still should be one invitation

            RunServiceMethod(delegate(InternalBodyArchitectService Service)
            {
                //result = Service.InviteFriendOperation(data.Token, invited, InviteFriendOperation.Invite);
                var arg       = new InviteFriendOperationData();
                arg.User      = invited;
                arg.Operation = InviteFriendOperation.Invite;
                result        = Service.InviteFriendOperation(data.Token, arg);
            });
            Assert.IsNull(result);
            count = Session.QueryOver <FriendInvitation>().RowCount();
            Assert.AreEqual(1, count);
            var invitation = Session.QueryOver <FriendInvitation>().SingleOrDefault();

            Assert.IsNotNull(invitation);
            Assert.AreEqual(FriendInvitationType.Invite, invitation.InvitationType);
        }
Пример #3
0
        public async Task <IActionResult> Get(string email)
        {
            if (email != null)
            {
                string userId = _userRepo.GetUserIdFromEmail(email);
                if (userId != null)
                {
                    Profile profile = _profileRepo.Get(userId);

                    ProfileDTO profDTO = new ProfileDTO
                    {
                        Alias       = profile.Alias,
                        Avatar      = profile.Avatar,
                        Description = profile.Description,
                        Email       = email,
                        ImageURLs   = profile.Images.Select(i => i.Path).ToArray()
                    };
                    return(Ok(profDTO));
                }
            }
            return(NotFound());
        }
Пример #4
0
        public void GetProfile_NotNullAvatar()
        {
            //Arrange
            var             mock = new Mock <IUserRepository>();
            ApplicationUser user = new ApplicationUser {
                UserProfile = new UserProfile {
                    AvatarName = "MyAvatar"
                }
            };

            mock.Setup(a => a.GetUserById(1)).Returns(user);
            ProfileService service = new ProfileService(mock.Object);

            service.AvatarFolder = "C:\\SomeFolder";
            string expected = "C:\\SomeFolder\\MyAvatar";

            //Act
            ProfileDTO profile = service.GetProfile(1);

            //Accert
            Equals(expected, profile.AvatarPath);
        }
        public async Task <IActionResult> GetProfile([FromQuery] GetProfileDTO getProfileDTO)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest());
                }
                var user  = userManager.Users.FirstOrDefault(u => u.Email == getProfileDTO.Email);
                var roles = await userManager.GetRolesAsync(user);

                var roleId = await roleManager.FindByNameAsync(roles.SingleOrDefault());

                if (roleId.Id == getProfileDTO.Role.ToString())
                {
                    var res = new ProfileDTO
                    {
                        Email           = user.Email,
                        FirstName       = user.FirstName,
                        LastName        = user.LastName,
                        Role            = getProfileDTO.Role,
                        Gender          = user.Gender,
                        DateOfBirth     = user.DateOfBirth,
                        PhoneNumber     = user.PhoneNumber,
                        LinkedInProfile = user.LinkedInProfile,
                        Status          = user.Status,
                        Experience      = user.Experience
                    };
                    // return newly formatted data as -- res
                    return(Created("getUser",
                                   new { Message = "User data obtained successfully!", user = res }));
                }
                return(NotFound(getProfileDTO));
            }
            catch (Exception e)
            {
                throw;
            }
        }
        public void TestDeleteProfile_BlogEntry()
        {
            ProfileDTO  profile1 = (ProfileDTO)profiles[0].Tag;
            SessionData data     = SecurityManager.CreateNewSession(profile1, ClientInformation);

            var count = Session.QueryOver <BlogEntry>().RowCount();

            Assert.AreEqual(1, count);
            count = Session.QueryOver <BlogComment>().RowCount();
            Assert.AreEqual(2, count);
            var list = Session.QueryOver <BlogComment>().List();

            RunServiceMethod(delegate(InternalBodyArchitectService service)
            {
                service.DeleteProfile(data.Token, profile1);
            });

            count = Session.QueryOver <BlogEntry>().RowCount();
            Assert.AreEqual(0, count);
            count = Session.QueryOver <BlogComment>().RowCount();
            Assert.AreEqual(0, count);
        }
        public void RemoveFromFavorites_DataInfo_Refresh()
        {
            var plan = CreatePlan(Session, profiles[0], "plan1");

            //now add plan to favorites
            profiles[1].FavoriteWorkoutPlans.Add(plan);
            insertToDatabase(profiles[1]);
            var         oldHash  = profiles[0].DataInfo.WorkoutPlanHash;
            ProfileDTO  profile1 = (ProfileDTO)profiles[1].Tag;
            SessionData data     = CreateNewSession(profile1, ClientInformation, new LoginData());

            RunServiceMethod(delegate(InternalBodyArchitectService Service)
            {
                var param           = new WorkoutPlanOperationParam();
                param.WorkoutPlanId = plan.GlobalId;
                param.Operation     = SupplementsCycleDefinitionOperation.RemoveFromFavorites;
                Service.WorkoutPlanOperation(data.Token, param);
            });
            var dbProfile = Session.Get <Profile>(profile1.GlobalId);

            Assert.AreNotEqual(dbProfile.DataInfo.WorkoutPlanHash, oldHash);
        }
Пример #8
0
 /// <summary>Gets the profile by user identifier.</summary>
 /// <param name="prof">The profile.</param>
 /// <returns>ProfileDTO.</returns>
 public ProfileDTO GetProfileByUserId(ProfileDTO prof)
 {
     try
     {
         var profile = Database.Profiles.GetAll().Select(b =>
                                                         new ProfileDTO()
         {
             ProfileId = b.ProfileId,
             FirstName = b.FirstName,
             LastName  = b.LastName,
             UserName  = b.UserName,
             IsBlocked = b.IsBlocked,
             PhotosDTO = b.Photos,
             Role      = b.Role
         }).SingleOrDefault(b => b.ProfileId == prof.ProfileId);
         return(profile);
     }
     catch (NullReferenceException)
     {
         return(new ProfileDTO());
     }
 }
Пример #9
0
        public void TestMapExercises_PrivateToGlobal()
        {
            createStrengthEntry(DateTime.Now, profiles[0], "t4");
            createStrengthEntry(DateTime.Now.AddDays(1), profiles[0], "t3");
            createStrengthEntry(DateTime.Now.AddDays(2), profiles[0], "t1");
            createStrengthEntry(DateTime.Now.AddDays(3), profiles[0], "t4", "t1");


            ProfileDTO  profile1 = (ProfileDTO)profiles[0].Tag;
            SessionData data     = SecurityManager.CreateNewSession(profile1, ClientInformation);

            MapperData mapperData = new MapperData();

            mapperData.Entries.Add(new MapperEntry(exercises["t4"].GlobalId, exercises["t1"].GlobalId));
            RunServiceMethod(delegate(InternalBodyArchitectService service)
            {
                service.MapExercises(data.Token, mapperData);
            });
            Assert.AreEqual(0, Session.QueryOver <StrengthTrainingItem>().Where(x => x.ExerciseId == exercises["t4"].GlobalId).RowCount());
            Assert.AreEqual(1, Session.QueryOver <StrengthTrainingItem>().Where(x => x.ExerciseId == exercises["t3"].GlobalId).RowCount());
            Assert.AreEqual(4, Session.QueryOver <StrengthTrainingItem>().Where(x => x.ExerciseId == exercises["t1"].GlobalId).RowCount());
        }
Пример #10
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName    = model.Email,
                    Email       = model.Email,
                    PhoneNumber = model.PhoneNumber
                };
                var profile = new ProfileDTO
                {
                    FirstName = model.FirstName,
                    LastName  = model.LastName
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    profile.Id = user.Id;
                    _profileService.Create(profile);
                    _profileService.SaveChanges();

                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return(RedirectToAction("Index", "Home"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Пример #11
0
        async void EditProfile()
        {
            try
            {
                var imageBase64 = string.Empty;
                if (this._file != null)
                {
                    var imageArray = Helpers.FileHelper.ReadFully(this._file.GetStream());
                    imageBase64 = Convert.ToBase64String(imageArray);
                }
                var userID     = Helpers.Settings.UserID;
                var profileDTO = new ProfileDTO
                {
                    UserID = userID,
                    Image  = imageBase64,
                    Ext    = "jpg"
                };


                var responseDTO = await _apiService.RequestAPI <ResponseDTO>(Endpoints.URL_BASE_UNIVERSITY_AUTH,
                                                                             Helpers.Endpoints.PROFILE,
                                                                             profileDTO,
                                                                             ApiService.Method.Post,
                                                                             true);

                if (responseDTO.Code == 200)
                {
                    await Application.Current.MainPage.DisplayAlert(Languages.Notification, Languages.ProcessSuccessfull, Languages.Accept);
                }
                else
                {
                    await Application.Current.MainPage.DisplayAlert(Languages.Notification, responseDTO.Message, Languages.Accept);
                }
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert(Languages.Notification, ex.Message, Languages.Accept);
            }
        }
        public void RegisterNewProfile_WithValidExistingModel_Returns_ConflictResult()
        {
            // Arrange
            var profileServiceMock = new Mock <IProfileService>();

            profileServiceMock.Setup(service => service
                                     .RegisterNewProfileAsync(It.IsAny <ProfileDTO>()))
            .Returns(Task.FromResult((new Guid(), false)));

            var loggerMock = new Mock <ILogger>();

            loggerMock.Setup(c => c.Warning(It.IsAny <string>()));

            var controller = new ProfilesController(profileServiceMock.Object, loggerMock.Object);
            var profileDTO = new ProfileDTO();

            // Act
            var result = controller.RegisterNewProfile(profileDTO).GetAwaiter().GetResult();

            // Assert
            var conflictObjectResult = Assert.IsType <ConflictObjectResult>(result);
        }
Пример #13
0
        /// <inheritdoc/>
        public async Task <bool> UpdateProfileAsync(ProfileDTO profileDTO)
        {
            var profile = await _profileContext.Profiles.FirstOrDefaultAsync(p => p.Id == profileDTO.Id);

            if (profile == null)
            {
                return(false);
            }

            profile.FirstName  = profileDTO.FirstName;
            profile.LastName   = profileDTO.LastName;
            profile.MiddleName = profileDTO.MiddleName;
            profile.BirthDate  = profileDTO.BirthDate;
            profile.Gender     = profileDTO.Gender;
            profile.Height     = profileDTO.Height;
            profile.Weight     = profileDTO.Weight;

            _profileContext.Update(profile);
            await _profileContext.SaveChangesAsync(new CancellationToken());

            return(true);
        }
Пример #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public ResponseDTO <bool> EditProfileImage(ProfileDTO obj)
        {
            ResponseDTO <bool> response = new ResponseDTO <bool>();
            var foundProfile            = (from user in db.Credentials
                                           join profile in db.UserProfiles
                                           on user.UserID equals profile.UserID
                                           where user.UserName == obj.UserName
                                           select profile).FirstOrDefault();

            if (foundProfile == null)
            {
                // Return failure in responseDTO
                response.IsSuccessful = false;
                return(response);
            }
            using (var dbTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    foundProfile.ProfilePicture = obj.ProfilePicture;
                    // Saves changes
                    db.SaveChanges();
                    // Commits if works
                    dbTransaction.Commit();
                    // Inform other layer that it succeeded
                    response.IsSuccessful = true;
                    return(response);
                }
                catch (Exception)
                {
                    // undo any changes if errors
                    dbTransaction.Rollback();
                    // Inform other layer about failure
                    response.IsSuccessful = false;
                    return(response);
                }
            }
        }
Пример #15
0
        public async Task LoginReq(string username, string password)
        {
            User u = await _dataService.Login(username, password);

            if (u != null)
            {
                var tokenHandler    = new JwtSecurityTokenHandler();
                var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
                var securekey       = new SymmetricSecurityKey(key);
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.NameIdentifier, u.Id),
                        new Claim(ClaimTypes.Name, u.UserName)
                    }),
                    Expires            = DateTime.UtcNow.AddDays(7),
                    SigningCredentials = new SigningCredentials(securekey, SecurityAlgorithms.HmacSha256Signature)
                };
                var token       = tokenHandler.CreateToken(tokenDescriptor);
                var tokenString = tokenHandler.WriteToken(token);

                // return basic user info and authentication token
                ProfileDTO p = new ProfileDTO
                {
                    username  = u.UserName,
                    interests = u.Interests,
                    languages = u.Languages,
                    favorites = u.Favorites?.Select(x => x.EventId).ToArray(),
                    token     = tokenString
                };
                await Clients.Caller.SendAsync("Login", p);
            }
            else
            {
                await Clients.Caller.SendAsync("LoginFailed");
            }
        }
        public void TestSendMessageAfterRejectInvitation()
        {
            FriendInvitationDTO result = null;

            ProfileDTO  inviter = (ProfileDTO)profiles[0].Tag;
            ProfileDTO  invited = (ProfileDTO)profiles[1].Tag;
            SessionData data    = SecurityManager.CreateNewSession(inviter, ClientInformation);

            RunServiceMethod(delegate(InternalBodyArchitectService Service)
            {
                var arg       = new InviteFriendOperationData();
                arg.User      = invited;
                arg.Operation = InviteFriendOperation.Invite;
                result        = Service.InviteFriendOperation(data.Token, arg);
            });

            data = SecurityManager.CreateNewSession(invited, ClientInformation);

            RunServiceMethod(delegate(InternalBodyArchitectService Service)
            {
                var arg       = new InviteFriendOperationData();
                arg.User      = inviter;
                arg.Operation = InviteFriendOperation.Reject;
                arg.Message   = "test msg";
                result        = Service.InviteFriendOperation(data.Token, arg);
            });

            int count = Session.QueryOver <Message>().RowCount();

            Assert.AreEqual(1, count);
            var message = Session.QueryOver <Message>().SingleOrDefault();

            Assert.AreEqual(MessageType.InvitationRejected, message.MessageType);
            Assert.AreEqual("test msg", message.Content);
            Assert.AreEqual(MessagePriority.System, message.Priority);
            Assert.AreEqual(invited.Id, message.Sender.Id);
            Assert.AreEqual(inviter.Id, message.Receiver.Id);
        }
Пример #17
0
        /*
         *      var context = new EmployeeContext();
         *      var entity = AutoMapperConfiguration.Mapper.Map<Division>(division);
         *      var result = context.Divisions.Find(division.DivisionId);
         *      if (result != null)
         *      {
         *          result.Description = entity.Description;
         *          result.DivisionInfoId = entity.DivisionInfoId;
         *          result.DivisionType = entity.DivisionType;
         *          result.Name = entity.Name;
         *          context.Entry(result).State = EntityState.Modified;
         *          context.Entry(result.DivisionType).State = EntityState.Modified;
         *          return await context.SaveChangesAsync();
         *      }
         *      else
         *      {
         *          context.Divisions.Attach(entity);
         *          context.Divisions.Add(entity);
         *
         *          var divisionId = await context.SaveChangesAsync();
         *          if (divisionId > 0)
         *          {
         *              return await Task.FromResult(entity.DivisionId);
         *          }
         *          else
         *          {
         *              return await Task.FromResult(0);
         *          }
         *      }
         */

        public async Task <bool> UpdateProfileAsync(int employeeId, ProfileDTO profile)
        {
            try
            {
                var context = new ElementContext();
                var entity  = AutoMapperConfiguration.Mapper.Map <Profile>(profile);
                var result  = context.Profiles.Find(profile.ProfileId);
                if (result != null)
                {
                    if (result.Amount != entity.Amount)
                    {
                        result.ElementInfos.Add(new ElementInfo {
                            Amount = entity.Amount, Time = DateTime.Now, EmployeeId = employeeId
                        });
                    }

                    result.Amount               = entity.Amount;
                    result.Contraction          = entity.Contraction;
                    result.Count                = entity.Count;
                    result.Description          = entity.Description;
                    result.Length               = entity.Length;
                    result.ProfileNumber        = entity.ProfileNumber;
                    result.Surface              = entity.Surface;
                    context.Entry(result).State = EntityState.Modified;
                    if (await context.SaveChangesAsync() > 0)
                    {
                        return(await Task.FromResult(true));
                    }
                }

                return(await Task.FromResult(false));
            }
            catch (Exception ex)
            {
                PrintException(ex);
                throw new FaultException(ex.Message, new FaultCode("UpdateProfileAsync"), "UpdateProfileAsync");
            }
        }
Пример #18
0
        public async Task <IActionResult> Get(int status)
        {
            if (status >= 0 && status <= 3)
            {
                string userId                = User.FindFirst(ClaimTypes.NameIdentifier).Value;
                List <Relationship> rels     = _relationshipRepo.GetRelationships(userId, status);
                List <ProfileDTO>   profsDTO = new List <ProfileDTO>();

                foreach (var rel in rels)
                {
                    Profile    prof    = new Profile();
                    ProfileDTO profDTO = new ProfileDTO();
                    if (userId == rel.User_OneId)
                    {
                        prof                = _profileRepo.Get(rel.User_TwoId);
                        profDTO.Alias       = prof.Alias;
                        profDTO.Avatar      = prof.Avatar;
                        profDTO.Email       = _userRepo.GetUserEmailFromId(rel.User_TwoId);
                        profDTO.Description = prof.Description;
                    }
                    else
                    {
                        prof                = _profileRepo.Get(rel.User_OneId);
                        profDTO.Alias       = prof.Alias;
                        profDTO.Avatar      = prof.Avatar;
                        profDTO.Email       = _userRepo.GetUserEmailFromId(rel.User_OneId);
                        profDTO.Description = prof.Description;
                    }
                    profsDTO.Add(profDTO);
                }

                return(Ok(profsDTO));
            }
            else
            {
                return(BadRequest());
            }
        }
Пример #19
0
        public async Task <OperationDetails> ChangeProfileInfo(ProfileDTO profile)
        {
            if (profile.Id == 0)
            {
                return(new OperationDetails(false, "Id field is '0'", ""));
            }

            UserProfile oldProfile = Db.ProfileRepository.GetProfileWithAllFields(profile.Id);

            if (oldProfile == null)
            {
                return(new OperationDetails(false, "Not found", ""));
            }

            oldProfile.City     = Db.CityRepository.Get(profile.CityId);
            oldProfile.Birthday = profile.Birthday;

            Db.ProfileRepository.Update(oldProfile);

            await Db.SaveAsync();

            return(new OperationDetails(true, "", ""));
        }
Пример #20
0
        public async Task <IActionResult> AddPhoto(IFormFile uploadedFile)
        {
            if (uploadedFile != null)
            {
                // путь к папке Files
                string path = "/images/" + uploadedFile.FileName;
                // сохраняем файл в папку Files в каталоге wwwroot
                using (var fileStream = new FileStream(_appEnvironment.WebRootPath + path, FileMode.Create))
                {
                    await uploadedFile.CopyToAsync(fileStream);
                }
                User user = await profileService.Find(User.Identity.Name);

                ProfileDTO profile = new ProfileDTO()
                {
                    GetUser = user
                };
                await profileService.AddPhoto(path, profile.GetUser.Profile);

                return(RedirectToAction("Profile"));
            }
            return(RedirectToAction("Index", "Home"));
        }
Пример #21
0
        /// <summary>
        /// Update existing profile
        /// </summary>
        /// <param name="id"></param>
        /// <param name="profileDTO"></param>
        public void UpdateProfileInformation(int id, ProfileDTO profileDTO)
        {
            //if profileDTO data is not valid
            if (profileDTO == null)
            {
                throw new ArgumentException(Messages.warning_CannotAddProfileWithNullInformation);
            }

            //Create a new profile entity
            var currentProfile = _profileRepository.Get(id);

            //Assign updated value to existing profile
            var updatedProfile = new Profile();

            updatedProfile.ProfileId = id;
            updatedProfile.FirstName = profileDTO.FirstName;
            updatedProfile.LastName  = profileDTO.LastName;
            updatedProfile.Email     = profileDTO.Email;
            updatedProfile.Status    = profileDTO.Status;

            //Update Profile
            updatedProfile = this.UpdateProfile(currentProfile, updatedProfile);
        }
        public void CreateDataInfo()
        {
            ProfileDTO newProfile = new ProfileDTO();

            newProfile.UserName  = "******";
            newProfile.Password  = "******";
            newProfile.Email     = "*****@*****.**";
            newProfile.Birthday  = DateTime.Now.AddYears(-20);
            newProfile.CountryId = Country.Countries[1].GeoId;
            SessionData data = null;

            RunServiceMethod(delegate(InternalBodyArchitectService service)
            {
                service.Configuration.CurrentApiKey = key;
                data = service.CreateProfile(this.ClientInformation, newProfile);
            });
            Profile dbProfile = Session.Get <Profile>(data.Profile.GlobalId);

            Assert.IsNotNull(dbProfile.DataInfo);
            var count = Session.QueryOver <DataInfo>().RowCount();

            Assert.AreEqual(1, count);
        }
Пример #23
0
        public void TestRemoveFromFavorites()
        {
            ProfileDTO  profile1 = (ProfileDTO)profiles[0].Tag;
            ProfileDTO  profile2 = (ProfileDTO)profiles[1].Tag;
            SessionData data     = SecurityManager.CreateNewSession(profile2, ClientInformation);

            RunServiceMethod(delegate(InternalBodyArchitectService Service)
            {
                Service.UserFavoritesOperation(data.Token, profile1, FavoriteOperation.Add);
            });

            RunServiceMethod(delegate(InternalBodyArchitectService Service)
            {
                Service.UserFavoritesOperation(data.Token, profile1, FavoriteOperation.Remove);
            });
            GetProfileInformationCriteria criteria = new GetProfileInformationCriteria();

            RunServiceMethod(delegate(InternalBodyArchitectService Service)
            {
                var info = Service.GetProfileInformation(data.Token, criteria);
                Assert.AreEqual(0, info.FavoriteUsers.Count);
            });
        }
        public void CreateDefaultMyPlace()
        {
            ProfileDTO newProfile = new ProfileDTO();

            newProfile.UserName  = "******";
            newProfile.Password  = "******";
            newProfile.Email     = "*****@*****.**";
            newProfile.Birthday  = DateTime.Now.AddYears(-20);
            newProfile.CountryId = Country.Countries[1].GeoId;
            SessionData data = null;

            RunServiceMethod(delegate(InternalBodyArchitectService service)
            {
                ((MockTimerService)service.Configuration.TimerService).UtcNow = DateTime.UtcNow.Date;
                service.Configuration.CurrentApiKey = key;
                data = service.CreateProfile(this.ClientInformation, newProfile);
            });
            var myPlace = Session.QueryOver <MyPlace>().Where(x => x.Profile.GlobalId == data.Profile.GlobalId).SingleOrDefault();

            Assert.IsNotNull(myPlace);
            Assert.IsTrue(myPlace.IsDefault);
            Assert.IsTrue(myPlace.IsSystem);
        }
Пример #25
0
        internal void Remove(ProfileDTO profile)
        {//remove all logged instance for this user (used for delete profile to logout all instances)
            lock (syncObject)
            {
                Cache myCache = (Cache)Cache.GetType().GetField("realCache", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(Cache);

                List <Guid> keysToRemove = new List <Guid>();
                foreach (var Item in myCache.CurrentCacheState.Values)
                {
                    CacheItem    CacheItem = (CacheItem)Item;
                    SecurityInfo val       = (SecurityInfo)CacheItem.Value;
                    if (val.SessionData.Profile.GlobalId == profile.GlobalId)
                    {
                        keysToRemove.Add(val.SessionData.Token.SessionId);
                    }
                    // do Something with them
                }
                foreach (Guid guid in keysToRemove)
                {
                    Cache.Remove(guid.ToString());
                }
            }
        }
        public void TestInviteAFriend_AlreadyFriendsException()
        {
            ProfileDTO  inviter = (ProfileDTO)profiles[0].Tag;
            ProfileDTO  invited = (ProfileDTO)profiles[1].Tag;
            SessionData data    = SecurityManager.CreateNewSession(inviter, ClientInformation);

            RunServiceMethod(delegate(InternalBodyArchitectService Service)
            {
                //Service.InviteFriendOperation(data.Token, invited, InviteFriendOperation.Invite);
                var arg       = new InviteFriendOperationData();
                arg.User      = invited;
                arg.Operation = InviteFriendOperation.Invite;
                Service.InviteFriendOperation(data.Token, arg);
            });
            //accept invitation
            data = SecurityManager.CreateNewSession(invited, ClientInformation);

            RunServiceMethod(delegate(InternalBodyArchitectService Service)
            {
                //Service.InviteFriendOperation(data.Token, inviter, InviteFriendOperation.Accept);
                var arg       = new InviteFriendOperationData();
                arg.User      = inviter;
                arg.Operation = InviteFriendOperation.Accept;
                Service.InviteFriendOperation(data.Token, arg);
            });

            //this should throw exception because those users are friends already

            RunServiceMethod(delegate(InternalBodyArchitectService Service)
            {
                //Service.InviteFriendOperation(data.Token, inviter, InviteFriendOperation.Invite);
                var arg       = new InviteFriendOperationData();
                arg.User      = inviter;
                arg.Operation = InviteFriendOperation.Invite;
                Service.InviteFriendOperation(data.Token, arg);
            });
        }
Пример #27
0
        public ProfileDTO GetProfile(Guid accountId)
        {
            var dac   = new MerchantAccountDAC();
            var agent = new MerchantProfileAgent();

            var account = dac.GetById(accountId);
            var profile = agent.GetMerchantProfile(accountId);
            var pos     = new POSDAC().GetById(account.POSId.Value);
            var country = new CountryComponent().GetById(account.CountryId);

            var result = new ProfileDTO
            {
                MerchantAccount    = account.Username,
                LastName           = profile.LastName,
                FirstName          = profile.FirstName,
                IdentityDocNo      = profile.IdentityDocNo,
                IdentityDocType    = (profile.IdentityDocType != IdentityDocType.IdentityCard && profile.IdentityDocType != IdentityDocType.Passport) ? IdentityDocType.IdentityCard : profile.IdentityDocType,
                FrontIdentityImage = profile.FrontIdentityImage,
                BackIdentityImage  = profile.BackIdentityImage,
                HandHoldWithCard   = profile.HandHoldWithCard,
                MerchantName       = account.MerchantName,
                CompanyName        = profile?.CompanyName,
                Email          = account.Email,
                Cellphone      = $"{account.PhoneCode} {account.Cellphone}",
                PosSn          = pos.Sn,
                Country        = country.Name,
                L1VerifyStatus = (int)(profile?.L1VerifyStatus ?? 0),
                L2VerifyStatus = (int)(profile?.L2VerifyStatus ?? 0),
                Address1       = profile?.Address1,
                Address2       = profile?.Address2,
                Postcode       = profile?.Postcode,
                City           = profile?.City,
                State          = profile?.State
            };

            return(result);
        }
Пример #28
0
        private string ResolveCompanionAvatar(MessageDTO message, PossibleConverstionItem conversation)
        {
            string avatarPath = null;

            ProfileDTO profileDTO = null;

            switch (conversation.MessagingCompanionType)
            {
            case MessagingCompanionType.Family:
                profileDTO = ((FamilyDTO)conversation.Companion).Members?.FirstOrDefault(m => m.Id == message.FromId);
                break;

            case MessagingCompanionType.Friend:
                profileDTO = ((ProfileDTO)conversation.Companion);
                break;

            case MessagingCompanionType.Team:
                profileDTO = ((TeamDTO)conversation.Companion).Members?.FirstOrDefault(m => m.Member.Id == message.FromId)?.Member;

                if (profileDTO == null)
                {
                    profileDTO = ((TeamDTO)conversation.Companion).CreatedBy;
                }
                break;

            case MessagingCompanionType.Group:
                profileDTO = ((GroupDTO)conversation.Companion).Members?.FirstOrDefault(m => m.Profile.Id == message.FromId).Profile;
                break;
            }

            if (profileDTO != null && profileDTO.Avatar != null)
            {
                avatarPath = profileDTO.Avatar.Url;
            }

            return(avatarPath);
        }
    //example of returning a generic action script object
    private void LoadInvoiceForUser(AMFClientRequest request)
    {
        //get the current user id, since this page is in our normal ASP.NET application
        //we have access to anything in our normal AppDomain, including our security
        //whether we our using Cookies, Sessions, etc....
        //this way we let our security mechanism handle user params and identity instead
        //of passing user id as a parameter on the wire
        string userId = Thread.CurrentPrincipal.Identity.Name;

        //create a generic action script container to return the profile of the current
        //user and the invoice requested
        ActionScriptObject aso = new ActionScriptObject();

        //again, normally you would be loading these up from another component
        ProfileDTO userProfile = new ProfileDTO();

        userProfile.Id    = userId;
        userProfile.Name  = "Current User";
        userProfile.Email = "*****@*****.**";

        //add it to the action script object
        aso.AddProperty("user", AMFDataType.AMFEnabledObject, userProfile);

        //load up an invoice
        InvoiceDTO invoice = new InvoiceDTO();

        invoice.Id = Guid.NewGuid();

        //add it to the action script object
        aso.AddProperty("invoice", AMFDataType.AMFEnabledObject, invoice);

        //add specific properties also
        aso.AddProperty("loaded", AMFDataType.Boolean, true);

        //set the response object
        request.Response = aso;
    }
Пример #30
0
        public void TestDisableSendEMailAfterRejectInvitation()
        {
            profiles[1].Settings.NotificationSocial = ProfileNotification.None;
            profiles[0].Settings.NotificationSocial = ProfileNotification.None;
            insertToDatabase(profiles[1]);
            insertToDatabase(profiles[0]);

            FriendInvitationDTO result = null;

            ProfileDTO  inviter = (ProfileDTO)profiles[0].Tag;
            ProfileDTO  invited = (ProfileDTO)profiles[1].Tag;
            SessionData data    = CreateNewSession(inviter, ClientInformation);

            RunServiceMethod(delegate(InternalBodyArchitectService Service)
            {
                var arg       = new InviteFriendOperationData();
                arg.User      = invited;
                arg.Operation = InviteFriendOperation.Invite;
                result        = Service.InviteFriendOperation(data.Token, arg);
            });

            data = CreateNewSession(invited, ClientInformation);

            RunServiceMethod(delegate(InternalBodyArchitectService Service)
            {
                var arg       = new InviteFriendOperationData();
                arg.User      = inviter;
                arg.Operation = InviteFriendOperation.Reject;
                arg.Message   = "test msg";
                result        = Service.InviteFriendOperation(data.Token, arg);
                Assert.IsFalse(((MockEmailService)Service.EMailService).EMailSent);
            });

            int count = Session.QueryOver <Message>().RowCount();

            Assert.AreEqual(0, count);
        }