public IActionResult InviteUser(UserInvitation userInvitation)
        {
            try
            {
                if (!ClientKeyIsValid())
                {
                    return(Unauthorized());
                }

                if (!UserIsAuthenticatedAndAuthorized(MethodBase.GetCurrentMethod()))
                {
                    return(Unauthorized());
                }

                var taskResults = _sendUserInvitationTask.DoTask(userInvitation);

                return(taskResults.Success ?
                       Json(taskResults) :
                       Error(taskResults.Exception));
            }
            catch (Exception e)
            {
                return(Error(e));
            }
        }
Exemple #2
0
        public async Task <UserInvitation> InviteUserAsync(InviteUserModel inviteUserModel, CancellationToken cancellationToken)
        {
            var userInvitationEntity = await this.FairplaytubeDatabaseContext.UserInvitation
                                       .Where(p => p.InvitedUserEmail == inviteUserModel.ToEmailAddress).SingleOrDefaultAsync(cancellationToken: cancellationToken);

            if (userInvitationEntity is not null)
            {
                throw new CustomValidationException($"An invitation already exists for user: {inviteUserModel.ToEmailAddress}");
            }
            var currentUserObjectId = this.CurrentUserProvider.GetObjectId();
            var currentUserEntity   = await this.FairplaytubeDatabaseContext.ApplicationUser
                                      .Where(p => p.AzureAdB2cobjectId.ToString() == currentUserObjectId).SingleAsync(cancellationToken: cancellationToken);

            userInvitationEntity = new UserInvitation()
            {
                InviteCode                = Guid.NewGuid(),
                InvitedUserEmail          = inviteUserModel.ToEmailAddress,
                InvitingApplicationUserId = currentUserEntity.ApplicationUserId,
            };
            await this.FairplaytubeDatabaseContext.UserInvitation.AddAsync(userInvitationEntity, cancellationToken : cancellationToken);

            await this.FairplaytubeDatabaseContext.SaveChangesAsync(cancellationToken : cancellationToken);

            return(userInvitationEntity);
        }
        public IActionResult AcceptInvitation(Guid uuid, UserInvitation userInvitation)
        {
            try
            {
                if (!ClientKeyIsValid())
                {
                    return(Unauthorized());
                }

                var getUserInvitationResults = _getUserInvitationTask.DoTask(uuid);

                if (getUserInvitationResults.HasException)
                {
                    return(Error(getUserInvitationResults.Exception));
                }

                if (getUserInvitationResults.HasNoData)
                {
                    return(NotFound());
                }

                userInvitation.Uuid = uuid;
                var taskResults = _acceptUserInvitationTask.DoTask(userInvitation);

                return(taskResults.Success ?
                       Json(taskResults) :
                       Error(taskResults.Exception));
            }
            catch (Exception e)
            {
                return(Error(e));
            }
        }
Exemple #4
0
        public void DeleteInvitation(int id)
        {
            UserInvitation invitation = m_UserInvitationRepository.FindById(id);

            m_UserInvitationRepository.Set().Remove(invitation);
            m_UserInvitationRepository.SaveChanges();
        }
Exemple #5
0
        public async Task <IActionResult> PutUserInvitation(int id, UserInvitation userInvitation)
        {
            if (id != userInvitation.Id)
            {
                return(BadRequest());
            }

            _context.Entry(userInvitation).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UserInvitationExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Exemple #6
0
        public async Task <ActionResult <UserInvitation> > PostUserInvitation(UserInvitation userInvitation)
        {
            _context.UserInvitation.Add(userInvitation);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetUserInvitation", new { id = userInvitation.Id }, userInvitation));
        }
Exemple #7
0
        private string ReplaceTokens(string template, UserInvitation userInvitation, Installation installation)
        {
            var replaced = _tokenService.ReplaceTokens(template, installation);

            replaced = _tokenService.ReplaceTokens(replaced, userInvitation);
            replaced = _tokenService.ReplaceTokens(replaced, userInvitation.InvitedByUser);
            replaced = _tokenService.ReplaceTokens(replaced, userInvitation.InvitedByUser.Person);

            switch (userInvitation.Type)
            {
            case UserType.SystemUser:
                if (userInvitation.Roles.HasFlag(SystemUserRoles.ArtistMember) || userInvitation.Roles.HasFlag(SystemUserRoles.ArtistManager))
                {
                    replaced = _tokenService.ReplaceTokens(replaced, userInvitation.Artist);
                }
                break;

            case UserType.PublisherAdministrator:
                replaced = _tokenService.ReplaceTokens(replaced, userInvitation.Publisher);
                break;

            case UserType.LabelAdministrator:
                replaced = _tokenService.ReplaceTokens(replaced, userInvitation.RecordLabel);
                break;
            }

            return(replaced);
        }
Exemple #8
0
        private async Task <UserInvitation> Map(IMapper mapper, CoreSettings settings, IUserInvitation innerInvitation)
        {
            UserInvitation result = mapper.Map <UserInvitation>(innerInvitation);

            result.EmailAddress = (await innerInvitation.GetEmailAddress(settings)).Address;
            return(result);
        }
        public async Task <IActionResult> OnPostAsync(UserInvitationRequest userInvitationRequest)
        {
            // Check that the current user has permissions to create the invitation.
            if (!this.User.IsInRole(Constants.DelegatedUserManagementRoles.GlobalAdmin) && !this.User.IsInRole(Constants.DelegatedUserManagementRoles.CompanyAdmin))
            {
                return(this.Unauthorized());
            }

            var userInvitation = new UserInvitation
            {
                InvitationCode = Guid.NewGuid().ToString(),
                CompanyId      = userInvitationRequest.CompanyId,
                DelegatedUserManagementRole = userInvitationRequest.DelegatedUserManagementRole,
                CreatedTime = DateTimeOffset.UtcNow,
                ExpiresTime = DateTimeOffset.UtcNow.AddHours(userInvitationRequest.ValidHours),
                CreatedBy   = this.User.FindFirst(Constants.ClaimTypes.ObjectId)?.Value
            };

            if (this.User.IsInRole(Constants.DelegatedUserManagementRoles.CompanyAdmin))
            {
                // For company admins, ensure to set the newly invited user's company to the inviting user's company.
                var userCompanyId = this.User.FindFirst(this.b2cGraphService.GetUserAttributeClaimName(Constants.UserAttributes.CompanyId))?.Value;
                userInvitation.CompanyId = userCompanyId;

                // Also ensure the invited user isn't elevated to a global admin.
                if (string.Equals(userInvitation.DelegatedUserManagementRole, Constants.DelegatedUserManagementRoles.GlobalAdmin, StringComparison.InvariantCultureIgnoreCase))
                {
                    userInvitation.DelegatedUserManagementRole = Constants.DelegatedUserManagementRoles.CompanyAdmin;
                }
            }
            await this.userInvitationRepository.CreateUserInvitationAsync(userInvitation);

            return(RedirectToPage());
        }
Exemple #10
0
        private string ReplaceTokens(string template, UserInvitation userInvitation, Installation installation)
        {
            var replaced = _tokenService.ReplaceTokens(template, installation);

            replaced = _tokenService.ReplaceTokens(replaced, userInvitation);
            replaced = _tokenService.ReplaceTokens(replaced, userInvitation.CreatedUser);
            replaced = _tokenService.ReplaceTokens(replaced, userInvitation.CreatedUser.Person);

            switch (userInvitation.Type)
            {
            case UserType.SystemUser:
                replaced = _tokenService.ReplaceTokens(replaced, userInvitation.Artist);
                break;

            case UserType.PublisherAdministrator:
                replaced = _tokenService.ReplaceTokens(replaced, userInvitation.Publisher);
                break;

            case UserType.LabelAdministrator:
                replaced = _tokenService.ReplaceTokens(replaced, userInvitation.RecordLabel);
                break;
            }

            return(replaced);
        }
        internal static UserInvitation TransformToUserInvitation(UserInvitationsTableEntity userInvitationTableEntity, string accountAtribute = null)
        {
            UserInvitation userInvitation = null;

            if (userInvitationTableEntity != null)
            {
                userInvitation = new UserInvitation
                {
                    Email         = userInvitationTableEntity.Email,
                    FirstName     = userInvitationTableEntity.FirstName,
                    LastName      = userInvitationTableEntity.LastName,
                    Role          = userInvitationTableEntity.Role,
                    InvitationKey = userInvitationTableEntity.InvitationKey,
                    Owner         = userInvitationTableEntity.Owner
                };

                if (accountAtribute != null)
                {
                    var account = AccountManager.GetAccount(accountAtribute);

                    userInvitation.AccountID      = account.AccountID.ToString();
                    userInvitation.AccountName    = account.AccountName;
                    userInvitation.AccountNameKey = account.AccountNameKey;
                    userInvitation.AccountLogoUrl = ""; //<-- To Add
                }
            }

            return(userInvitation);
        }
Exemple #12
0
        private async Task InviteUserAsync(UserDto user, Workspace workspace, string email)
        {
            if (string.IsNullOrWhiteSpace(email))
            {
                return;
            }

            var existingInvitation = await _context.UserInvitations
                                     .SingleOrDefaultAsync(ui => ui.Acceptted == false && ui.Cancelled == false &&
                                                           ui.UserEmail == email && ui.WorkspaceId == workspace.Id);

            if (existingInvitation != null)
            {
                existingInvitation.Cancel();
            }

            var newUserInvitation = new UserInvitation(email, user.Id, workspace.Id);

            _context.UserInvitations.Add(newUserInvitation);
            await _context.SaveChangesAsync();

            await _emailService.SendUserInvitationEmailAsync(new UserInvitationData {
                ReceiverAddress = email,
                InviterName     = user.DisplayName,
                InviterEmail    = user.Email,
                WorkspaceName   = workspace.Name,
                InvitationCode  = newUserInvitation.InvitationCode
            });
        }
Exemple #13
0
        public void AddParticipant(string groupName, string username)
        {
            Group        group = m_GroupRepository.Set().Where(p => p.Name == groupName).FirstOrDefault();
            UserIdentity user  = m_UserRepository.Set().Where(p => p.UserName == username).FirstOrDefault();

            if (group != null && user != null)
            {
                GroupParticipant participant = new GroupParticipant
                {
                    Group  = group,
                    User   = user,
                    Fellow = null
                };

                m_GroupParticipantRepository.Set().Add(participant);
                m_GroupParticipantRepository.SaveChanges();
            }

            UserInvitation invitation = m_UserInvitationRepository.Set().Where(p => p.Group.Name == groupName && p.User.UserName == username).FirstOrDefault();

            if (invitation != null)
            {
                m_UserInvitationRepository.Set().Remove(invitation);
                m_UserInvitationRepository.SaveChanges();
            }
        }
Exemple #14
0
        /// <summary>
        /// Invites a user to manage one or more accounts of a customer.
        /// </summary>
        /// <param name="userInvitation"></param>
        /// <returns></returns>
        private async Task <long> SendUserInvitationAsync(UserInvitation userInvitation)
        {
            var request = new SendUserInvitationRequest
            {
                UserInvitation = userInvitation
            };

            return((await Service.CallAsync((s, r) => s.SendUserInvitationAsync(r), request)).UserInvitationId);
        }
        public async Task <SendUserInvitationResponse> SendUserInvitationAsync(
            UserInvitation userInvitation)
        {
            var request = new SendUserInvitationRequest
            {
                UserInvitation = userInvitation
            };

            return(await CustomerManagementService.CallAsync((s, r) => s.SendUserInvitationAsync(r), request));
        }
Exemple #16
0
        public static UserInvitationDto MapToDto(UserInvitation source)
        {
            UserInvitationDto target = new UserInvitationDto();

            target.Id        = source.Id;
            target.Date      = source.Date;
            target.GroupName = source.Group.Name;
            target.Username  = source.User.UserName;
            return(target);
        }
        public Task <Result <string> > Create(UserInvitationData prefilledData, UserInvitationTypes invitationType,
                                              int inviterUserId, int?inviterAgencyId = null)
        {
            var invitationCode = GenerateRandomCode();
            var now            = _dateTimeProvider.UtcNow();

            return(Result.Success()
                   .Ensure(AllProvidedRolesExist, "All roles should exist")
                   .Bind(SaveInvitation)
                   .Tap(LogInvitationCreated)
                   .Map(_ => invitationCode));


            string GenerateRandomCode()
            {
                using var provider = new RNGCryptoServiceProvider();

                var byteArray = new byte[64];

                provider.GetBytes(byteArray);

                return(Base64UrlEncoder.Encode(byteArray));
            }

            async Task <bool> AllProvidedRolesExist()
            {
                var allRoleIds = await _context.AgentRoles.Select(r => r.Id).ToListAsync();

                return(prefilledData.RoleIds.All(x => allRoleIds.Contains(x)));
            }

            async Task <Result <UserInvitation> > SaveInvitation()
            {
                var newInvitation = new UserInvitation
                {
                    CodeHash         = HashGenerator.ComputeSha256(invitationCode),
                    Email            = prefilledData.UserRegistrationInfo.Email,
                    Created          = now,
                    InviterUserId    = inviterUserId,
                    InviterAgencyId  = inviterAgencyId,
                    InvitationType   = invitationType,
                    InvitationStatus = UserInvitationStatuses.Active,
                    Data             = JsonConvert.SerializeObject(prefilledData)
                };

                _context.UserInvitations.Add(newInvitation);

                await _context.SaveChangesAsync();

                return(newInvitation);
            }

            void LogInvitationCreated()
            => _logger.LogInvitationCreated(invitationType, prefilledData.UserRegistrationInfo.Email);
        }
        public async Task <IActionResult> OnGetAsync()
        {
            var allUsers = await this.b2cGraphService.GetUsersAsync();

            if (!allUsers.Any())
            {
                // If there aren't any users yet, allow anonymous access to bootstrap the initial global admin.
                var globalAdminUserInvitation = new UserInvitation
                {
                    InvitationCode = GlobalAdminInvitationCode,
                    CompanyId      = null,
                    DelegatedUserManagementRole = Constants.DelegatedUserManagementRoles.GlobalAdmin,
                    CreatedTime = DateTimeOffset.UtcNow,
                    ExpiresTime = DateTimeOffset.UtcNow.AddYears(1),
                };
                await this.userInvitationRepository.CreateUserInvitationAsync(globalAdminUserInvitation);

                this.ShowGlobalAdminUserInvitation = true;
                this.CanManageUserInvitations      = false;
            }
            else
            {
                if (!this.User.Identity.IsAuthenticated)
                {
                    // Force the user to sign in if they're not authenticated at this point.
                    return(this.Challenge());
                }
                this.ShowGlobalAdminUserInvitation = false;

                if (this.User.IsInRole(Constants.DelegatedUserManagementRoles.GlobalAdmin))
                {
                    this.CanManageUserInvitations = true;
                    this.CanSelectGlobalAdmins    = true;
                    this.CanSelectCompany         = true;
                    this.PendingUserInvitations   = await this.userInvitationRepository.GetPendingUserInvitationsAsync();;
                }
                else if (this.User.IsInRole(Constants.DelegatedUserManagementRoles.CompanyAdmin))
                {
                    this.CanManageUserInvitations = true;
                    this.CanSelectGlobalAdmins    = false;
                    this.CanSelectCompany         = false;
                    var userCompanyId = this.User.FindFirst(this.b2cGraphService.GetUserAttributeClaimName(Constants.UserAttributes.CompanyId))?.Value;
                    this.PendingUserInvitations = await this.userInvitationRepository.GetPendingUserInvitationsAsync(userCompanyId);;
                }
                else
                {
                    this.CanManageUserInvitations = false;
                }

                this.PendingUserInvitations = this.PendingUserInvitations?.OrderBy(u => u.CompanyId).ThenBy(u => u.DelegatedUserManagementRole).ToArray();
            }
            return(this.Page());
        }
Exemple #19
0
        private static void SendInvitation(UserInvitation userInvitation, User user)
        {
            using (WebClient client = new WebClient())
            {
                var    baseUrl            = ConfigurationManager.AppSettings["BaseUrl"];
                var    url                = baseUrl + "internal-email/invitation/" + userInvitation.Id;
                string inviteEmailContent = client.DownloadString(url);
                //Emailer.SendContent(user.Email, "You've been invited to Movid HEP", inviteEmailContent);

                new Emailer(null).SendEmail(EmailEnum.SendInvitation, user.Email, inviteEmailContent, 0);
            }
        }
        public IActionResult PostUserInvitation([FromRoute] int invitationid, [FromRoute] int userid, [FromBody] UserInvitation UserInvitation)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            UserInvitation.UserId       = userid;
            UserInvitation.InvitationId = invitationid;
            UserInvitation g = unit.UserInvitationManager.Insert(UserInvitation);

            return(Created("GetGameInPlace", g));
        }
Exemple #21
0
        public Task <Result <string> > Create(UserInvitationData prefilledData, int inviterUserId)
        {
            if (prefilledData.RoleIds is null || !prefilledData.RoleIds.Any())
            {
                return(Task.FromResult(Result.Failure <string>("Invitation should have role ids")));
            }

            var invitationCode   = GenerateRandomCode();
            var now              = _dateTimeProvider.UtcNow();
            var registrationInfo = prefilledData.UserRegistrationInfo;

            return(SaveInvitation()
                   .Tap(LogInvitationCreated)
                   .Map(_ => invitationCode));


            string GenerateRandomCode()
            {
                using var provider = new RNGCryptoServiceProvider();

                var byteArray = new byte[64];

                provider.GetBytes(byteArray);

                return(Base64UrlEncoder.Encode(byteArray));
            }

            async Task <Result <UserInvitation> > SaveInvitation()
            {
                var newInvitation = new UserInvitation
                {
                    CodeHash         = HashGenerator.ComputeSha256(invitationCode),
                    Email            = registrationInfo.Email,
                    Created          = now,
                    InviterUserId    = inviterUserId,
                    InvitationType   = UserInvitationTypes.Administrator,
                    InvitationStatus = UserInvitationStatuses.Active,
                    Data             = JsonConvert.SerializeObject(prefilledData)
                };

                _context.UserInvitations.Add(newInvitation);

                await _context.SaveChangesAsync();

                return(newInvitation);
            }

            void LogInvitationCreated()
            => _logger.LogInvitationCreated(UserInvitationTypes.Administrator, registrationInfo.Email);
        }
        public async Task <IActionResult> InviteAsync(int userID)
        {
            var userSpecification = new UserSpecification()
            {
                ID = userID
            };

            var user = await _userRepository.ReadAsync(userSpecification);

            var userDTO             = new UserDTO(user);
            var userInvitationEvent = new UserInvitation(userDTO);
            await _mediator.Publish(userInvitationEvent);

            return(Ok());
        }
 public void OutputUserInvitation(UserInvitation dataObject)
 {
     if (null != dataObject)
     {
         OutputStatusMessage(string.Format("Id: {0}", dataObject.Id));
         OutputStatusMessage(string.Format("FirstName: {0}", dataObject.FirstName));
         OutputStatusMessage(string.Format("LastName: {0}", dataObject.LastName));
         OutputStatusMessage(string.Format("Email: {0}", dataObject.Email));
         OutputStatusMessage(string.Format("CustomerId: {0}", dataObject.CustomerId));
         OutputStatusMessage(string.Format("RoleId: {0}", dataObject.RoleId));
         OutputArrayOfLong(dataObject.AccountIds);
         OutputStatusMessage(string.Format("ExpirationDate: {0}", dataObject.ExpirationDate));
         OutputStatusMessage(string.Format("Lcid: {0}", dataObject.Lcid));
     }
 }
Exemple #24
0
        public ApiResponse AddUser(UserPostedModel postedModel)
        {
            var existingUserWithSameEmail =
                RavenSession.Query <User>()
                .Any(x => x.AccountId == LoggedInUser.AccountId && x.Email == postedModel.Email);

            if (existingUserWithSameEmail)
            {
                return(new ApiResponse(error: "A user with this email already exists"));
            }

            var user = new User()
            {
                Name      = postedModel.Name,
                Status    = UserStatus.Invited,
                Email     = postedModel.Email,
                ClinicIds = new List <int>()
                {
                    postedModel.ClinicId
                },
                CreatedOn = DateTime.Now,
                AccountId = LoggedInUser.AccountId
            };

            RavenSession.Store(user);

            var invitation = new UserInvitation()
            {
                ClinicId = postedModel.ClinicId,
                ToUserId = user.Id,
                Created  = DateTime.Now
            };

            Ownership.Assign(invitation, this);
            invitation.ClinicId = postedModel.ClinicId;

            RavenSession.Store(invitation);
            RavenSession.SaveChanges();

            SendInvitation(invitation, user);

            return(new ApiResponse(success: "User created")
            {
                Model = user
            });
        }
Exemple #25
0
        public void Invite(string userName, string groupName)
        {
            UserIdentity user  = m_UserRepository.Set().Where(p => p.UserName == userName).FirstOrDefault();
            Group        group = m_GroupRepository.Set().Where(p => p.Name == groupName).FirstOrDefault();

            if (user != null && group != null)
            {
                UserInvitation target = new UserInvitation
                {
                    Date  = DateTime.Now,
                    User  = user,
                    Group = group
                };

                m_UserInvitationRepository.Set().Add(target);
                m_UserInvitationRepository.SaveChanges();
            }
        }
Exemple #26
0
        /// <summary>
        /// Sends an invitation for a Microsoft account user to manage one or more Bing Ads customer accounts. When the invitation is accepted, the user's Microsoft account is linked to the specified Bing Ads customer accounts. For more information about user authentication, see Managing User Authentication with OAuth.
        /// https://msdn.microsoft.com/en-US/library/bing-ads-customer-management-senduserinvitation(v=msads.90).aspx
        /// </summary>
        /// <param name="auth">Do not use ApiAuthentication directly. Use PasswordAuthentication or OAuthAuthentication derives from it instead.</param>
        /// <param name="userInvitation">The user invitation to send.
        /// https://msdn.microsoft.com/en-US/library/bing-ads-customer-management-userinvitation(v=msads.90).aspx</param>
        /// <returns>
        /// UserInvitationId: A system-generated identifier for the user invitation that was sent.</returns>
        public SendUserInvitationResponse SendUserInvitation(ApiAuthentication auth, UserInvitation userInvitation)
        {
            var request = new SendUserInvitationRequest
            {
                UserInvitation = userInvitation,
            };

            try
            {
                SetAuthHelper.SetAuth(auth, request);

                return(Check().SendUserInvitation(request));
            }
            catch (Exception ex)
            {
                Log(new LogEventArgs(ServiceType.CustomerManagement, "SendUserInvitation", ex.Message, new { Request = request }, ex));
            }

            return(null);
        }
        public ActionResult AcceptInvitation(int id)
        {
            var service = this.Service <IUserInvitationService>();

            ResponseModel <bool> response = null;

            try {
                UserInvitation invi = service.FirstOrDefaultActive(x => x.Id == id);

                invi.Accepted = true;

                service.Update(invi);

                service.Save();

                response = new ResponseModel <bool>(true, "Đã chấp nhận lời mời", null);
            } catch (Exception) {
                response = ResponseModel <bool> .CreateErrorResponse("Thao tác thất bại", systemError);
            }
            return(Json(response));
        }
        public async Task AddInviteToUser(InvitationModel model, UserData userData)
        {
            var user = await _dbContext.Users.FirstOrDefaultAsync(x => x.Id == userData.UserId);

            var userInvitations =
                await _dbContext.UserInvitations
                .Where(x => x.UserId == user.Id).Select(x => x.InvitationId)
                .ToListAsync();

            var currentInvitation =
                await _dbContext.Invitations.FirstOrDefaultAsync(x => x.InvitationCode == model.InvitationCode);

            if (currentInvitation is null)
            {
                return;
            }

            if (userInvitations.Any())
            {
                var examsId = await _dbContext.Invitations
                              .Where(x => userInvitations
                                     .Contains(x.ExamId))
                              .Select(x => x.ExamId)
                              .ToListAsync();

                if (examsId.Contains(currentInvitation.ExamId))
                {
                    return;
                }
            }

            var userInvitation = new UserInvitation
            {
                InvitationId = currentInvitation.InvitationId,
                UserId       = user.Id
            };
            await _dbContext.UserInvitations.AddAsync(userInvitation);

            await _dbContext.SaveChangesAsync();
        }
Exemple #29
0
        public async override Task RunAsync(AuthorizationData authorizationData)
        {
            try
            {
                OutputStatusMessage("You must edit this example to provide the email address (UserInviteRecipientEmail) for " +
                                    "the user invitation.");
                OutputStatusMessage("You must use Super Admin credentials to send a user invitation.\n");

                CustomerService = new ServiceClient <ICustomerManagementService>(authorizationData);

                // Prepare to invite a new user
                var userInvitation = new UserInvitation
                {
                    // The identifier of the customer this user is invited to manage.
                    // The AccountIds element determines which customer accounts the user can manage.
                    CustomerId = authorizationData.CustomerId,

                    // Users with account level roles such as Advertiser Campaign Manager can be restricted to specific accounts.
                    // Users with customer level roles such as Super Admin can access all accounts within the user’s customer,
                    // and their access cannot be restricted to specific accounts.
                    AccountIds = null,

                    // The user role, which determines the level of access that the user has to the accounts specified in the AccountIds element.
                    Role = UserRole.AdvertiserCampaignManager,

                    // The email address where the invitation should be sent. This element can contain a maximum of 100 characters.
                    Email = UserInviteRecipientEmail,

                    // The first name of the user. This element can contain a maximum of 40 characters.
                    FirstName = "FirstNameGoesHere",

                    // The last name of the user. This element can contain a maximum of 40 characters.
                    LastName = "LastNameGoesHere",

                    // The locale to use when sending correspondence to the user by email or postal mail. The default is EnglishUS.
                    Lcid = LCID.EnglishUS,
                };

                // Once you send a user invitation, there is no option to rescind the invitation using the API.
                // You can delete a pending invitation in the Accounts & Billing -> Users tab of the Bing Ads web application.
                var userInvitationId = (await SendUserInvitationAsync(userInvitation))?.UserInvitationId;
                OutputStatusMessage(string.Format("Sent new user invitation to {0}.\n", UserInviteRecipientEmail));

                // It is possible to have multiple pending invitations sent to the same email address,
                // which have not yet expired. It is also possible for those invitations to have specified
                // different user roles, for example if you sent an invitation with an incorrect user role
                // and then sent a second invitation with the correct user role. The recipient can accept
                // any of the invitations. The Bing Ads API does not support any operations to delete
                // pending user invitations. After you invite a user, the only way to cancel the invitation
                // is through the Bing Ads web application. You can find both pending and accepted invitations
                // in the Users section of Accounts & Billing.

                // Since a recipient can accept the invitation and sign into Bing Ads with a Microsoft account different
                // than the invitation email address, you cannot determine with certainty the mapping from UserInvitation
                // to accepted User. You can search by the invitation ID (returned by SendUserInvitations),
                // only to the extent of finding out whether or not the invitation has been accepted or has expired.
                // The SearchUserInvitations operation returns all pending invitations, whether or not they have expired.
                // Accepted invitations are not included in the SearchUserInvitations response.

                // This example searches for all user invitations of the customer that you manage,
                // and then filters the search results to find the invitation sent above.
                // Note: In this example the invitation (sent above) should be active and not expired. You can set a breakpoint
                // and then either accept or delete the invitation in the Bing Ads web application to change the invitation status.

                var predicate = new Predicate
                {
                    Field    = "CustomerId",
                    Operator = PredicateOperator.In,
                    Value    = authorizationData.CustomerId.ToString(CultureInfo.InvariantCulture)
                };

                var userInvitations = (await SearchUserInvitationsAsync(new[] { predicate }))?.UserInvitations;
                OutputStatusMessage("Existing UserInvitation(s):\n");
                OutputUserInvitations(userInvitations);

                // Determine whether the invitation has been accepted or has expired.
                // If you specified a valid InvitationId, and if the invitation is not found,
                // then the recipient has accepted the invitation.
                // If the invitation is found, and if the expiration date is later than the current date and time,
                // then the invitation is still pending and has not yet expired.
                var pendingInvitation = userInvitations.SingleOrDefault(invitation =>
                                                                        invitation.Id == userInvitationId &&
                                                                        DateTime.Compare(invitation.ExpirationDate.ToUniversalTime(), DateTime.UtcNow) > 0);

                // You can send a new invitation if the invitation was either not found, has expired,
                // or the user has accepted the invitation. This example does not send a new invitation if the
                // invitationId was found and has not yet expired, i.e. the invitation is pending.
                if (pendingInvitation == null)
                {
                    // Once you send a user invitation, there is no option to rescind the invitation using the API.
                    // You can delete a pending invitation in the Accounts & Billing -> Users tab of the Bing Ads web application.
                    userInvitationId = (await SendUserInvitationAsync(userInvitation))?.UserInvitationId;
                    OutputStatusMessage(string.Format("Sent new user invitation to {0}.\n", UserInviteRecipientEmail));
                }
                else
                {
                    OutputStatusMessage(string.Format("UserInvitationId {0} is pending.\n", userInvitationId));
                }

                // After the invitation has been accepted, you can call GetUsersInfo and GetUser to access the Bing Ads user details.
                // Once again though, since a recipient can accept the invitation and sign into Bing Ads with a Microsoft account
                // different than the invitation email address, you cannot determine with certainty the mapping from UserInvitation
                // to accepted User. With the user ID returned by GetUsersInfo or GetUser, you can call DeleteUser to remove the user.

                var usersInfo         = (await GetUsersInfoAsync(authorizationData.CustomerId))?.UsersInfo;
                var confirmedUserInfo = usersInfo.SingleOrDefault(info => info.UserName == UserInviteRecipientEmail);

                // If a user has already accepted an invitation, you can call GetUser to view all user details.
                if (confirmedUserInfo != null)
                {
                    var getUserResponse = (await GetUserAsync(confirmedUserInfo.Id));
                    OutputStatusMessage("Found Requested User Details (Not necessarily related to above Invitation ID(s):");
                    OutputUser(getUserResponse.User);
                    OutputStatusMessage("Role Ids:");
                    OutputStatusMessage(string.Join("; ", getUserResponse.Roles.Select(role => string.Format("{0}", role))));
                }
            }
            // Catch authentication exceptions
            catch (OAuthTokenRequestException ex)
            {
                OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description));
            }
            // Catch Customer Management AdApiFaultDetail service exceptions
            catch (FaultException <Microsoft.BingAds.V11.CustomerManagement.AdApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            // Catch Customer Management ApiFault service exceptions
            catch (FaultException <Microsoft.BingAds.V11.CustomerManagement.ApiFault> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            // Catch other .NET framework exceptions
            catch (Exception ex)
            {
                OutputStatusMessage(ex.Message);
            }
        }
Exemple #30
0
        public async override Task RunAsync(AuthorizationData authorizationData)
        {
            try
            {
                OutputStatusMessage("You must edit this example to provide the email address (UserInviteRecipientEmail) for " +
                                    "the user invitation.");
                OutputStatusMessage("You must use Super Admin credentials to send a user invitation.");

                ApiEnvironment environment = ((OAuthDesktopMobileAuthCodeGrant)authorizationData.Authentication).Environment;

                CustomerManagementExampleHelper CustomerManagementExampleHelper = new CustomerManagementExampleHelper(
                    OutputStatusMessageDefault: this.OutputStatusMessage);
                CustomerManagementExampleHelper.CustomerManagementService = new ServiceClient <ICustomerManagementService>(
                    authorizationData: authorizationData,
                    environment: environment);

                // Prepare to invite a new user
                var userInvitation = new UserInvitation
                {
                    // The identifier of the customer this user is invited to manage.
                    // The AccountIds element determines which customer accounts the user can manage.
                    CustomerId = authorizationData.CustomerId,

                    // Users with account level roles such as Advertiser Campaign Manager can be restricted to specific accounts.
                    // Users with customer level roles such as Super Admin can access all accounts within the user's customer,
                    // and their access cannot be restricted to specific accounts.
                    AccountIds = null,

                    // The user role, which determines the level of access that the user has to the accounts specified in the AccountIds element.
                    // The identifier for an advertiser campaign manager is 16.
                    RoleId = 16,

                    // The email address where the invitation should be sent.
                    Email = UserInviteRecipientEmail,

                    // The first name of the user.
                    FirstName = "FirstNameGoesHere",

                    // The last name of the user.
                    LastName = "LastNameGoesHere",

                    // The locale to use when sending correspondence to the user by email or postal mail. The default is EnglishUS.
                    Lcid = LCID.EnglishUS,
                };

                // Once you send a user invitation, there is no option to rescind the invitation using the API.
                // You can delete a pending invitation in the Accounts & Billing -> Users tab of the Microsoft Advertising web application.

                OutputStatusMessage("-----\nSendUserInvitation:");
                var userInvitationId = (await CustomerManagementExampleHelper.SendUserInvitationAsync(
                                            userInvitation: userInvitation))?.UserInvitationId;
                OutputStatusMessage(string.Format("Sent new user invitation to {0}.", UserInviteRecipientEmail));

                // It is possible to have multiple pending invitations sent to the same email address,
                // which have not yet expired. It is also possible for those invitations to have specified
                // different user roles, for example if you sent an invitation with an incorrect user role
                // and then sent a second invitation with the correct user role. The recipient can accept
                // any of the invitations. The Bing Ads API does not support any operations to delete
                // pending user invitations. After you invite a user, the only way to cancel the invitation
                // is through the Microsoft Advertising web application. You can find both pending and accepted invitations
                // in the Users section of Accounts & Billing.

                // Since a recipient can accept the invitation with credentials that differ from
                // the invitation email address, you cannot determine with certainty the mapping from UserInvitation
                // to accepted User. You can only determine whether the invitation has been accepted or has expired.
                // The SearchUserInvitations operation returns all pending invitations, whether or not they have expired.
                // Accepted invitations are not included in the SearchUserInvitations response.

                var predicate = new Predicate
                {
                    Field    = "CustomerId",
                    Operator = PredicateOperator.In,
                    Value    = authorizationData.CustomerId.ToString(CultureInfo.InvariantCulture)
                };

                OutputStatusMessage("-----\nSearchUserInvitations:");
                var userInvitations = (await CustomerManagementExampleHelper.SearchUserInvitationsAsync(
                                           predicates: new[] { predicate }))?.UserInvitations;
                OutputStatusMessage("UserInvitations:");
                CustomerManagementExampleHelper.OutputArrayOfUserInvitation(userInvitations);

                // After the invitation has been accepted, you can call GetUsersInfo and GetUser to access the Microsoft Advertising user details.
                // Once again though, since a recipient can accept the invitation with credentials that differ from
                // the invitation email address, you cannot determine with certainty the mapping from UserInvitation
                // to accepted User.

                OutputStatusMessage("-----\nGetUsersInfo:");
                var usersInfo = (await CustomerManagementExampleHelper.GetUsersInfoAsync(
                                     customerId: authorizationData.CustomerId,
                                     statusFilter: null))?.UsersInfo;
                OutputStatusMessage("UsersInfo:");
                CustomerManagementExampleHelper.OutputArrayOfUserInfo(usersInfo);

                foreach (var info in usersInfo)
                {
                    OutputStatusMessage("-----\nGetUser:"******"User:"******"CustomerRoles:");
                    CustomerManagementExampleHelper.OutputArrayOfCustomerRole(getUserResponse.CustomerRoles);
                }
            }
            // Catch authentication exceptions
            catch (OAuthTokenRequestException ex)
            {
                OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description));
            }
            // Catch Customer Management AdApiFaultDetail service exceptions
            catch (FaultException <Microsoft.BingAds.V12.CustomerManagement.AdApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            // Catch Customer Management ApiFault service exceptions
            catch (FaultException <Microsoft.BingAds.V12.CustomerManagement.ApiFault> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            // Catch other .NET framework exceptions
            catch (Exception ex)
            {
                OutputStatusMessage(ex.Message);
            }
        }