Created
September 22, 2017 17:48
-
-
Save sean-m/32c3c37f4c6eebe45909a219bf5d3dac to your computer and use it in GitHub Desktop.
Script that generates C# object properties that lazy load from a private DirectoryEntry (_de) field. Input text file is: [property type] [property name].
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function GenProp { | |
param ($type, $name) | |
if ($type -like 'bool' ` | |
-or $type -like 'int' ) { | |
$_default = $null | |
switch ($type) { | |
'bool' { | |
$_default = 'false' | |
} | |
'int' { | |
$_default = '0' | |
} | |
} | |
$baseProp = @" | |
private $type`? _$name; | |
public $type $name { | |
get { | |
if (_$name == null) { | |
this.GetValueFromDirectoryEntry(_de, "$name"); | |
} | |
return ($type)(_$name ?? $_default); | |
} | |
set { | |
_$name = value; | |
} | |
} | |
"@ | |
$baseProp | |
} | |
else { | |
$baseProp = @" | |
private $type _$name; | |
public $type $name { | |
get { | |
if (_$name == null) { | |
$(>> {$type -like 'List<string>'} {"_$name = new $type();"} {}) | |
this.GetValueFromDirectoryEntry(_de, "$name"); | |
} | |
return _$name; | |
} | |
set { | |
_$name = value; | |
} | |
} | |
"@ | |
$baseProp | |
} | |
} | |
gc ".\aduser_properties.txt" | % { | |
$t = $_.Split()[0].Trim() | |
$n = $_.Split()[1].Trim() | |
"" | |
GenProp $t $n | |
} | clip | |
<# | |
public static void GetValueFromDirectoryEntry<T>(this T obj, DirectoryEntry entry, string name) { | |
var utype = obj.GetType(); | |
var p = utype.GetProperty(name); | |
try { | |
var val = entry?.Properties[p.Name]?.Value; | |
if (val == null) return; | |
Type propType = p.PropertyType; | |
if (val?.GetType() == typeof(object[])) { | |
var temp = Activator.CreateInstance(propType); | |
var ctor = utype.GetConstructor(new Type[] { propType }); | |
if (propType.GetMethods().Any(x => x.Name == "AddRange")) { | |
var val_arr = (val as object[]).Cast<string>(); | |
temp.GetType().GetMethod("AddRange").Invoke(temp, new object[] { val_arr }); | |
} | |
p.SetValue(obj, temp); | |
} | |
else { | |
p.SetValue(obj, val); | |
} | |
} | |
catch (Exception e) { | |
Trace.WriteLine($"Error setting property: {p.Name}"); | |
Trace.WriteLine(e.Message); | |
Trace.WriteLine(e.StackTrace); | |
} | |
} | |
#> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment