-
Notifications
You must be signed in to change notification settings - Fork 1
/
RemoveDuplicateUsers.cs
233 lines (203 loc) · 9.28 KB
/
RemoveDuplicateUsers.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Collabco.Myday.Scim;
using Polly;
namespace Remove_duplicate_users
{
public partial class RemoveDuplicateUsers : Form
{
private readonly SynchronizationContext synchronizationContext;
public RemoveDuplicateUsers()
{
InitializeComponent();
synchronizationContext = SynchronizationContext.Current;
}
//Dictionary of users by externalId
Dictionary<string, Collabco.Myday.Scim.v2.Model.ScimUser2> users = new Dictionary<string, Collabco.Myday.Scim.v2.Model.ScimUser2>();
//List of duplicate user ids
List<string> duplicateUserIds = new List<string>();
private async void btn_IdentityDuplicates_Click(object sender, EventArgs e)
{
try
{
users.Clear();
duplicateUserIds.Clear();
var scimClient = CreateScimClient();
await Task.Run(() => FindDuplicateScimUsers(scimClient));
MessageBox.Show("Duplicate search completed", "Operation complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Operation failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private async Task FindDuplicateScimUsers(ScimClient scimClient)
{
var errorCount = 0;
var totalUserCount = 0;
Collabco.Myday.Scim.v2.Model.ScimListResponse2<Collabco.Myday.Scim.v2.Model.ScimUser2> usersPage = null;
var startIndex = 1;
while (usersPage == null || usersPage.TotalResults > totalUserCount)
{
usersPage = await Policy
.Handle<Exception>(e => !(e is ArgumentNullException || e is ArgumentException))
.WaitAndRetryAsync(
DecorrelatedJitter(5, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(30)),
(exception, timeSpan, context) =>
{
errorCount++;
UpdateErrorCount(errorCount);
Debug.WriteLine($"Scim search error: {exception.Message}");
}
)
.ExecuteAsync(() =>
{
return scimClient.Search<Collabco.Myday.Scim.v2.Model.ScimUser2>(
new Collabco.Myday.Scim.Query.ScimQueryOptions
{
Attributes = new List<string> { "id", "externalId", "meta.created", "meta.lastModified" },
StartIndex = startIndex,
//SortBy = "meta.created",
// SortOrder = Collabco.Myday.Scim.Core.Model.SortOrder.Ascending,
Count = 100
}
);
});
totalUserCount += usersPage.Resources.Count();
startIndex += usersPage.ItemsPerPage;
foreach(var user in usersPage.Resources.Where(g => !string.IsNullOrEmpty(g.ExternalId)))
{
if (users.TryGetValue(user.ExternalId, out Collabco.Myday.Scim.v2.Model.ScimUser2 existingUser))
{
if (SuperceedsExistingUser(existingUser, user))
{
users[user.ExternalId] = user;
duplicateUserIds.Add(existingUser.Id);
}
else
{
duplicateUserIds.Add(user.Id);
}
}
else
{
users[user.ExternalId] = user;
}
}
UpdateDuplicateCounts(totalUserCount);
}
}
private void UpdateDuplicateCounts(int totalGroupCount)
{
synchronizationContext.Post(new SendOrPostCallback(o =>
{
lbl_TotalUsers.Text = o.ToString();
lbl_NoDuplicates.Text = duplicateUserIds.Count.ToString();
lbl_NoUniqueUsers.Text = users.Count.ToString();
}), totalGroupCount);
}
private async void btn_Delete_Click(object sender, EventArgs e)
{
try
{
var scimClient = CreateScimClient();
await Task.Run(async () =>
{
var deleteCount = 0;
foreach (var groupId in duplicateUserIds)
{
await Policy
.Handle<Exception>(ex => !(ex is ArgumentNullException || ex is ArgumentException))
.WaitAndRetryAsync(
DecorrelatedJitter(5, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(30)),
(exception, timeSpan, context) =>
{
Debug.WriteLine($"Scim delete error: {exception.Message}");
}
)
.ExecuteAsync(() =>
{
return scimClient.Delete<Collabco.Myday.Scim.v2.Model.ScimUser2>(groupId);
});
deleteCount++;
UpdateDeleteCount(deleteCount);
}
});
MessageBox.Show("Delete duplicates completed", "Operation complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Operation failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void UpdateErrorCount(int deleteCount)
{
synchronizationContext.Post(new SendOrPostCallback(o =>
{
lbl_NoError.Text = o.ToString();
}), deleteCount);
}
private void UpdateDeleteCount(int deleteCount)
{
synchronizationContext.Post(new SendOrPostCallback(o =>
{
lbl_NoDeleted.Text = o.ToString();
}), deleteCount);
}
private ScimClient CreateScimClient()
{
var scimConfig = new Collabco.Myday.Scim.Configuration.ScimConfiguration
{
BaseUrl = $"{txt_ScimUrl.Text}/{txt_TenantId.Text}/v2",
DefaultSearchPageSize = 100
};
scimConfig.AddDefaultScimResourceTypes();
scimConfig.AddMydayScimResourceTypes();
return new ScimClient(scimConfig, txt_Token.Text);
}
/// <summary>
/// Implementation of Decorrelated Jitter strategy
/// </summary>
/// <param name="maxRetries">Max imum number of retries</param>
/// <param name="seedDelay">Initial minimum delay for a retry</param>
/// <param name="maxDelay">Maximum delay for a retry</param>
/// <returns>TimeSpan of the delay</returns>
private static IEnumerable<TimeSpan> DecorrelatedJitter(int maxRetries, TimeSpan seedDelay, TimeSpan maxDelay)
{
Random jitterer = new Random();
int retries = 0;
double seed = seedDelay.TotalMilliseconds;
double max = maxDelay.TotalMilliseconds;
double current = seed;
while (++retries <= maxRetries)
{
current = Math.Min(max, Math.Max(seed, current * 3 * jitterer.NextDouble())); // adopting the 'Decorrelated Jitter' formula from https://www.awsarchitectureblog.com/2015/03/backoff.html. Can be between seed and previous * 3. Mustn't exceed max.
yield return TimeSpan.FromMilliseconds(current);
}
}
private bool SuperceedsExistingUser(Collabco.Myday.Scim.v2.Model.ScimUser2 existingtUser, Collabco.Myday.Scim.v2.Model.ScimUser2 duplicateUser)
{
////Superceed if duplicate user is active and existing user is not
//bool superceed = !(existingtUser.Active ?? false) && (duplicateUser.Active ?? false);
//if (!superceed)
//{
// //Superceed if duplicate user has UserType 'AzureAD' and existing user does not
// superceed = existingtUser.UserType != "AzureAD" && duplicateUser.UserType == "AzureAD";
//}
//if (!superceed)
//{
// //Superceed if duplicate user has more identityProviders associated that the existing user
// var existingUserIdProviders = existingtUser.Extension<Collabco.Myday.Scim.v2.Model.MydayUser2Extension>()?.IdentityProviders;
// var duplicateUserIdProviders = duplicateUser.Extension<Collabco.Myday.Scim.v2.Model.MydayUser2Extension>()?.IdentityProviders;
// superceed = duplicateUserIdProviders != null && duplicateUserIdProviders.Count > (existingUserIdProviders?.Count ?? 0);
//}
return duplicateUser.Meta.Created < existingtUser.Meta.Created;
}
}
}