Skip to content

Commit a584c55

Browse files
committed
Added role removal in cleanup
1 parent bc6891b commit a584c55

File tree

2 files changed

+72
-62
lines changed

2 files changed

+72
-62
lines changed

dataverse/orgsvc/CSharp-NETCore/Security/AssociateSecurityRoleToUser/Program.cs

Lines changed: 68 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
using Microsoft.Crm.Sdk.Messages;
22
using Microsoft.Extensions.Configuration;
33
using Microsoft.PowerPlatform.Dataverse.Client;
4-
using Microsoft.PowerPlatform.Dataverse.Client.Utils;
54
using Microsoft.Xrm.Sdk;
65
using Microsoft.Xrm.Sdk.Query;
76
using MyApp.DataModel;
@@ -10,14 +9,67 @@ namespace PowerPlatform_Dataverse_CodeSamples
109
{
1110
internal class Program
1211
{
12+
private static Guid _userId;
13+
1314
// <AssociateSecurityRole>
1415
/// <summary>
1516
/// Associate a user with a security role.
1617
/// </summary>
1718
/// <param name="service">Authenticated web service connection.</param>
1819
/// <param name="securityRole">Dataverse security role.</param>
1920
/// <param name="user">A system user.</param>
20-
static public void AssociateSecurityRole(ServiceClient service, string securityRole, Guid user)
21+
static public void AssociateSecurityRole(IOrganizationService service, string securityRole, Guid user)
22+
{
23+
Role targetRole = GetRoleByName(service, securityRole);
24+
25+
// Associate the user with the role.
26+
if (targetRole.Id != Guid.Empty && user != Guid.Empty)
27+
{
28+
service.Associate("systemuser", user,
29+
new Relationship("systemuserroles_association"),
30+
new EntityReferenceCollection()
31+
{
32+
new EntityReference(Role.EntityLogicalName, targetRole.Id)
33+
}
34+
);
35+
}
36+
}
37+
// </AssociateSecurityRole>
38+
39+
// <DisassociateSecurityRole>
40+
/// <summary>
41+
/// Disassociate a user with a security role.
42+
/// </summary>
43+
/// <param name="service">Authenticated web service connection.</param>
44+
/// <param name="securityRole">Dataverse security role.</param>
45+
/// <param name="user">A system user.</param>
46+
static public void DisassociateSecurityRole(IOrganizationService service, string securityRole, Guid user)
47+
{
48+
Role targetRole = GetRoleByName(service, securityRole);
49+
50+
// Disassociate the user with the role.
51+
if (targetRole.Id != Guid.Empty && user != Guid.Empty)
52+
{
53+
service.Disassociate("systemuser", user,
54+
new Relationship("systemuserroles_association"),
55+
new EntityReferenceCollection()
56+
{
57+
new EntityReference(Role.EntityLogicalName, targetRole.Id)
58+
}
59+
);
60+
}
61+
}
62+
// </DisassociateSecurityRole>
63+
64+
// <GetRoleByName>
65+
/// <summary>
66+
/// Retrieve a security role using its name attribute.
67+
/// </summary>
68+
/// <param name="service">Authenticated web service connection.param>
69+
/// <param name="securityRole">Dataverse security role name.</param>
70+
/// <returns>Dataverse security role.</returns>
71+
/// <exception cref="Exception">General exception when role name not found.</exception>
72+
private static Role GetRoleByName(IOrganizationService service, string securityRole)
2173
{
2274
// Create a query to find the role by name.
2375
QueryExpression query = new QueryExpression
@@ -51,19 +103,9 @@ static public void AssociateSecurityRole(ServiceClient service, string securityR
51103
throw new Exception(String.Format("Role named '{0}' not found", securityRole));
52104
}
53105

54-
// Associate the user with the role.
55-
if (targetRole.Id != Guid.Empty && user != Guid.Empty)
56-
{
57-
service.Associate("systemuser", user,
58-
new Relationship("systemuserroles_association"),
59-
new EntityReferenceCollection()
60-
{
61-
new EntityReference(Role.EntityLogicalName, targetRole.Id)
62-
}
63-
);
64-
}
106+
return targetRole;
65107
}
66-
// </AssociateSecurityRole>
108+
// </GetRoleByName>
67109

68110
/// <summary>
69111
/// Contains the application's configuration settings.
@@ -114,21 +156,21 @@ static void Main(string[] args)
114156
/// Initializes any pre-existing data and resources required by the Run() method.
115157
/// </summary>
116158
/// <param name="service">Authenticated web service connection.</param>
117-
/// <param name="entityStore">Entity name and reference collection.</param>
159+
/// <param name="entityStore">Not used.</param>
118160
static public void Setup(IOrganizationService service, out Dictionary<string,
119161
EntityReference> entityStore)
120162
{
121163
entityStore = new Dictionary<string, EntityReference>();
122164

123-
// This sample does not require any setup. It uses and existing
165+
// This sample does not require any setup. It uses an existing
124166
// system user and role.
125167
}
126168

127169
/// <summary>
128170
/// The main logic of this program being demonstrated.
129171
/// </summary>
130172
/// <param name="service">Authenticated web service connection.</param>
131-
/// <param name="entityStore">Entity name and reference collection.</param>
173+
/// <param name="entityStore">Not used.</param>
132174
/// <returns>True if successful; otherwise false.</returns>
133175
static public bool Run(IOrganizationService service,
134176
Dictionary<string, EntityReference> entityStore)
@@ -139,14 +181,15 @@ static public bool Run(IOrganizationService service,
139181
WhoAmIResponse response = (WhoAmIResponse)service.Execute(request);
140182
Console.WriteLine("done.");
141183

142-
ServiceClient? clientService = service as ServiceClient;
143-
if (clientService != null)
184+
_userId = response.UserId;
185+
186+
if (service != null)
144187
{
145188
Console.Write("Associating your system user record with role 'Basic User'..");
146-
AssociateSecurityRole(clientService, "Basic User", response.UserId);
189+
AssociateSecurityRole(service, "Basic User", _userId);
147190
Console.WriteLine("done.");
148-
Console.WriteLine("\nUse the Power Platform admin center to see that you now have");
149-
Console.WriteLine("the 'Basic User' role. Afterwards, remove the role if desired.");
191+
Console.WriteLine("\nUse the Power Platform admin center to verify that you now have");
192+
Console.WriteLine("the 'Basic User' role before continuing this program's execution.");
150193
return true;
151194
}
152195
else
@@ -159,7 +202,7 @@ static public bool Run(IOrganizationService service,
159202
/// Dispose of any data and resources created by the this program.
160203
/// </summary>
161204
/// <param name="service">Authenticated web service connection.</param>
162-
/// <param name="entityStore">Entity name and reference collection.</param>
205+
/// <param name="entityStore">Not used.</param>
163206
static public void Cleanup(ServiceClient service,
164207
Dictionary<string, EntityReference> entityStore)
165208
{
@@ -170,42 +213,7 @@ static public void Cleanup(ServiceClient service,
170213
return;
171214
}
172215

173-
if (entityStore == null)
174-
{
175-
Console.WriteLine("Cleanup(): entref store collection is null, cleanup aborted.");
176-
Console.WriteLine("Cleanup(): be sure to run Setup() prior to Cleanup().");
177-
return;
178-
}
179-
180-
// Collect the keys of entities to be deleted.
181-
var keysToDelete = new List<string>(entityStore.Keys);
182-
183-
// Delete in Dataverse each entity in the entity store.
184-
foreach (var key in keysToDelete)
185-
{
186-
var entref = entityStore[key];
187-
try
188-
{
189-
service.Delete(entref.LogicalName, entref.Id);
190-
entityStore.Remove(key);
191-
}
192-
catch (Exception ex)
193-
{
194-
Console.WriteLine($"Cleanup(): exception deleting {key}\n\t{ex.Message}");
195-
continue;
196-
}
197-
}
198-
199-
// Output a list of entities that could not be deleted.
200-
if (entityStore.Count > 0)
201-
{
202-
Console.WriteLine("Cleanup(): the following entities could not be deleted:");
203-
foreach (var item in entityStore)
204-
{
205-
Console.WriteLine($"Cleanup(): name={item.Key}, " +
206-
$"logical name={item.Value.LogicalName}, ID={item.Value.Id}");
207-
}
208-
}
209-
}
216+
DisassociateSecurityRole(service, "Basic User", _userId);
217+
}
210218
}
211219
}

dataverse/orgsvc/CSharp-NETCore/Security/AssociateSecurityRoleToUser/README.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ page_type: sample
88
description: "This sample demonstrates how to ..."
99
---
1010

11-
# How to
11+
# How to associate a user with a security role
1212

1313
Learn how to associate a system user with a security role.
1414

@@ -22,7 +22,7 @@ Related article(s):
2222

2323
|Sample|Description|Build target|
2424
|---|---|---|
25-
|AssociateSecurityRole|Demonstrates associating a user with a role.|.NET 9|
25+
|[AssociateSecurityRoleToUser](https://github.com/microsoft/PowerApps-Samples/tree/master/dataverse/orgsvc/CSharp-NETCore/Security/AssociateSecurityRoleToUser) | Demonstrates associating a user with a security role.|.NET 9|
2626

2727
The code samples demonstrates how to associate a system user with a security role. Specifically, the samples demonstrates how to:
2828

@@ -54,3 +54,5 @@ Use the Power Platform admin center to see that you now have
5454
the 'Basic User' role. Afterwards, remove the role if desired.
5555
Press any key to undo environment data changes.
5656
```
57+
58+
If you get a "duplicate key" exception, it is probably because the Basic User role was already associated with your system user account. In that case, you can removed the Basic User role from your account using the Power Platfor admin center before running the program.

0 commit comments

Comments
 (0)