Skip to content

Instantly share code, notes, and snippets.

@sjoshua270
Created April 2, 2019 20:40
Show Gist options
  • Save sjoshua270/03dfeb476502920740d72c1b6a8f07ee to your computer and use it in GitHub Desktop.
Save sjoshua270/03dfeb476502920740d72c1b6a8f07ee to your computer and use it in GitHub Desktop.
public class OUViewModel : TreeViewItemViewModel
{
readonly DirectoryEntry _de;
private Stack<string> searchStack = new Stack<string>();
public OUViewModel(DirectoryEntry de, OUViewModel parent)
// The DirectorySearcher here is checking to see if there are any children under this DirectoryEntry
: base(parent, new DirectorySearcher(de, "(objectClass=organizationalUnit)", null, SearchScope.OneLevel).FindOne() != null)
{
_de = de;
}
public string Name
{
get { return _de.Name.Substring(_de.Name.IndexOf('=') + 1); }
}
public string Path
{
get { return _de.Path; }
}
protected override void LoadChildren()
{
MainWindow.StartProgressBar();
BackgroundWorker childLoader = new BackgroundWorker();
childLoader.DoWork += GetChildren;
childLoader.RunWorkerCompleted += UpdateChildren;
childLoader.RunWorkerAsync(this);
}
private void GetChildren(object sender, DoWorkEventArgs e)
{
OUViewModel parent = e.Argument as OUViewModel;
DirectoryEntry parentDE = parent._de;
DirectorySearcher searcher = new DirectorySearcher(parentDE, "(objectClass=organizationalUnit)")
{
// SearchScope = OneLevel means the searcher will return its children when using FindOne() or FindAll()
SearchScope = SearchScope.OneLevel
};
ObservableCollection<OUViewModel> children = new ObservableCollection<OUViewModel>();
foreach (SearchResult result in searcher.FindAll())
{
children.Add(new OUViewModel(result.GetDirectoryEntry(), parent));
}
e.Result = children;
}
private void UpdateChildren(object sender, RunWorkerCompletedEventArgs e)
{
foreach (OUViewModel child in e.Result as ObservableCollection<OUViewModel>)
{
child.Search(searchStack);
Children.Add(child);
}
MainWindow.StopProgressBar();
}
#region Custom Methods
public void Search(Stack<string> path)
{
searchStack = path;
if (searchStack.Count > 0)
{
// Let's see if our current OU is next in the path
string name = searchStack.Peek();
if (Name == name)
{
searchStack.Pop();
IsExpanded = true;
if (HasLoadedChildren)
{
foreach (OUViewModel child in Children)
{
child.Search(searchStack);
}
}
else
{
LoadChildren();
}
if (searchStack.Count == 0)
{
IsSelected = true;
}
}
}
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment