public async Task Create_ReturnsViewResult() { // Arrange GetUserAsyncReturns = user1; Profile testProfile = new Profile { ProfileId = 1, UserId = user1.Id }; _context.Add(testProfile); UserRelationship testRelationship = new UserRelationship { UserRelationshipId = 1, RelatingUser = user1, RelatedUser = user2, RelatingProfile = testProfile, RelatedProfile = testProfile, Type = Relationship.Friend }; _context.Add(testRelationship); await _context.SaveChangesAsync(); // Act var result = await ControllerSUT.Create(testRelationship.UserRelationshipId); // Assert Assert.IsAssignableFrom <ViewResult>(result); }
public async Task <Unit> Handle(Command command, CancellationToken cancellationToken) { var appUser = await _databaseContext.Users.SingleOrDefaultAsync(x => x.UserName == _userAccessor.GetCurrentUsername()); var userToFollow = await _databaseContext.Users.SingleOrDefaultAsync(x => x.UserName == command.Username); if (userToFollow == null) { throw new RESTException(HttpStatusCode.NotFound, new { UserToFollow = "Not found" }); } var userRelationship = await _databaseContext.UserRelationships .SingleOrDefaultAsync(x => x.FollowerId == appUser.Id && x.UserFollowedId == userToFollow.Id); if (userRelationship == null) { userRelationship = new UserRelationship { Follower = appUser, UserFollowed = userToFollow, }; _databaseContext.UserRelationships.Add(userRelationship); } var attemptTofollowIsSuccessful = await _databaseContext.SaveChangesAsync() > 0; if (attemptTofollowIsSuccessful) { return(Unit.Value); } throw new Exception("Problem while attempting to follow user"); }
public ActionResult Create([Bind(Include = "Id,Subject,CourseNumber,Section,Title,StartDate,EndDate,Location,Term")] Course course) { course.CreatedById = User.Identity.GetUserId(); course.isActive = true; ModelState.Clear(); TryValidateModel(course); var errors = ModelState.Values.SelectMany(v => v.Errors); if (ModelState.IsValid) { UserRelationship _UserRelationship = new UserRelationship() { AccountId = course.CreatedById, AccountRole = CourseRole.owner, CreatedBy = User.Identity.GetUserId() }; db.UserRelationships.Add(_UserRelationship); course.UserRelationships.Add(_UserRelationship); db.Courses.Add(course); db.Users.Find(User.Identity.GetUserId()).Courses.Add(course); db.SaveChanges(); return(RedirectToAction("Index", "Home", new { area = "" })); } return(View(course)); }
public FavouriteStatus Set(int id) { FavouriteStatus status = new FavouriteStatus { Status = false }; if (User.Identity.IsAuthenticated) { string uid = User.Identity.GetUserId(); using (PixurfDBContext db = new PixurfDBContext()) { Favourite favourite = db.Favourites.FirstOrDefault(f => f.User_ID == uid && f.Content_ID == id); Content content = db.Contents.Find(id); if (content != null) { UserRelationship userRelationship = new UserRelationship(); if ((content.User_ID == uid) || (userRelationship.Following(content.User_ID, uid) && content.Access != "Private") || (!userRelationship.Blocked(content.User_ID, uid) && content.Access == "Public")) { if (favourite != null) { db.Favourites.Remove(favourite); try { db.SaveChanges(); status.Status = false; } catch (Exception e) { Console.WriteLine(e); status.Status = true; } } else { db.Favourites.Add(new Favourite { Content = content, User_ID = uid, Creation_Date = DateTime.Now }); try { db.SaveChanges(); status.Status = true; } catch (Exception e) { Console.WriteLine(e); } } } } } } return(status); }
public UserConnectionModel(FriendRequestStatus?status, long?id, bool isRequestRecived) { Id = id; if (status.HasValue) { switch (status.Value) { case FriendRequestStatus.Accept: Type = UserRelationship.Friends; Id = null; break; case FriendRequestStatus.Reject: Type = UserRelationship.None; Id = null; break; case FriendRequestStatus.None: Type = isRequestRecived ? UserRelationship.FriendRequestReceived : UserRelationship.FriendRequestSent; break; default: throw new ArgumentOutOfRangeException(); } } else { Type = UserRelationship.None; } }
public ActionResult Enroll(EnrollViewModel model) { if (ModelState.IsValid) { if (!db.Courses.Any(obj => obj.RegistrationCode.Equals(model.RegistrationCode))) { ModelState.AddModelError("RegistrationCode", "Invalid Registration Code"); return(View(model)); } Course course = db.Courses.Where(obj => obj.RegistrationCode.Equals(model.RegistrationCode)).FirstOrDefault(); if (course.UserRelationships.Any(c => c.AccountId.Equals(User.Identity.GetUserId()))) { ModelState.AddModelError("RegistrationCode", "You can have already register for this course."); return(View(model)); } UserRelationship _UserRelationship = new UserRelationship() { AccountId = User.Identity.GetUserId(), AccountRole = CourseRole.student, CourseId = course.Id, CreatedBy = User.Identity.GetUserId() }; db.UserRelationships.Add(_UserRelationship); course.UserRelationships.Add(_UserRelationship); db.Users.Find(User.Identity.GetUserId()).Courses.Add(course); db.SaveChanges(); return(RedirectToAction("Details", new { id = course.Id })); } return(View(model)); }
public UserConnectionModel(int?status, long?requestId) { if (status.HasValue) { Id = requestId; switch (status.Value) { case 0: Type = UserRelationship.FriendRequestSent; break; case 1: Type = UserRelationship.Friends; Id = null; break; case 2: Type = UserRelationship.FriendRequestReceived; break; case -1: Type = UserRelationship.None; Id = null; break; default: break; } } else { Type = UserRelationship.None; } }
public async Task <IActionResult> AddUsername([FromForm] string username) { if (string.IsNullOrWhiteSpace(username)) { ModelState.AddModelError("username", $"Username is required"); return(View()); } User user = await _userManager.GetUserAsync(User); if (user == null) { return(Problem()); } User userInviting = await _userManager.FindByNameAsync(username); if (userInviting == null) { ModelState.AddModelError("username", $"No results found matching \"{username}\""); return(View()); } else if (userInviting.Id == user.Id) { ModelState.AddModelError("username", "Cannot invite yourself"); return(View()); } TempData["FriendInvite"] = $"A friend invite was sent to {userInviting.UserName}."; // friend relationship (or invite) already exists if (await _context.UserRelationships.AnyAsync(r => r.RelatingUserId == user.Id && r.RelatedUserId == userInviting.Id)) { return(RedirectToAction(nameof(Index))); } var relationship = new UserRelationship { RelatingUserId = user.Id, RelatedUserId = userInviting.Id, Type = Relationship.Pending, }; // friend has already sent relationship invite - add them as a friend without invite var existingRelationship = await _context.UserRelationships.FirstOrDefaultAsync(r => r.RelatingUserId == userInviting.Id && r.RelatedUserId == user.Id); if (existingRelationship != null) { existingRelationship.Type = Relationship.Friend; _context.UserRelationships.Update(existingRelationship); relationship.Type = Relationship.Friend; TempData["FriendInvite"] = $"{userInviting.UserName} has been added to your friends."; } _context.UserRelationships.Add(relationship); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); }
// Promotes a user to manager status private async Task <IActionResult> PromoteUser(User user, User admin) { // Checks to see if relation between admin and user exists var relationship = await(from ur in _context.UserRelationships where ur.UserAId == user.Id && ur.UserBId == admin.Id && ur.UserBSuperior select ur).FirstOrDefaultAsync(); // if it does not exist, create one if (relationship == null) { // Creates record to link the new manager and the admin var newRelationship = new UserRelationship() { UserAId = user.Id, UserBId = admin.Id, UserBSuperior = true }; _context.UserRelationships.Add(newRelationship); } // Promotes account type to manager user.AccountType = 1; try { await _context.SaveChangesAsync(); } catch (Exception) { throw; } return(NoContent()); }
public BizUserRelationship(UserRelationship dataInfo) { UserRelationshipID = dataInfo.UserRelationshipID; FollowerID = dataInfo.FollowerID; BeFollwedUID = dataInfo.BeFollwedUID; IsMutuallyFollwe = dataInfo.IsMutuallyFollwe; CreateTime = dataInfo.CreateTime; }
/// ----------------------------------------------------------------------------- /// <summary> /// DeleteFriend - Initiating User deletes a friend relationship with the target User /// </summary> /// <param name="initiatingUser">UserInfo for Initiating User</param> /// <param name="targetUser">UserInfo for Target User</param> /// ----------------------------------------------------------------------------- public void DeleteFriend(UserInfo initiatingUser, UserInfo targetUser) { Requires.NotNull("user1", initiatingUser); UserRelationship friend = RelationshipController.Instance.GetUserRelationship(initiatingUser, targetUser, RelationshipController.Instance.GetFriendsRelationshipByPortal(initiatingUser.PortalID)); RelationshipController.Instance.DeleteUserRelationship(friend); }
public void Update(UserRelationship userRelationship) { var currentUserRelationShip = GetForID(userRelationship.ID); if (currentUserRelationShip != null) { _healthyEntities.Entry(currentUserRelationShip).CurrentValues.SetValues(userRelationship); _healthyEntities.SaveChanges(); } }
public async Task<IActionResult> Create([Bind("ID,UserID,FriendID,Accepted")] UserRelationship userRelationship) { if (ModelState.IsValid) { _context.Add(userRelationship); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(userRelationship); }
public async Task <IActionResult> CreateOrg(CreateOrgViewModel model) { var user = await GetCurrentUserAsync(); if (!ModelState.IsValid) { model.ModelStateValid = false; model.Recover(user); return(View(model)); } // Ensure no org with the same name. if (await _dbContext.Organizations.AnyAsync(t => t.DisplayName.ToLower() == model.OrganizationName.ToLower())) { ModelState.AddModelError("", $"There is already an organization with name: '{model.OrganizationName.ToLower()}'"); model.ModelStateValid = false; model.Recover(user); return(View(model)); } // Ensure site can be created. try { await _sitesService.CreateNewSiteAsync(await accesstoken, model.OrganizationSiteName, true, true); } catch (AiurUnexceptedResponse e) { ModelState.AddModelError(string.Empty, e.Response.Message); model.ModelStateValid = false; model.Recover(user); return(View(model)); } // Create org. var newOrg = new Organization { DisplayName = model.OrganizationName, Description = model.OrganizationDescription, SiteName = model.OrganizationSiteName }; _dbContext.Organizations.Add(newOrg); await _dbContext.SaveChangesAsync(); var newRelation = new UserRelationship { OrganizationId = newOrg.Id, UserId = user.Id }; _dbContext.UserRelationships.Add(newRelation); await _dbContext.SaveChangesAsync(); return(RedirectToAction(nameof(OrgHome), new OrgHomeAddressModel { OrgName = model.OrganizationName })); }
private List <Content> GetViewableContents(string ownerId) { List <Content> contents = new List <Content>(); string viewerId = ""; if (User.Identity.IsAuthenticated) { viewerId = User.Identity.GetUserId(); } using (PixurfDBContext db = new PixurfDBContext()) { if (viewerId.IsNullOrWhiteSpace()) { //Only the public contents contents = db.Contents.Where(a => a.User_ID == ownerId && a.Access == "Public" && a.Status == 1).Take(4).ToList(); } else { User viewer = db.Users.Find(viewerId); if (viewer != null) { if (viewer.Admin) { contents = db.Contents.Where(a => a.User_ID == ownerId).Take(4).ToList(); } else if (viewer.User_ID == ownerId) { contents = db.Contents.Where(a => a.User_ID == ownerId && a.Status == 1).Take(4).ToList(); } else { //Handle followers UserRelationship relationship = new UserRelationship(); if (relationship.Following(ownerId, viewerId)) { contents = db.Contents .Where(a => a.User_ID == ownerId && a.Status == 1 && (a.Access == "Public" || a.Access == "Follower")).Take(4).ToList(); } else { contents = db.Contents .Where(a => a.User_ID == ownerId && a.Status == 1 && a.Access == "Public").Take(4).ToList(); } } } } } return(contents); }
/// <summary> /// 把DataRow转换成Model /// </summary> public UserRelationship ToModel(MySqlDataReader dr) { UserRelationship userRelationship = new UserRelationship(); userRelationship.UserRelationshipID = (long)ToModelValue(dr, "UserRelationshipID"); userRelationship.FollowerID = (long)ToModelValue(dr, "FollowerID"); userRelationship.BeFollwedUID = (long)ToModelValue(dr, "BeFollwedUID"); userRelationship.IsMutuallyFollwe = (int)ToModelValue(dr, "IsMutuallyFollwe"); userRelationship.CreateTime = (DateTime)ToModelValue(dr, "CreateTime"); return(userRelationship); }
private FriendModel ConvertFriendEntity(UserFriendEntity friend, UserRelationship relationship) { return(new FriendModel { Id = friend.user.id, Nickname = GetUserNickname(friend), Tag = friend.user.tag, AvatarUrl = friend.user.picture, Status = friend.IsOnline() ? UserOnlineStatus.Online : UserOnlineStatus.Offline, Relationship = relationship }); }
public string AddUserFromModeal(AddUserToCourse model) { if (ModelState.IsValid) { if (db.Courses.ToList().Any(obj => obj.UserRelationships.Any(u => u.IsActive && u.AccountId.Equals(model.AccountId)))) { //user is in course already Response.StatusCode = 400; return("User is already part of this course"); } if (db.Courses.ToList().Any(obj => obj.UserRelationships.Any(u => u.AccountId.Equals(User.Identity.GetUserId()) && u.AccountRole == CourseRole.owner))) { UserRelationship _UserRelationship; if (db.Courses.Find(model.CourseId).UserRelationships.Any(obj => obj.AccountId == model.AccountId && !obj.IsActive)) { _UserRelationship = db.Courses.Find(model.CourseId).UserRelationships.Where(obj => obj.AccountId == model.AccountId && !obj.IsActive).ToList()[0]; _UserRelationship.IsActive = true; _UserRelationship.ModifiedDate = DateTime.Now; _UserRelationship.ModifedBy = User.Identity.GetUserId(); db.SaveChanges(); } else { _UserRelationship = new UserRelationship() { AccountId = model.AccountId, AccountRole = (CourseRole)model.AccountRole, CreateDate = DateTime.Now, CreatedBy = User.Identity.GetUserId(), Course = db.Courses.Find(model.CourseId) }; db.UserRelationships.Add(_UserRelationship); db.Courses.Find(model.CourseId).UserRelationships.Add(_UserRelationship); db.Users.Find(model.AccountId).Courses.Add(db.Courses.Find(model.CourseId)); var errors = ModelState.Values.SelectMany(v => v.Errors); db.SaveChanges(); } Response.StatusCode = 200; return("User " + db.Users.Find(model.AccountId).UserName + " has been added."); } else { Response.StatusCode = 403; return("You can not make changes to this course"); } } Response.StatusCode = 400; return("All values are required"); }
public ActionResult Delete(UserRelationship model) { using (MyDBContext dc = new MyDBContext()) { var v = dc.UserRelationship.Where(a => a.Id == model.Id).FirstOrDefault(); if (v != null) { dc.UserRelationship.Remove(v); dc.SaveChanges(); } } return(View("Index")); }
public async Task <IActionResult> Create([Bind("Id,RelatingUserId,RelatedUserId,RequestStatus,RelationshipStatus,DateOfRequest,DateOfAcceptance")] UserRelationship userRelationship) { if (ModelState.IsValid) { _context.Add(userRelationship); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["RelatedUserId"] = new SelectList(_context.User, "Id", "Email", userRelationship.RelatedUserId); ViewData["RelatingUserId"] = new SelectList(_context.User, "Id", "Email", userRelationship.RelatingUserId); return(View(userRelationship)); }
public ActionResult Edit(UserRelationship model) { try { _userRelationshipRepository.Update(model); return(RedirectToAction("UserProfile", "Account")); } catch (Exception ex) { ModelState.AddModelError("error", String.Format("Cannot Edit User Realtionship Because {0}", ex.Message)); } return(View()); }
//[Route("api/{controller}/follow/{action}/{id}")] public RelationStatus Get(string id) { RelationStatus status = new RelationStatus { Type = RelationStatus.Follow }; if (User.Identity.IsAuthenticated && !id.IsNullOrWhiteSpace()) { string uid = User.Identity.GetUserId(); UserRelationship userRelationship = new UserRelationship(); status.Status = userRelationship.Following(id, uid); } return(status); }
public async Task <UserDto> CreateAsync(ChildInfoDto dto) { var child = await CreateUserAsync(dto, async (entity) => { var relationShip = new UserRelationship { UserId1 = UserId, User1Level = RelationshipLevel.Father, UserId2 = entity.Id, User2Level = RelationshipLevel.Son }; _unitOfWork.UserRelationshipRepository.Add(relationShip); await _unitOfWork.CommitAsync(); }); return(child); }
public void MapMixed() { var relationship = new UserRelationship { Owner = new User(), Child = new User() }; var relationshipProjected = _expander.Expand <UserRelationshipMixedProjection>(relationship); relationshipProjected.ShouldNotBeNull(); relationshipProjected.Owner.ShouldNotBeNull(); relationshipProjected.Owner.Name.ShouldBe(TestName); relationshipProjected.Child.ShouldNotBeNull(); relationshipProjected.Child.Email.ShouldBe(TestEmail); }
public void MapDefault() { var relationship = new UserRelationship { Owner = new User(), Child = new User() }; var relationshipProjected = _expander.Expand(relationship, null, includes: "[Owner]") as UserRelationship; relationshipProjected.ShouldNotBeNull(); relationshipProjected.Owner.ShouldNotBeNull(); relationshipProjected.Owner.Name.ShouldBe(TestName); relationshipProjected.Owner.Email.ShouldBe(TestEmail); relationshipProjected.Child.ShouldBeNull(); }
public void SetUserState(UserRelationship relationship) { switch (relationship) { case UserRelationship.Unknown: { SetUserState(UserState.Initial); break; } case UserRelationship.Friend: { SetUserState(UserState.MyFriend); break; } case UserRelationship.Pending: { SetUserState(UserState.Pending); break; } case UserRelationship.Requested: { SetUserState(UserState.Requested); break; } case UserRelationship.Blocked: { SetUserState(UserState.Blocked); break; } case UserRelationship.SocialNonXsolla: { SetUserState(UserState.SocialNonXsolla); break; } default: { Debug.LogException(new ArgumentOutOfRangeException(nameof(relationship), relationship, null)); break; } } }
internal ProfilePanel( ProfilePage page, string zuneTag, Category profilePivot, Guid playlistTrack, int chosenSortFriends, string selectedFriendTag) : base(page) { this._zuneTag = zuneTag; this._selectedPivot = profilePivot; this._relationshipToSignedInUser = UserRelationship.Unknown; this._chosenIndexSortFriends = chosenSortFriends; this._selectedFriendTag = selectedFriendTag; this._selectedPlaylistTrack = playlistTrack; this._canChangeSelectedItem = true; }
public ActionResult AcceptFriendRequests(string fromId) { var usr = User.Identity.GetUserId(); var req = db.UserRelationships.Where(a => a.ToUserId == usr && a.FromUserId == fromId).FirstOrDefault(); UserRelationship newReq = new UserRelationship(); newReq.ToUserId = req.ToUserId; newReq.FromUserId = req.FromUserId; newReq.RelationshipType = "accepted"; db.UserRelationships.Add(newReq); db.UserRelationships.Remove(req); db.SaveChanges(); return(RedirectToAction("Requests")); }
public async Task <ActionResult <UserRelationship> > PostManagedMember(UserRelationship userRelationship) { // Checks if the record already exists within the Db var result = await(from mm in _context.UserRelationships where mm.UserAId == userRelationship.UserAId && mm.UserBId == userRelationship.UserBId && mm.UserBSuperior == userRelationship.UserBSuperior select mm).FirstOrDefaultAsync(); // Checks that user and superior exists // could be simplified if API knows who's making the call var user1 = await _context.Users.FindAsync(userRelationship.UserAId); var user2 = await _context.Users.FindAsync(userRelationship.UserBId); if (user1 == null || user2 == null) { return(BadRequest()); } if (result == null) { if (user1.AccountType != user2.AccountType) { if (user1.AccountType > user2.AccountType) { var temp = userRelationship.UserAId; userRelationship.UserAId = userRelationship.UserBId; userRelationship.UserBId = temp; } userRelationship.UserBSuperior = true; } else { userRelationship.UserBSuperior = false; } _context.UserRelationships.Add(userRelationship); await _context.SaveChangesAsync(); return(CreatedAtAction("GetManagedMember", userRelationship)); } else { return(NoContent()); } }
public ActionResult Stumble() { using (PixurfDBContext db = new PixurfDBContext()) { if (User.Identity.IsAuthenticated) { string userId = User.Identity.GetUserId(); UserRelationship relationship = new UserRelationship(); List <string> followedPeoplesId = relationship.GetFollowedPeoplesId(userId); List <Content> contents = db.Contents.Where(c => //c.User_ID != userId && (c.Access == "Public" || (followedPeoplesId.Contains(c.User_ID) && (c.Access != "Public" || c.Access != "Follower")))) .OrderBy(c => Guid.NewGuid()).Take(1).ToList(); if (contents.Count > 0) { int contentId = contents[0].Content_ID; return(RedirectToAction("View", "Content", new { id = contentId })); } } else { List <Content> contents = db.Contents.Where(c => c.Access == "Public").OrderBy(c => Guid.NewGuid()).Take(1).ToList(); if (contents.Count > 0) { int contentId = contents[0].Content_ID; return(RedirectToAction("View", "Content", new { id = contentId })); } } //Error Report StatusReport report = new StatusReport { Title = "Error", Description = "Something went wrong. Please try again", Status = StatusReport.Warning }; List <StatusReport> reports = new List <StatusReport>(); reports.Add(report); Session["Reports"] = reports; return(RedirectToAction("Index", "Home")); } }
private void AddFriendRequestNotification(UserInfo initiatingUser, UserInfo targetUser, UserRelationship userRelationship) { var notificationType = NotificationsController.Instance.GetNotificationType(FriendRequest); var subject = string.Format(Localization.GetString("AddFriendRequestSubject", Localization.GlobalResourceFile), initiatingUser.DisplayName); var body = string.Format(Localization.GetString("AddFriendRequestBody", Localization.GlobalResourceFile), initiatingUser.DisplayName); var notification = new Notification { NotificationTypeID = notificationType.NotificationTypeId, Subject = subject, Body = body, IncludeDismissAction = true, Context = userRelationship.UserRelationshipId.ToString(CultureInfo.InvariantCulture), SenderUserID = initiatingUser.UserID }; NotificationsController.Instance.SendNotification(notification, initiatingUser.PortalID, null, new List<UserInfo> { targetUser }); }