Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>try</p> <pre><code>public List&lt;ADGroup&gt; GetMemberGroups(string loginId, PrincipalContext principalContext, int tries = 0) { var result = new List&lt;ADGroup&gt;(); bool Done = false; try { var samAccountName = ""; if (loginId.Contains(" ")) { var fName = loginId.Split(Char.Parse(" "))[0].ToLower(); var sName = loginId.Split(Char.Parse(" "))[1].ToLower(); if (sName.Trim().Length == 2) samAccountName = string.Format("{0}{1}", fName.StartsWith(".") ? fName.Substring(0, 4) : fName.Substring(0, 3), sName.Substring(0, 2)); else samAccountName = string.Format("{0}{1}", fName.StartsWith(".") ? fName.Substring(0, 3) : fName.Substring(0, 2), sName.Substring(0, 3)); } else samAccountName = loginId.Substring(loginId.IndexOf(@"\") + 1); var authPrincipal = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, samAccountName); if (authPrincipal == null) throw new Exception(string.Format("authPrincipal is null for loginId - {0}", loginId)); var firstLevelGroups = authPrincipal.GetGroups(); AddGroups(firstLevelGroups, ref result); Done = true; } catch { if (tries &gt; 5) throw; tries += 1; } if ( ( !Done) &amp;&amp; (tries &lt; 6) ) { System.Threading.Thread.Sleep(1000); result = GetMemberGroups(loginId, principalContext, tries); } return result; } private void AddGroups(PrincipalSearchResult&lt;Principal&gt; principal, ref List&lt;ADGroup&gt; returnList) { if ( principal == null ) return; foreach (var item in principal) { if (item.GetGroups().Count() &gt; 0) AddGroups(item.GetGroups(), ref returnList); returnList.Add(new ADGroup(item.SamAccountName, item.Sid.Value)); } } </code></pre> <p>When an exception happens you called the function again from the catch-block (depending on the value of tries) but <em>discarded its return value - so even if the second/third... call worked you returned an empty result to the original caller</em>. I changed that so the result won't be discarded anymore...</p> <p>In the second function you never checked the principal param for null before starting the foreach... I changed that too...</p> <p>And I removed the recursion from within the catch block catch (although I am really not sure whether this change has any real effect).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload