This repository has been archived by the owner on Mar 11, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
AcUsers.cs
687 lines (634 loc) · 33.2 KB
/
AcUsers.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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
/*! \file
Copyright (C) 2016-2018 Verizon. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace AcUtils
{
/// <summary>
/// A user's AccuRev [principal attributes](@ref AcUtils#AcPrincipal) \e name, \e ID, and \e status (active or inactive).
/// In addition, the user's AccuRev [group membership](@ref AcUtils#AcUser#initGroupsListAsync) list along with regular and
/// other <a href="class_ac_utils_1_1_ac_user.html#properties">user properties</a> from Active Directory can be included
/// (both optional) during [list construction](@ref AcUtils#AcUsers#AcUsers).
/// </summary>
/*! \attention User properties require that AccuRev principal names match login names stored on the LDAP server. */
[Serializable]
[TypeDescriptionProvider(typeof(PrncplDescriptionProvider))]
public sealed class AcUser : IFormattable, IEquatable<AcUser>, IComparable<AcUser>, IComparable
{
#region class variables
private AcPrincipal _principal = new AcPrincipal();
private string _givenName; // John
private string _middleName;
private string _surname; // Doe
private string _displayName; // Doe, John
private string _business; // business phone number
private string _emailAddress; // [email protected]
private string _description;
private string _distinguishedName;
// [title,value] pairs for user properties outside the default set
private Dictionary<string, object> _other = new Dictionary<string, object>();
#endregion
/// <summary>
/// Initialize user's AccuRev [principal attributes](@ref AcUtils#AcPrincipal) \e name, \e ID, and \e status (active or inactive).
/// AcUser objects are instantiated during AcUsers list construction. This constructor is called internally and not by user code.
/// </summary>
/// <param name="id">User's AccuRev principal ID number.</param>
/// <param name="name">User's AccuRev principal name.</param>
/// <param name="status">Whether the user is active or inactive in AccuRev.</param>
/*! \sa [AcUsers.initAsync](@ref AcUtils#AcUsers#initAsync), [AcUser.initFromADAsync](@ref AcUtils#AcUser#initFromADAsync),
[AcUser.initGroupsListAsync](@ref AcUtils#AcUser#initGroupsListAsync) */
internal AcUser(int id, string name, PrinStatus status)
{
_principal.ID = id;
_principal.Name = name;
_principal.Status = status;
}
#region Equality comparison
/*! \name Equality comparison */
/**@{*/
/// <summary>
/// IEquatable implementation to determine the equality of instances of type AcUser.
/// Uses the user's principal ID to compare instances as this number is immutable in AccuRev;
/// a user's principal attributes can change except their ID.
/// </summary>
/// <param name="other">The AcUser object being compared to \e this instance.</param>
/// <returns>\e true if AcUser \e rhs is the same, \e false otherwise.</returns>
public bool Equals(AcUser other)
{
if (ReferenceEquals(other, null)) return false;
if (ReferenceEquals(this, other)) return true;
return Principal.ID == other.Principal.ID;
}
/// <summary>
/// Overridden to determine equality.
/// </summary>
/// <returns>Return value of generic [Equals(AcUser)](@ref AcUser#Equals) version.</returns>
public override bool Equals(object other)
{
if (ReferenceEquals(other, null)) return false;
if (ReferenceEquals(this, other)) return true;
if (GetType() != other.GetType()) return false;
return this.Equals(other as AcUser);
}
/// <summary>
/// Override appropriate for type AcUser.
/// </summary>
/// <returns>AccuRev principal ID number since it's immutable and unique across both users and groups.</returns>
public override int GetHashCode()
{
return Principal.ID;
}
/**@}*/
#endregion
#region Order comparison
/*! \name Order comparison */
/**@{*/
/// <summary>
/// Generic IComparable implementation (default) for comparing AcUser objects to sort by [DisplayName](@ref AcUtils#AcUser#DisplayName)
/// from Active Directory if available, otherwise their AccuRev principal name.
/// </summary>
/// <param name="other">An AcUser object to compare with this instance.</param>
/// <returns>Value indicating the relative order of the AcUser objects being compared.</returns>
/*! \sa [AcUsers constructor example](@ref AcUtils#AcUsers#AcUsers) */
public int CompareTo(AcUser other)
{
int result;
if (AcUser.ReferenceEquals(this, other))
result = 0;
else
{
if (!String.IsNullOrEmpty(DisplayName) && !String.IsNullOrEmpty(other.DisplayName))
result = String.Compare(DisplayName, other.DisplayName);
else
result = String.Compare(Principal.Name, other.Principal.Name);
}
return result;
}
/// <summary>
/// Pre-generic interface implementation for code using reflection.
/// </summary>
/// <param name="other">An AcUser object to compare with this instance.</param>
/// <returns>Return value of generic [CompareTo(AcUser)](@ref AcUser#CompareTo) version.</returns>
/// <exception cref="ArgumentException">thrown if argument is not an AcUser object.</exception>
int IComparable.CompareTo(object other)
{
if (!(other is AcUser))
throw new ArgumentException("Argument is not an AcUser", "other");
AcUser o = (AcUser)other;
return this.CompareTo(o);
}
/**@}*/
#endregion
/// <summary>
/// AccuRev principal attributes \e name, \e ID, and \e status (active or inactive),
/// and optionally their [group membership list](@ref AcUtils#AcUser#initGroupsListAsync) as per
/// [AcUsers constructor](@ref AcUtils#AcUsers#AcUsers) \e includeGroupsList parameter.
/// </summary>
public AcPrincipal Principal
{
get { return _principal; }
}
/*! \name User properties default set (Active Directory) */
/**@{*/
/// <summary>
/// User's given name from Active Directory, e.g. John
/// </summary>
public string GivenName
{
get { return _givenName ?? String.Empty; }
}
/// <summary>
/// User's middle name from Active Directory.
/// </summary>
public string MiddleName
{
get { return _middleName ?? String.Empty; }
}
/// <summary>
/// User's surname from Active Directory, e.g. Doe
/// </summary>
public string Surname
{
get { return _surname ?? String.Empty; }
}
/// <summary>
/// User's display name from Active Directory, e.g. Doe, John
/// </summary>
public string DisplayName
{
get { return _displayName ?? String.Empty; }
}
/// <summary>
/// User's business phone number from Active Directory.
/// </summary>
public string Business
{
get { return _business ?? String.Empty; }
}
/// <summary>
/// User's email address from Active Directory.
/// </summary>
public string EmailAddress
{
get { return _emailAddress ?? String.Empty; }
}
/// <summary>
/// User's description from Active Directory.
/// </summary>
public string Description
{
get { return _description ?? String.Empty; }
}
/// <summary>
/// User's distinguished name from Active Directory.
/// </summary>
public string DistinguishedName
{
get { return _distinguishedName ?? String.Empty; }
}
/**@}*/
/// <summary>
/// Additional Active Directory user properties not in the regular
/// <a href="class_ac_utils_1_1_ac_user.html#properties">default set</a>.
/// </summary>
/// <remarks>
/// Optionally initialized during [list construction](@ref AcUtils#AcUsers#AcUsers) for
/// user properties beyond the <a href="class_ac_utils_1_1_ac_user.html#properties">default set</a>.
/// Elements are [\e title,\e value] pairs: \e title from the [properties section](@ref AcUtils#PropCollection)
/// in <tt>\<prog_name\>.exe.config</tt> and its value from Active Directory.
/// </remarks>
/*! \code
<activeDir>
<!-- contact your company LDAP administrator for these values -->
<domains>
<add host="xyzdc.mycorp.com" path="DC=XYZ,DC=xy,DC=zcorp,DC=com"/>
<add host="abcdc.mycorp.com" path="DC=ABC,DC=ab,DC=com"/>
</domains>
<properties>
<add field="mobile" title="Mobile"/>
<add field="manager" title="Manager"/>
<add field="department" title="Department"/>
</properties>
</activeDir>
...
row["GivenName"] = user.GivenName;
row["Surname"] = user.Surname;
row["Mobile"] = user.Other.ContainsKey("Mobile") ? user.Other["Mobile"] : String.Empty;
row["EmailAddress"] = user.EmailAddress;
row["Manager"] = user.Other.ContainsKey("Manager") ? getManager((string)user.Other["Manager"]) : String.Empty;
row["Department"] = user.Other.ContainsKey("Department") ? user.Other["Department"] : String.Empty;
row["Description"] = user.Description;
...
\endcode */
/*! \sa PropCollection */
public IDictionary<string, object> Other
{
get { return _other; }
}
#region ToString
/// <summary>
/// The ToString implementation.
/// </summary>
/// <param name="format">The format specifier to use, e.g. <b>Console.WriteLine(user.ToString("e"));</b></param>
/// <param name="provider">Allow clients to format output for their own types using [ICustomFormatter](https://msdn.microsoft.com/en-us/library/system.icustomformatter.aspx).</param>
/// <returns>The formatted string.</returns>
/// <exception cref="FormatException">thrown if an invalid format string is specified.</exception>
/// \par Format specifiers:
/// \arg \c G User's display name from Active Directory if available (e.g. Doe, John), otherwise their AccuRev principal name. The default when no format specifier is used.
/// \arg \c LV Long version (verbose).
/// \arg \c I User's AccuRev principal ID number.
/// \arg \c N User's AccuRev principal name.
/// \arg \c S Principal's status in AccuRev: \e Active or \e Inactive.
/// \arg \c F User's given name from Active Directory.
/// \arg \c M User's middle name from Active Directory.
/// \arg \c L User's surname from Active Directory.
/// \arg \c DN User's display name from Active Directory.
/// \arg \c B User's business phone number from Active Directory.
/// \arg \c E User's email address from Active Directory.
/// \arg \c D User's description from Active Directory.
/// \arg \c DG User's distinguished name from Active Directory.
public string ToString(string format, IFormatProvider provider)
{
if (provider != null)
{
ICustomFormatter fmt = provider.GetFormat(this.GetType()) as ICustomFormatter;
if (fmt != null)
return fmt.Format(format, this, provider);
}
if (String.IsNullOrEmpty(format))
format = "G";
switch (format.ToUpperInvariant())
{
case "G": // user's display name from Active Directory if available, otherwise their AccuRev principal name
return _displayName ?? Principal.Name;
case "LV": // long version (verbose)
return $"{DisplayName} ({Principal.Name}), Business: {(String.IsNullOrEmpty(Business) ? "N/A" : Business)}, {EmailAddress}";
case "I": // user's AccuRev principal ID
return Principal.ID.ToString();
case "N": // user's AccuRev principal name
return Principal.Name;
case "S": // principal's status in AccuRev: Active or Inactive
return Principal.Status.ToString();
case "F": // user's given name from Active Directory
return GivenName;
case "M": // user's middle name from Active Directory
return MiddleName;
case "L": // user's surname from Active Directory
return Surname;
case "DN": // user's display name from Active Directory
return DisplayName;
case "B": // business phone number from Active Directory
return Business;
case "E": // user's email address from Active Directory
return EmailAddress;
case "D": // description from Active Directory
return Description;
case "DG": // distinguished name from Active Directory
return DistinguishedName;
default:
throw new FormatException($"The {format} format string is not supported.");
}
}
// Calls ToString(string, IFormatProvider) version with a null IFormatProvider argument.
public string ToString(string format)
{
return ToString(format, null);
}
// Calls ToString(string, IFormatProvider) version with the general format and a null IFormatProvider argument.
public override string ToString()
{
return ToString("G", null);
}
#endregion ToString
/// <summary>
/// Optionally called during [list construction](@ref AcUtils#AcUsers#AcUsers) to initialize the
/// <a href="class_ac_utils_1_1_ac_user.html#properties">default set</a> of regular user properties
/// and others from Active Directory. This method is called internally and not by user code.
/// </summary>
/// <param name="dc">List of DomainElement objects as defined in <tt>\<prog_name\>.exe.config</tt> \e domains section. Used to initialize
/// the user properties <a href="class_ac_utils_1_1_ac_user.html#properties">default set</a> from Active Directory.</param>
/// <param name="pc">List of PropElement objects as defined in <tt>\<prog_name\>.exe.config</tt> \e properties section. Used to add
/// and initialize user properties from Active Directory that are outside the regular <a href="class_ac_utils_1_1_ac_user.html#properties">default set</a>.</param>
/// <returns>\e true if no exception was thrown and operation succeeded, \e false otherwise.</returns>
/// <exception cref="Exception">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
/// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on failure to handle a range of exceptions.</exception>
/*! \sa DomainCollection, PropCollection, Other */
/*! \attention User properties require that AccuRev principal names match login names stored on the LDAP server. */
internal async Task<bool> initFromADAsync(DomainCollection dc, PropCollection pc = null)
{
return await Task.Run(() =>
{
bool ret = true; // assume success
foreach (DomainElement de in dc)
{
PrincipalContext ad = null;
try
{
ad = new PrincipalContext(ContextType.Domain, de.Host.Trim(), de.Path.Trim());
UserPrincipal up = new UserPrincipal(ad);
up.SamAccountName = Principal.Name;
using (PrincipalSearcher ps = new PrincipalSearcher(up))
{
UserPrincipal rs = (UserPrincipal)ps.FindOne();
if (rs != null)
{
_givenName = rs.GivenName;
_middleName = rs.MiddleName;
_surname = rs.Surname;
_displayName = rs.DisplayName;
_business = rs.VoiceTelephoneNumber;
_emailAddress = rs.EmailAddress;
_description = rs.Description;
_distinguishedName = rs.DistinguishedName;
if (pc != null)
{
DirectoryEntry lowerLdap = (DirectoryEntry)rs.GetUnderlyingObject();
foreach (PropElement pe in pc)
{
PropertyValueCollection pvc = lowerLdap.Properties[pe.Field];
if (pvc != null)
_other.Add(pe.Title.Trim(), pvc.Value);
}
}
break;
}
}
}
catch (Exception ecx)
{
ret = false;
AcDebug.Log($"Exception caught and logged in AcUser.initFromADAsync{Environment.NewLine}{ecx.Message}");
}
// avoid CA2202: Do not dispose objects multiple times
finally { if (ad != null) ad.Dispose(); }
}
return ret;
}).ConfigureAwait(false);
}
/// <summary>
/// Optionally called during [list construction](@ref AcUtils#AcUsers#AcUsers) to initialize the list of groups
/// this user is a member of by way of direct or indirect (implicit) membership, e.g. Mary is implicitly a member
/// of groupA because she's a member of groupB which is a member of groupA. This method is called internally
/// and not by user code.
/// </summary>
/// <remarks>Membership lists for inactive users are initialized too when
/// [constructor parameter](@ref AcUtils#AcUsers#AcUsers) \e includeDeactivated is \e true.</remarks>
/// <returns>\e true if no exception was thrown and operation succeeded, \e false otherwise.</returns>
/// <exception cref="AcUtilsException">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
/// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on \c show command failure.</exception>
/// <exception cref="Exception">caught and logged in same on failure to handle a range of exceptions.</exception>
/*! \sa [AcGroups.initMembersListAsync](@ref AcUtils#AcGroups#initMembersListAsync) */
/*! \show_ <tt>show -fx -u \<user\> groups</tt> */
/*! \accunote_ Unlike the \c show command used here, its <tt>show -fx -g \<group\> members</tt> counterpart
does not include memberships resulting from indirect (implicit) membership. */
internal async Task<bool> initGroupsListAsync()
{
bool ret = false; // assume failure
try
{
// works for inactive users too
AcResult r = await AcCommand.runAsync($@"show -fx -u ""{Principal.Name}"" groups")
.ConfigureAwait(false);
if (r != null && r.RetVal == 0) // if command succeeded
{
SortedSet<string> members = new SortedSet<string>();
XElement xml = XElement.Parse(r.CmdResult);
foreach (XElement e in xml.Elements("Element"))
{
string name = (string)e.Attribute("Name");
members.Add(name);
}
Principal.Members = members;
ret = true; // operation succeeded
}
}
catch (AcUtilsException ecx)
{
AcDebug.Log($"AcUtilsException caught and logged in AcUser.initGroupsListAsync{Environment.NewLine}{ecx.Message}");
}
catch (Exception ecx)
{
AcDebug.Log($"Exception caught and logged in AcUser.initGroupsListAsync{Environment.NewLine}{ecx.Message}");
}
return ret;
}
/// <summary>
/// Get the [list of groups](@ref AcUtils#AcUser#initGroupsListAsync) this user is a member of as a formatted string.
/// List optionally initialized by [AcUsers constructor](@ref AcUtils#AcUsers#AcUsers) when \e includeGroupsList param is \e true.
/// </summary>
/// <returns>User's group membership list as an ordered formatted comma-delimited string, otherwise \e null if not found.</returns>
/*! \sa [AcGroups.isMember](@ref AcUtils#AcGroups#isMember), [AcGroups.getMembers](@ref AcUtils#AcGroups#getMembers) */
public string getGroups()
{
string list = null;
if (Principal.Members != null)
list = String.Join(", ", Principal.Members);
return list;
}
}
/// <summary>
/// A container of AcUser objects that define AccuRev users.
/// </summary>
/// <remarks>
/// Elements contain user [principal attributes](@ref AcUtils#AcPrincipal) \e name, \e ID, and \e status (active or inactive).
/// In addition, the user's AccuRev group membership list, regular and other
/// <a href="class_ac_utils_1_1_ac_user.html#properties">user properties</a> from Active Directory, and deactivated (removed)
/// users can be included as well.
/// </remarks>
/*! \attention User properties require that AccuRev principal names match login names stored on the LDAP server. */
[Serializable]
public sealed class AcUsers : List<AcUser>
{
#region class variables
private DomainCollection _dc;
private PropCollection _pc; // user properties from Active Directory beyond the default set
private bool _includeGroupsList;
private bool _includeDeactivated;
[NonSerialized] private readonly object _locker = new object(); // token for lock keyword scope
[NonSerialized] private int _counter; // used to report initialization progress back to the caller
#endregion
#region object construction:
//! \name Two-part object construction:
//@{
/// <summary>
/// A container of AcUser objects that define AccuRev users. Elements contain user
/// [principal attributes](@ref AcUtils#AcPrincipal) \e name, \e ID, and \e status (active or inactive).
/// Optionally, the user's AccuRev group membership list, regular and other
/// <a href="class_ac_utils_1_1_ac_user.html#properties">user properties</a> from Active Directory,
/// and deactivated (removed) users can be included as well.
/// </summary>
/// <remarks>
/// Including group membership initialization (<em>includeGroupsList = true</em>) is slower, so we give the option to exclude it when
/// the list isn't needed. A user's group membership list includes groups from implicit membership, i.e. if user is a member of groupA
/// and groupA is a member of groupB, the user is implicitly a member of groupB.
/// </remarks>
/// <param name="dc">List of DomainElement objects as defined in <tt>\<prog_name\>.exe.config</tt> \e domains section. Used to initialize
/// the user properties <a href="class_ac_utils_1_1_ac_user.html#properties">default set</a> from Active Directory.</param>
/// <param name="pc">List of PropElement objects as defined in <tt>\<prog_name\>.exe.config</tt> \e properties section. Used to add
/// and initialize user properties from Active Directory that are outside the regular <a href="class_ac_utils_1_1_ac_user.html#properties">default set</a>.
/// Note: requires a valid DomainCollection \e dc parameter.
/// </param>
/// <param name="includeGroupsList">\e true to include group membership initialization for each user (slower), \e false for no initialization (faster).</param>
/// <param name="includeDeactivated">\e true to include deactivated (removed) users, otherwise \e false.</param>
/*! \code
ADSection adSection = ConfigurationManager.GetSection("activeDir") as ADSection;
_domains = adSection.Domains;
_pc = adSection.Props;
...
toolStripStatusLabel.Text = "Loading users...";
toolStripProgressBar.Maximum = await AcQuery.getUsersCountAsync();
var progress = new Progress<int>(i => toolStripProgressBar.Value = i);
AcUsers users = new AcUsers(_domains, _pc, includeGroupsList: true);
if (await users.initAsync(progress)) // if successful
{
foreach (AcUser user in users.OrderBy(n => n)) // use default comparer
...
\endcode */
/*! \attention User properties require that AccuRev principal names match login names stored on the LDAP server. */
/*! \sa initAsync, [AcUser.initGroupsListAsync](@ref AcUtils#AcUser#initGroupsListAsync), [AcUser.initFromADAsync](@ref AcUtils#AcUser#initFromADAsync),
[default comparer](@ref AcUtils#AcUser#CompareTo), [AcGroups constructor](@ref AcUtils#AcGroups#AcGroups) */
public AcUsers(DomainCollection dc = null, PropCollection pc = null, bool includeGroupsList = false, bool includeDeactivated = false)
{
_dc = dc;
_pc = pc;
_includeGroupsList = includeGroupsList;
_includeDeactivated = includeDeactivated;
}
/// <summary>
/// Populate this container with AcUser objects as per [constructor parameters](@ref AcUtils#AcUsers#AcUsers).
/// </summary>
/// <param name="progress">Optionally report progress back to the caller.</param>
/// <returns>\e true if list initialization succeeded, \e false otherwise.</returns>
/// <exception cref="AcUtilsException">caught and [logged](@ref AcUtils#AcDebug#initAcLogging) in
/// <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on \c show command failure.</exception>
/// <exception cref="Exception">caught and logged in same on failure to handle a range of exceptions.</exception>
/*! \show_ <tt>show \<-fx | -fix\> users</tt> */
public async Task<bool> initAsync(IProgress<int> progress = null)
{
bool ret = false; // assume failure
try
{
AcResult r = await AcCommand.runAsync($"show {(_includeDeactivated ? "-fix" : "-fx")} users")
.ConfigureAwait(false);
if (r != null && r.RetVal == 0) // if command succeeded
{
XElement xml = XElement.Parse(r.CmdResult);
IEnumerable<XElement> query = from element in xml.Elements("Element") select element;
List<Task<bool>> tasks = new List<Task<bool>>(query.Count());
Func<Task<bool>, bool> cf = t =>
{
bool res = t.Result;
if (res && progress != null) progress.Report(Interlocked.Increment(ref _counter));
return res;
};
foreach (XElement e in query)
{
string name = (string)e.Attribute("Name");
int id = (int)e.Attribute("Number");
// XML attribute isActive exists only if the user is inactive, otherwise it isn't there
PrinStatus status = (e.Attribute("isActive") == null) ? PrinStatus.Active : PrinStatus.Inactive;
AcUser user = new AcUser(id, name, status);
lock (_locker) { Add(user); }
Task<bool> t = initUserPropsAsync(user).ContinueWith(cf);
tasks.Add(t);
}
bool[] arr = await Task.WhenAll(tasks).ConfigureAwait(false);
ret = (arr != null && arr.All(n => n == true));
}
}
catch (AcUtilsException ecx)
{
AcDebug.Log($"AcUtilsException caught and logged in AcUsers.initAsync{Environment.NewLine}{ecx.Message}");
}
catch (Exception ecx)
{
AcDebug.Log($"Exception caught and logged in AcUsers.initAsync{Environment.NewLine}{ecx.Message}");
}
return ret;
}
//@}
#endregion
/// <summary>
/// Helper function for initializing \e user with their Active Directory properties and group memberships
/// as per [constructor parameters](@ref AcUtils#AcUsers#AcUsers). Called internally and not by user code.
/// </summary>
/// <param name="user">The user to initialize.</param>
/// <returns>\e true if list initialization succeeded, \e false otherwise.</returns>
/// <exception cref="Exception">caught and [logged](@ref AcUtils#AcDebug#initAcLogging) in
/// <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on failure to handle a range of exceptions.</exception>
private async Task<bool> initUserPropsAsync(AcUser user)
{
bool ret = false; // assume failure
try
{
if (_dc != null && _includeGroupsList)
{
Task<bool>[] tasks = new Task<bool>[2];
// initialize default set and other user properties from Active Directory
tasks[0] = user.initFromADAsync(_dc, _pc);
// include group membership list initialization
tasks[1] = user.initGroupsListAsync();
bool[] arr = await Task.WhenAll(tasks).ConfigureAwait(false);
ret = (arr != null && arr.All(n => n == true));
}
else if (_dc != null && !_includeGroupsList)
ret = await user.initFromADAsync(_dc, _pc).ConfigureAwait(false);
else if (_dc == null && _includeGroupsList)
ret = await user.initGroupsListAsync().ConfigureAwait(false);
else // _dc == null && !_includeGroupsList
ret = true; // nothing to do
}
catch (Exception ecx)
{
AcDebug.Log($"Exception caught and logged in AcUsers.initUserPropsAsync{Environment.NewLine}{ecx.Message}");
}
return ret;
}
/// <summary>
/// Get the AcUser object for AccuRev principal \e name.
/// </summary>
/// <param name="name">AccuRev principal name.</param>
/// <returns>AcUser object for principal \e name or \e null if not found.</returns>
public AcUser getUser(string name)
{
return this.SingleOrDefault(n => n.Principal.Name == name);
}
/// <summary>
/// Get the AcUser object for AccuRev principal \e ID number.
/// </summary>
/// <param name="ID">AccuRev principal ID number.</param>
/// <returns>AcUser object for principal \e ID number or \e null if not found.</returns>
public AcUser getUser(int ID)
{
return this.SingleOrDefault(n => n.Principal.ID == ID);
}
/// <summary>
/// Get the AcUser object owner of AccuRev workspace \e name.
/// </summary>
/// <param name="name">Name of the workspace to query.</param>
/// <returns>AcUser object for owner of workspace \e name or \e null if not found.</returns>
public AcUser getWorkspaceOwner(string name)
{
int ii = name.LastIndexOf('_');
string prncpl = name.Substring(++ii);
return getUser(prncpl);
}
}
}