public void SetBusinessUnit(PAUser user, Guid buId) { var currentUser = ContextContainer.GetValue <ICurrentUserInfoContext>(ContextTypes.CurrentUser); Entity updateUser = new Entity("systemuser"); updateUser.Id = user.EntityRecord.Id; updateUser["businessunitid"] = new EntityReference("businessunit", buId); var orgService = ContextContainer.GetValue <IOrganizationService>(ContextTypes.OrgService); try { orgService.Update(updateUser); } catch { SetBusinessSystemUserRequest request = new SetBusinessSystemUserRequest(); request.UserId = user.EntityRecord.Id; request.BusinessId = buId; //var administrator = _configurationService.GetAdministratorID(); request.ReassignPrincipal = currentUser.GetUserID(); orgService.Execute(request); } }
private void SetCrmUserBusinessUnit(Guid userId, Guid businessUnitId) { var request = new SetBusinessSystemUserRequest() { ReassignPrincipal = new EntityReference("systemuser", userId), UserId = userId, BusinessId = businessUnitId }; _client.Execute(request); }
public void AssignBusinessUnit(EntityReference userToChange, EntityReference userToCopy) { Entity userToCopy_ent = service.Retrieve("systemuser", userToCopy.Id, new ColumnSet("businessunitid")); // Create the request object. SetBusinessSystemUserRequest user = new SetBusinessSystemUserRequest(); // Set the properties of the request object. user.BusinessId = ((EntityReference)userToCopy_ent.Attributes["businessunitid"]).Id; //SecurityPrincipal assignee = new SecurityPrincipal(); //assignee.PrincipalId = new Guid("59727AF6-09A0-DB11-BEB5-0013727B635D"); user.ReassignPrincipal = new EntityReference("systemuser", new Guid("5CDD7FF1-CD73-E611-A14E-EACD0C285D01")); user.UserId = userToChange.Id; // Execute the request. SetBusinessSystemUserResponse assigned = (SetBusinessSystemUserResponse)service.Execute(user); }
/// <summary> /// Change <c>Business Unit</c> of specified <c>System User</c>. /// <para> /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.setbusinesssystemuserrequest(v=crm.8).aspx /// </para> /// </summary> /// <param name="userId"><c>System User</c> Id</param> /// <param name="businessUnitId">New <c>Business Unit</c> id</param> /// <param name="reassignedUserId"> /// Target <c>SystemUser</c> to which the instances of entities previously owned by the user are to be assigned. /// If you do not want to re-assign it, you can set <c>null</c> or <see cref="Guid.Empty"/>. In this case the records will remain on the current owner (specified <c>SystemUser</c> on <paramref name="userId"/>) /// </param> public void ChangeBusinessUnit(Guid userId, Guid businessUnitId, Guid?reassignedUserId = null) { ExceptionThrow.IfGuidEmpty(userId, "userId"); ExceptionThrow.IfGuidEmpty(businessUnitId, "businessUnitId"); Guid principalId = userId; if (reassignedUserId.HasValue) { ExceptionThrow.IfGuidEmpty(reassignedUserId.Value, "reassignedUserId"); ExceptionThrow.IfEquals(reassignedUserId.Value, "reassignedUserId", userId); principalId = reassignedUserId.Value; } SetBusinessSystemUserRequest request = new SetBusinessSystemUserRequest() { BusinessId = businessUnitId, UserId = userId, ReassignPrincipal = new EntityReference(this.EntityName, principalId) }; this.OrganizationService.Execute(request); }
private void ImportAndAddButton_Click(object sender, EventArgs e) { ResultTextBox.Text = string.Empty; if (TeamBusinessUnitSelectionOptionset.SelectedIndex == -1)//Nothing selected { MessageBox.Show("Please select Team ", "Error"); return; } progressBar1.Minimum = 0; progressBar1.Maximum = 100; progressBar1.Value = 10; List <ProcessCSV> listA = new List <ProcessCSV>(); string Location = FileLocationTextBox.Text; using (var reader = new System.IO.StreamReader(Location)) { while (!reader.EndOfStream) { var line = reader.ReadLine(); var values = line.Split(','); listA.Add(new ProcessCSV { emailuser = values[0] }); progressBar1.Value = 20; } progressBar1.Value = 30; } string text = string.Empty; int userCount = 0; progressBar1.Minimum = 0; progressBar1.Maximum = 100; EntityCollection UserEmails = new EntityCollection(); var fetchXml = "<fetch>" + "<entity name='systemuser'>" + "<filter>" + "<condition attribute='domainname' operator='in'>"; foreach (ProcessCSV email in listA) { userCount++; progressBar1.Value = 40; if (userCount > 200) { MessageBox.Show("This tool can process only first 200 Records"); //System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=""JavaScript"">alert("Hello this is an Alert")</SCRIPT>"); goto BreakLoop; } fetchXml += "<value>" + email.emailuser + "</value>"; } BreakLoop: //timer1.Interval = userCount; fetchXml += "</condition>" + "</filter>" + "</entity>" + "</fetch> "; EntityCollection userCollection = new EntityCollection(); try { userCollection = Service.RetrieveMultiple(new FetchExpression(fetchXml)); } catch (Exception ex) { progressBar1.Value = 10; throw new InvalidPluginExecutionException(ex.Message + "As you have provided Invalid CSV file"); } try { progressBar1.Value = 50; // MessageBox.Show(userCollection.Entities.Count.ToString()); string ResultedString = "Below Users are Added Sucessfully to " + TeamBusinessUnitSelectionOptionset.Text + " " + System.Environment.NewLine; Guid[] members = new Guid[userCollection.Entities.Count]; if (AssignmentcomboBox.SelectedIndex == 0) { if (checkbox == true && userCollection.Entities.Count > 0) { progressBar1.Value = 70; // Instantiate QueryExpression QEsystemuser var QEsystemuser = new QueryExpression("systemuser"); // Add columns to QEsystemuser.ColumnSet QEsystemuser.ColumnSet.AddColumns("systemuserid"); // Add link-entity QEsystemuser_teammembership var QEsystemuser_teammembership = QEsystemuser.AddLink("teammembership", "systemuserid", "systemuserid"); // Define filter QEsystemuser_teammembership.LinkCriteria QEsystemuser_teammembership.LinkCriteria.AddCondition("teamid", ConditionOperator.Equal, teamToBeassign); EntityCollection usersToBeremoveCollection = Service.RetrieveMultiple(QEsystemuser); Guid[] removeMembers = new Guid[usersToBeremoveCollection.Entities.Count]; for (int i = 0; i < usersToBeremoveCollection.Entities.Count; i++) { removeMembers[i] = (Guid)usersToBeremoveCollection.Entities[i].Attributes["systemuserid"]; } // Create the AddMembersTeamRequest object. RemoveMembersTeamRequest addRequest2 = new RemoveMembersTeamRequest(); // Set the AddMembersTeamRequest TeamID property to the object ID of // an existing team. addRequest2.TeamId = EntityToBeassign; // Set the AddMembersTeamRequest MemberIds property to an // array of GUIDs that contains the object IDs of one or more system users. addRequest2.MemberIds = removeMembers; // Execute the request. Service.Execute(addRequest2); } //timer1.Start(); if (userCount == userCollection.Entities.Count || userCount == 201) { for (int i = 0; i < userCollection.Entities.Count; i++) { progressBar1.Value = 60; //MessageBox.Show(userCollection.Entities[i].Id.ToString()); members[i] = (Guid)userCollection.Entities[i].Attributes["systemuserid"]; //MessageBox.Show(i.ToString()); ResultedString += (userCollection.Entities[i].Attributes["fullname"]).ToString().ToUpper() + "" + System.Environment.NewLine; // textBox1.Text += (Guid)userCollection.Entities[i].Attributes["systemuserid"]; } if (EntityToBeassign != Guid.Empty && members.Length != 0) { progressBar1.Value = 90; // Create the AddMembersTeamRequest object. AddMembersTeamRequest addRequest = new AddMembersTeamRequest(); // Set the AddMembersTeamRequest TeamID property to the object ID of // an existing team. addRequest.TeamId = EntityToBeassign; // Set the AddMembersTeamRequest MemberIds property to an // array of GUIDs that contains the object IDs of one or more system users. addRequest.MemberIds = members; // Execute the request. Service.Execute(addRequest); progressBar1.Value = 100; ResultTextBox.Text = ResultedString; MessageBox.Show("Task completed Sucessfully", "sucess"); // progressBar1.ForeColor = Color.Black; } } else { progressBar1.Value = 10; MessageBox.Show("Task Could Not Be completed (Please check csv file)", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); //progressBar1.ForeColor= Color.Black; } } else { if (userCount == userCollection.Entities.Count || userCount == 201) { if (EntityToBeassign != Guid.Empty && members.Length != 0) { foreach (Entity user in userCollection.Entities) { progressBar1.Value = 90; SetBusinessSystemUserRequest changeUserBURequest = new SetBusinessSystemUserRequest(); changeUserBURequest.BusinessId = EntityToBeassign; changeUserBURequest.UserId = user.Id; changeUserBURequest.ReassignPrincipal = new EntityReference("systemuser", user.Id); Service.Execute(changeUserBURequest); } for (int i = 0; i < userCollection.Entities.Count; i++) { progressBar1.Value = 60; //MessageBox.Show(userCollection.Entities[i].Id.ToString()); members[i] = (Guid)userCollection.Entities[i].Attributes["systemuserid"]; //MessageBox.Show(i.ToString()); ResultedString += (userCollection.Entities[i].Attributes["fullname"]).ToString().ToUpper() + "" + System.Environment.NewLine; } progressBar1.Value = 100; ResultTextBox.Text = ResultedString; MessageBox.Show("Task completed Sucessfully", "sucess"); // progressBar1.ForeColor = Color.Black; } } else { progressBar1.Value = 10; MessageBox.Show("Task Could Not Be completed (Please check csv file)", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); //progressBar1.ForeColor= Color.Black; } } //timer1.Start(); // MessageBox.Show("TaskCompleted total "+userCount+" users are added to "+TeamSelectorOptionset.Text); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void syncRoles_Click(object sender, EventArgs e) { Guid sourceUserId = new Guid(Source.SelectedValue.ToString()); Guid targetUserId = new Guid(Target.SelectedValue.ToString()); Exception er = null; WorkAsync(new WorkAsyncInfo { Message = "Syncing Security Roles from Source to Target...", Work = (w, ar) => { // This code is executed in another thread try { List <Guid> sourceRoleIds; Guid SourceBuId; GetUserRoles(sourceUserId, out sourceRoleIds, out SourceBuId); List <Guid> targetRoleIds; Guid targetBuId; GetUserRoles(targetUserId, out targetRoleIds, out targetBuId); if (SourceBuId == targetBuId) { EntityReferenceCollection targetRoleCollection = new EntityReferenceCollection(); foreach (var tr in targetRoleIds) { targetRoleCollection.Add(new EntityReference("role", tr)); } //clear all the sec roles of target user Service.Disassociate( "systemuser", targetUserId, new Relationship("systemuserroles_association"), targetRoleCollection); } else { SetBusinessSystemUserRequest request = new SetBusinessSystemUserRequest(); request.BusinessId = SourceBuId; request.UserId = targetUserId; request.ReassignPrincipal = new EntityReference("systemuser", targetUserId); SetBusinessSystemUserResponse response = (SetBusinessSystemUserResponse)Service.Execute(request); } //Adding Bu and Roles to the target user EntityReferenceCollection roleCollection = new EntityReferenceCollection(); foreach (var r in sourceRoleIds) { roleCollection.Add(new EntityReference("role", r)); } Service.Associate("systemuser", targetUserId, new Relationship("systemuserroles_association"), roleCollection); //Remove Old Teams from Targer User List <Guid> targetUserTeamIds = GetUserTeams(targetUserId, Service); Guid[] targetUser = new Guid[] { targetUserId }; foreach (Guid team in targetUserTeamIds) { RemoveMembersFromTeam(team, targetUser, Service); } //Adding teams from Source users to Target user List <Guid> teamIds = GetUserTeams(sourceUserId, Service); foreach (Guid team in teamIds) { AddMembersToTeam(team, targetUser, Service); } } catch (Exception ex) { er = ex; } }, PostWorkCallBack = ar => { if (er != null) { MessageBox.Show(er.Message); } else { MessageBox.Show($"Security Roles synced."); } }, AsyncArgument = null, // Progress information panel size MessageWidth = 340, MessageHeight = 150 }); }