Feature #42: Active Directory Interop Upgrade

AD Interop moved to Disco.Services; Supports multi-domain environments,
sites, and searching restricted with OUs.
This commit is contained in:
Gary Sharp
2014-04-10 17:58:04 +10:00
parent b841c6b2c0
commit db73cc1a12
218 changed files with 6383 additions and 2535 deletions
File diff suppressed because it is too large Load Diff
@@ -1,229 +0,0 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Disco.Data.Repository;
using Disco.Services.Tasks;
using Quartz;
using Disco.Models.Interop.ActiveDirectory;
namespace Disco.BI.Interop.ActiveDirectory
{
public class ActiveDirectoryCachedGroups : ScheduledTask
{
private static ConcurrentDictionary<string, Tuple<ActiveDirectoryGroup, DateTime>> _SecurityIdentifierCache = new ConcurrentDictionary<string, Tuple<ActiveDirectoryGroup, DateTime>>();
private static ConcurrentDictionary<string, Tuple<ActiveDirectoryGroup, DateTime>> _DistinguishedNameCache = new ConcurrentDictionary<string, Tuple<ActiveDirectoryGroup, DateTime>>();
private const long CacheTimeoutTicks = 6000000000; // 10 Minutes
public static IEnumerable<string> GetGroups(IEnumerable<string> DistinguishedNames)
{
List<ActiveDirectoryGroup> groups = new List<ActiveDirectoryGroup>();
foreach (var distinguishedName in DistinguishedNames)
foreach (var group in GetGroupsRecursive(distinguishedName, new Stack<ActiveDirectoryGroup>()))
if (!groups.Contains(group))
{
groups.Add(group);
yield return group.SamAccountName;
}
}
public static IEnumerable<string> GetGroups(string DistinguishedName)
{
foreach (var group in GetGroupsRecursive(DistinguishedName, new Stack<ActiveDirectoryGroup>()))
yield return group.SamAccountName;
}
public static string GetGroupsDistinguishedNameForSecurityIdentifier(string SecurityIdentifier)
{
var group = GetGroupBySecurityIdentifier(SecurityIdentifier);
if (group == null)
return null;
else
return group.DistinguishedName;
}
private static IEnumerable<ActiveDirectoryGroup> GetGroupsRecursive(string DistinguishedName, Stack<ActiveDirectoryGroup> RecursiveTree)
{
var group = GetGroup(DistinguishedName);
if (group != null && !RecursiveTree.Contains(group))
{
yield return group;
if (group.MemberOf != null)
{
RecursiveTree.Push(group);
foreach (var parentDistinguishedName in group.MemberOf)
foreach (var parentGroup in GetGroupsRecursive(parentDistinguishedName, RecursiveTree))
yield return parentGroup;
RecursiveTree.Pop();
}
}
}
private static ActiveDirectoryGroup GetGroup(string DistinguishedName)
{
// Check Cache
Tuple<ActiveDirectoryGroup, DateTime> groupRecord = TryCache(DistinguishedName);
if (groupRecord == null)
{
// Load from AD
var group = ActiveDirectory.GetGroupFromDistinguishedName(DistinguishedName);
SetValue(group);
return group;
}
else
{
// Return from Cache
return groupRecord.Item1;
}
}
private static ActiveDirectoryGroup GetGroupBySecurityIdentifier(string SecurityIdentifier)
{
// Check Cache
Tuple<ActiveDirectoryGroup, DateTime> groupRecord = TrySecurityIdentifierCache(SecurityIdentifier);
if (groupRecord == null)
{
// Load from AD
var group = ActiveDirectory.GetGroupFromSecurityIdentifier(SecurityIdentifier);
SetValue(group);
return group;
}
else
{
// Return from Cache
return groupRecord.Item1;
}
}
private static Tuple<ActiveDirectoryGroup, DateTime> TryCache(string DistinguishedName)
{
string distinguishedName = DistinguishedName.ToLower();
Tuple<ActiveDirectoryGroup, DateTime> groupRecord;
if (_DistinguishedNameCache.TryGetValue(distinguishedName, out groupRecord))
{
if (groupRecord.Item2 > DateTime.Now)
return groupRecord;
else
{
if (_DistinguishedNameCache.TryRemove(distinguishedName, out groupRecord))
_SecurityIdentifierCache.TryRemove(groupRecord.Item1.SecurityIdentifier, out groupRecord);
}
}
return null;
}
private static Tuple<ActiveDirectoryGroup, DateTime> TrySecurityIdentifierCache(string SecurityIdentifier)
{
Tuple<ActiveDirectoryGroup, DateTime> groupRecord;
if (_SecurityIdentifierCache.TryGetValue(SecurityIdentifier, out groupRecord))
{
if (groupRecord.Item2 > DateTime.Now)
return groupRecord;
else
{
if (_SecurityIdentifierCache.TryRemove(SecurityIdentifier, out groupRecord))
_DistinguishedNameCache.TryRemove(groupRecord.Item1.DistinguishedName.ToLower(), out groupRecord);
}
}
return null;
}
private static bool SetValue(ActiveDirectoryGroup Group)
{
Tuple<ActiveDirectoryGroup, DateTime> groupRecord = new Tuple<ActiveDirectoryGroup, DateTime>(Group, DateTime.Now.AddTicks(CacheTimeoutTicks));
Tuple<ActiveDirectoryGroup, DateTime> oldGroupRecord;
string key = Group.DistinguishedName.ToLower();
if (_DistinguishedNameCache.ContainsKey(key))
{
if (_DistinguishedNameCache.TryGetValue(key, out oldGroupRecord))
{
_DistinguishedNameCache.TryUpdate(key, groupRecord, oldGroupRecord);
}
}
else
{
_DistinguishedNameCache.TryAdd(key, groupRecord);
}
string securityIdentifier = Group.SecurityIdentifier;
if (_SecurityIdentifierCache.ContainsKey(securityIdentifier))
{
if (_SecurityIdentifierCache.TryGetValue(securityIdentifier, out oldGroupRecord))
{
_SecurityIdentifierCache.TryUpdate(securityIdentifier, groupRecord, oldGroupRecord);
}
}
else
{
_SecurityIdentifierCache.TryAdd(securityIdentifier, groupRecord);
}
return true;
}
private static void CleanStaleCache()
{
// Clean Cache
var groupKeys = _DistinguishedNameCache.Keys.ToArray();
foreach (string groupKey in groupKeys)
{
Tuple<ActiveDirectoryGroup, DateTime> groupRecord;
if (_DistinguishedNameCache.TryGetValue(groupKey, out groupRecord))
{
if (groupRecord.Item2 <= DateTime.Now)
{
_DistinguishedNameCache.TryRemove(groupKey, out groupRecord);
}
}
}
// Clean SID Cache
groupKeys = _SecurityIdentifierCache.Keys.ToArray();
foreach (string groupKey in groupKeys)
{
Tuple<ActiveDirectoryGroup, DateTime> groupRecord;
if (_SecurityIdentifierCache.TryGetValue(groupKey, out groupRecord))
{
if (groupRecord.Item2 <= DateTime.Now)
{
_SecurityIdentifierCache.TryRemove(groupKey, out groupRecord);
}
}
}
}
public override string TaskName { get { return "AD Group Cache - Clean Stale Cache"; } }
public override bool SingleInstanceTask { get { return true; } }
public override bool CancelInitiallySupported { get { return false; } }
public override bool LogExceptionsOnly { get { return true; } }
public override void InitalizeScheduledTask(DiscoDataContext Database)
{
// Run @ every 15mins
// Next 15min interval
DateTime now = DateTime.Now;
int mins = (15 - (now.Minute % 15));
if (mins < 10)
mins += 15;
DateTimeOffset startAt = new DateTimeOffset(now).AddMinutes(mins).AddSeconds(now.Second * -1).AddMilliseconds(now.Millisecond * -1);
TriggerBuilder triggerBuilder = TriggerBuilder.Create().StartAt(startAt).
WithSchedule(SimpleScheduleBuilder.RepeatMinutelyForever(15));
this.ScheduleTask(triggerBuilder);
}
protected override void ExecuteTask()
{
CleanStaleCache();
}
}
}
@@ -1,19 +0,0 @@
using Disco.Models.Interop.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.BI.Interop.ActiveDirectory
{
public static class ActiveDirectoryGroupExtensions
{
public static IEnumerable<Tuple<string, string>> GetMembers(ActiveDirectoryGroup group)
{
throw new NotImplementedException();
}
}
}
@@ -1,198 +1,198 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using System.Threading;
//using System;
//using System.Collections;
//using System.Collections.Generic;
//using System.DirectoryServices;
//using System.DirectoryServices.ActiveDirectory;
//using System.Runtime.CompilerServices;
//using System.Runtime.InteropServices;
//using System.Security.Principal;
//using System.Text;
//using System.Threading;
namespace Disco.BI.Interop.ActiveDirectory
{
internal static class ActiveDirectoryHelpers
{
#region Static Cached Properties
private static string _DefaultDomainName;
private static string _DefaultDomainPDCName;
private static System.Collections.Generic.List<string> _DefaultDomainDCNames;
private static string _DefaultDomainNetBiosName;
private static string _DefaultDomainQualifiedName;
private static string _DefaultLdapPath;
private static bool _DetermineDomainProperties_Loaded = false;
private static object _DetermineDomainProperties_Lock = new object();
internal static string DefaultDomainName
{
get
{
ActiveDirectoryHelpers.DetermineDomainProperties();
return ActiveDirectoryHelpers._DefaultDomainName;
}
}
internal static string DefaultDomainPDCName
{
get
{
ActiveDirectoryHelpers.DetermineDomainProperties();
return ActiveDirectoryHelpers._DefaultDomainPDCName;
}
}
internal static System.Collections.Generic.List<string> DefaultDomainDCNames
{
get
{
ActiveDirectoryHelpers.DetermineDomainProperties();
return ActiveDirectoryHelpers._DefaultDomainDCNames;
}
}
internal static string DefaultDomainNetBiosName
{
get
{
ActiveDirectoryHelpers.DetermineDomainProperties();
return ActiveDirectoryHelpers._DefaultDomainNetBiosName;
}
}
internal static string DefaultDomainQualifiedName
{
get
{
ActiveDirectoryHelpers.DetermineDomainProperties();
return ActiveDirectoryHelpers._DefaultDomainQualifiedName;
}
}
internal static string DefaultLdapPath
{
get
{
ActiveDirectoryHelpers.DetermineDomainProperties();
return ActiveDirectoryHelpers._DefaultLdapPath;
}
}
internal static string DefaultDCLdapPath(string DC)
{
return string.Format("LDAP://{0}/", DC);
}
internal static DirectoryEntry DefaultLdapRoot
{
get
{
return new DirectoryEntry(string.Concat(ActiveDirectoryHelpers.DefaultLdapPath, ActiveDirectoryHelpers.DefaultDomainQualifiedName));
}
}
internal static DirectoryEntry DefaultDCLdapRoot(string DC)
{
return new DirectoryEntry(string.Concat(ActiveDirectoryHelpers.DefaultDCLdapPath(DC), ActiveDirectoryHelpers.DefaultDomainQualifiedName));
}
//namespace Disco.BI.Interop.ActiveDirectory
//{
// internal static class ActiveDirectoryHelpers
// {
// #region Static Cached Properties
// private static string _DefaultDomainName;
// private static string _DefaultDomainPDCName;
// private static System.Collections.Generic.List<string> _DefaultDomainDCNames;
// private static string _DefaultDomainNetBiosName;
// private static string _DefaultDomainQualifiedName;
// private static string _DefaultLdapPath;
// private static bool _DetermineDomainProperties_Loaded = false;
// private static object _DetermineDomainProperties_Lock = new object();
// internal static string DefaultDomainName
// {
// get
// {
// ActiveDirectoryHelpers.DetermineDomainProperties();
// return ActiveDirectoryHelpers._DefaultDomainName;
// }
// }
// internal static string DefaultDomainPDCName
// {
// get
// {
// ActiveDirectoryHelpers.DetermineDomainProperties();
// return ActiveDirectoryHelpers._DefaultDomainPDCName;
// }
// }
// internal static System.Collections.Generic.List<string> DefaultDomainDCNames
// {
// get
// {
// ActiveDirectoryHelpers.DetermineDomainProperties();
// return ActiveDirectoryHelpers._DefaultDomainDCNames;
// }
// }
// internal static string DefaultDomainNetBiosName
// {
// get
// {
// ActiveDirectoryHelpers.DetermineDomainProperties();
// return ActiveDirectoryHelpers._DefaultDomainNetBiosName;
// }
// }
// internal static string DefaultDomainQualifiedName
// {
// get
// {
// ActiveDirectoryHelpers.DetermineDomainProperties();
// return ActiveDirectoryHelpers._DefaultDomainQualifiedName;
// }
// }
// internal static string DefaultLdapPath
// {
// get
// {
// ActiveDirectoryHelpers.DetermineDomainProperties();
// return ActiveDirectoryHelpers._DefaultLdapPath;
// }
// }
// internal static string DefaultDCLdapPath(string DC)
// {
// return string.Format("LDAP://{0}/", DC);
// }
// internal static DirectoryEntry DefaultLdapRoot
// {
// get
// {
// return new DirectoryEntry(string.Concat(ActiveDirectoryHelpers.DefaultLdapPath, ActiveDirectoryHelpers.DefaultDomainQualifiedName));
// }
// }
// internal static DirectoryEntry DefaultDCLdapRoot(string DC)
// {
// return new DirectoryEntry(string.Concat(ActiveDirectoryHelpers.DefaultDCLdapPath(DC), ActiveDirectoryHelpers.DefaultDomainQualifiedName));
// }
private static void DetermineDomainProperties()
{
if (!ActiveDirectoryHelpers._DetermineDomainProperties_Loaded)
{
lock (ActiveDirectoryHelpers._DetermineDomainProperties_Lock)
{
// private static void DetermineDomainProperties()
// {
// if (!ActiveDirectoryHelpers._DetermineDomainProperties_Loaded)
// {
// lock (ActiveDirectoryHelpers._DetermineDomainProperties_Lock)
// {
if (!ActiveDirectoryHelpers._DetermineDomainProperties_Loaded)
{
using (Domain domain = Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain)))
{
ActiveDirectoryHelpers._DefaultDomainName = domain.Name;
ActiveDirectoryHelpers._DefaultDomainPDCName = domain.PdcRoleOwner.Name;
ActiveDirectoryHelpers._DefaultDomainDCNames = new System.Collections.Generic.List<string>(domain.DomainControllers.Count);
foreach (DomainController dc in domain.DomainControllers)
{
ActiveDirectoryHelpers._DefaultDomainDCNames.Add(dc.Name);
}
}
ActiveDirectoryHelpers._DefaultDomainQualifiedName = string.Format("DC={0}", ActiveDirectoryHelpers._DefaultDomainName.Replace(".", ",DC="));
ActiveDirectoryHelpers._DefaultLdapPath = string.Format("LDAP://{0}/", ActiveDirectoryHelpers._DefaultDomainPDCName);
using (DirectoryEntry entry = new DirectoryEntry(string.Format("{0}CN=Partitions,CN=Configuration,{1}", ActiveDirectoryHelpers._DefaultLdapPath, ActiveDirectoryHelpers._DefaultDomainQualifiedName)))
{
using (DirectorySearcher searcher = new DirectorySearcher(entry, "(&(objectClass=crossRef)(nETBIOSName=*))", new string[] { "nETBIOSName" }))
{
SearchResult result = searcher.FindOne();
if (result != null)
{
ActiveDirectoryHelpers._DefaultDomainNetBiosName = result.Properties["nETBIOSName"][0].ToString();
}
else
{
ActiveDirectoryHelpers._DefaultDomainNetBiosName = ActiveDirectoryHelpers._DefaultDomainQualifiedName;
}
}
}
}
ActiveDirectoryHelpers._DetermineDomainProperties_Loaded = true;
}
}
}
#endregion
// if (!ActiveDirectoryHelpers._DetermineDomainProperties_Loaded)
// {
// using (Domain domain = Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain)))
// {
// ActiveDirectoryHelpers._DefaultDomainName = domain.Name;
// ActiveDirectoryHelpers._DefaultDomainPDCName = domain.PdcRoleOwner.Name;
// ActiveDirectoryHelpers._DefaultDomainDCNames = new System.Collections.Generic.List<string>(domain.DomainControllers.Count);
// foreach (DomainController dc in domain.DomainControllers)
// {
// ActiveDirectoryHelpers._DefaultDomainDCNames.Add(dc.Name);
// }
// }
// ActiveDirectoryHelpers._DefaultDomainQualifiedName = string.Format("DC={0}", ActiveDirectoryHelpers._DefaultDomainName.Replace(".", ",DC="));
// ActiveDirectoryHelpers._DefaultLdapPath = string.Format("LDAP://{0}/", ActiveDirectoryHelpers._DefaultDomainPDCName);
// using (DirectoryEntry entry = new DirectoryEntry(string.Format("{0}CN=Partitions,CN=Configuration,{1}", ActiveDirectoryHelpers._DefaultLdapPath, ActiveDirectoryHelpers._DefaultDomainQualifiedName)))
// {
// using (DirectorySearcher searcher = new DirectorySearcher(entry, "(&(objectClass=crossRef)(nETBIOSName=*))", new string[] { "nETBIOSName" }))
// {
// SearchResult result = searcher.FindOne();
// if (result != null)
// {
// ActiveDirectoryHelpers._DefaultDomainNetBiosName = result.Properties["nETBIOSName"][0].ToString();
// }
// else
// {
// ActiveDirectoryHelpers._DefaultDomainNetBiosName = ActiveDirectoryHelpers._DefaultDomainQualifiedName;
// }
// }
// }
// }
// ActiveDirectoryHelpers._DetermineDomainProperties_Loaded = true;
// }
// }
// }
// #endregion
internal static string ConvertBytesToSDDLString(byte[] SID)
{
SecurityIdentifier sID = new SecurityIdentifier(SID, 0);
// internal static string ConvertBytesToSDDLString(byte[] SID)
// {
// SecurityIdentifier sID = new SecurityIdentifier(SID, 0);
return sID.ToString();
}
// return sID.ToString();
// }
internal static byte[] ConvertSDDLStringToBytes(string SidSsdlString)
{
SecurityIdentifier sID = new SecurityIdentifier(SidSsdlString);
// internal static byte[] ConvertSDDLStringToBytes(string SidSsdlString)
// {
// SecurityIdentifier sID = new SecurityIdentifier(SidSsdlString);
var sidBytes = new byte[sID.BinaryLength];
// var sidBytes = new byte[sID.BinaryLength];
sID.GetBinaryForm(sidBytes, 0);
// sID.GetBinaryForm(sidBytes, 0);
return sidBytes;
}
// return sidBytes;
// }
internal static byte[] BuildPrimaryGroupSid(byte[] UserSID, int PrimaryGroupId)
{
var groupSid = (byte[])UserSID.Clone();
// internal static byte[] BuildPrimaryGroupSid(byte[] UserSID, int PrimaryGroupId)
// {
// var groupSid = (byte[])UserSID.Clone();
int ridOffset = groupSid.Length - 4;
int groupId = PrimaryGroupId;
for (int i = 0; i < 4; i++)
{
groupSid[ridOffset + i] = (byte)(groupId & 0xFF);
groupId >>= 8;
}
// int ridOffset = groupSid.Length - 4;
// int groupId = PrimaryGroupId;
// for (int i = 0; i < 4; i++)
// {
// groupSid[ridOffset + i] = (byte)(groupId & 0xFF);
// groupId >>= 8;
// }
return groupSid;
}
// return groupSid;
// }
internal static string ConvertBytesToBinarySidString(byte[] SID)
{
StringBuilder escapedSid = new StringBuilder();
// internal static string ConvertBytesToBinarySidString(byte[] SID)
// {
// StringBuilder escapedSid = new StringBuilder();
foreach (var sidByte in SID)
{
escapedSid.Append('\\');
escapedSid.Append(sidByte.ToString("x2"));
}
// foreach (var sidByte in SID)
// {
// escapedSid.Append('\\');
// escapedSid.Append(sidByte.ToString("x2"));
// }
return escapedSid.ToString();
}
// return escapedSid.ToString();
// }
internal static string EscapeLdapQuery(string query)
{
return query.Replace("*", "\\2a").Replace("(", "\\28").Replace(")", "\\29").Replace("\\", "\\5c").Replace("NUL", "\\00").Replace("/", "\\2f");
}
internal static string FormatGuidForLdapQuery(System.Guid g)
{
checked
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
byte[] array = g.ToByteArray();
for (int i = 0; i < array.Length; i++)
{
byte b = array[i];
sb.Append("\\");
sb.Append(b.ToString("X2"));
}
return sb.ToString();
}
}
}
}
// internal static string EscapeLdapQuery(string query)
// {
// return query.Replace("*", "\\2a").Replace("(", "\\28").Replace(")", "\\29").Replace("\\", "\\5c").Replace("NUL", "\\00").Replace("/", "\\2f");
// }
// internal static string FormatGuidForLdapQuery(System.Guid g)
// {
// checked
// {
// System.Text.StringBuilder sb = new System.Text.StringBuilder();
// byte[] array = g.ToByteArray();
// for (int i = 0; i < array.Length; i++)
// {
// byte b = array[i];
// sb.Append("\\");
// sb.Append(b.ToString("X2"));
// }
// return sb.ToString();
// }
// }
// }
//}
@@ -1,301 +0,0 @@
using Disco.Models.Interop.ActiveDirectory;
using Disco.Models.Repository;
using System;
using System.Collections;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Text;
using System.Net.NetworkInformation;
using System.Management;
namespace Disco.BI.Interop.ActiveDirectory
{
public static class ActiveDirectoryMachineAccountExtensions
{
public static void DeleteAccount(this ActiveDirectoryMachineAccount account)
{
if (account.IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", account.DistinguishedName));
using (DirectoryEntry machineDE = new DirectoryEntry(account.Path))
{
DeleteAccountRecursive(machineDE);
using (var machineDEParent = machineDE.Parent)
{
machineDEParent.Children.Remove(machineDE);
}
}
}
private static void DeleteAccountRecursive(DirectoryEntry parent)
{
List<DirectoryEntry> children = new List<DirectoryEntry>();
foreach (DirectoryEntry child in parent.Children)
children.Add(child);
foreach (var child in children)
{
DeleteAccountRecursive(child);
parent.Children.Remove(child);
child.Dispose();
}
}
private static void SetNetbootGUID(this ActiveDirectoryMachineAccount account, System.Guid updatedNetbootGUID)
{
if (account.IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", account.DistinguishedName));
using (DirectoryEntry machineDE = new DirectoryEntry(account.Path))
{
PropertyValueCollection netbootGUIDProp = machineDE.Properties["netbootGUID"];
bool flag = netbootGUIDProp.Count > 0;
if (flag)
{
netbootGUIDProp.Clear();
}
netbootGUIDProp.Add(updatedNetbootGUID.ToByteArray());
machineDE.CommitChanges();
}
}
public static void SetDescription(this ActiveDirectoryMachineAccount account, string Description)
{
using (DirectoryEntry machineDE = new DirectoryEntry(account.Path))
{
PropertyValueCollection descriptionProp = machineDE.Properties["description"];
if (descriptionProp.Count > 0)
{
descriptionProp.Clear();
}
if (!string.IsNullOrEmpty(Description))
{
descriptionProp.Add(Description);
}
machineDE.CommitChanges();
}
}
public static void SetDescription(this ActiveDirectoryMachineAccount account, Device Device)
{
System.Text.StringBuilder descriptionBuilder = new System.Text.StringBuilder();
if (Device.AssignedUserId != null)
{
descriptionBuilder.Append(Device.AssignedUser.Id).Append(" (").Append(Device.AssignedUser.DisplayName).Append("); ");
}
if (Device.DeviceModelId.HasValue)
{
descriptionBuilder.Append(Device.DeviceModel.Description).Append("; ");
}
descriptionBuilder.Append(Device.DeviceProfile.Description).Append(";");
string description = descriptionBuilder.ToString().Trim();
if (description.Length > 1024)
{
description = description.Substring(0, 1024);
}
account.SetDescription(description);
}
public static void DisableAccount(this ActiveDirectoryMachineAccount account)
{
if (account.IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", account.DistinguishedName));
using (DirectoryEntry machineDE = new DirectoryEntry(account.Path))
{
int accountControl = (int)machineDE.Properties["userAccountControl"][0];
int updatedAccountControl = (accountControl | 2);
if (accountControl != updatedAccountControl)
{
machineDE.Properties["userAccountControl"][0] = updatedAccountControl;
machineDE.CommitChanges();
}
}
}
public static void EnableAccount(this ActiveDirectoryMachineAccount account)
{
if (account.IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", account.DistinguishedName));
using (DirectoryEntry machineDE = new DirectoryEntry(account.Path))
{
int accountControl = (int)machineDE.Properties["userAccountControl"][0];
if ((accountControl & 2) == 2)
{
int updatedAccountControl = (accountControl ^ 2);
machineDE.Properties["userAccountControl"][0] = updatedAccountControl;
machineDE.CommitChanges();
}
}
}
public static bool UpdateNetbootGUID(this ActiveDirectoryMachineAccount account, string UUID, string MACAddress)
{
if (account.IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", account.DistinguishedName));
System.Guid netbootGUID = System.Guid.Empty;
bool flag = !string.IsNullOrWhiteSpace(UUID);
if (flag)
{
netbootGUID = ActiveDirectoryMachineAccountExtensions.NetbootGUIDFromUUID(UUID);
}
else
{
flag = !string.IsNullOrWhiteSpace(MACAddress);
if (flag)
{
netbootGUID = ActiveDirectoryMachineAccountExtensions.NetbootGUIDFromMACAddress(MACAddress);
}
}
flag = (netbootGUID != System.Guid.Empty && netbootGUID != account.NetbootGUID);
bool UpdateNetbootGUID;
if (flag)
{
account.SetNetbootGUID(netbootGUID);
UpdateNetbootGUID = true;
}
else
{
UpdateNetbootGUID = false;
}
return UpdateNetbootGUID;
}
internal static System.Guid NetbootGUIDFromMACAddress(string MACAddress)
{
string strippedMACAddress = MACAddress.Trim().Replace(":", string.Empty).Replace("-", string.Empty);
bool flag = strippedMACAddress.Length == 12;
System.Guid NetbootGUIDFromMACAddress;
if (flag)
{
System.Guid guid = new System.Guid(string.Format("00000000-0000-0000-0000-{0}", strippedMACAddress));
NetbootGUIDFromMACAddress = guid;
}
else
{
NetbootGUIDFromMACAddress = System.Guid.Empty;
}
return NetbootGUIDFromMACAddress;
}
internal static System.Guid NetbootGUIDFromUUID(string UUID)
{
System.Guid result = new System.Guid(UUID);
return result;
}
public static object GetPropertyValue(this ActiveDirectoryMachineAccount account, string PropertyName, int Index = 0)
{
switch (PropertyName.ToLower())
{
case "name":
return account.Name;
case "samaccountname":
return account.SamAccountName;
case "distinguishedname":
return account.DistinguishedName;
case "objectsid":
return account.SecurityIdentifier;
case "netbootguid":
return account.NetbootGUID;
default:
object[] adProperty;
if (account.LoadedProperties.TryGetValue(PropertyName, out adProperty) && Index <= adProperty.Length)
return adProperty[Index];
else
return null;
}
}
public static IPStatus PingComputer(this ActiveDirectoryMachineAccount account, int Timeout = 2000)
{
using (var p = new Ping())
{
PingReply reply = p.Send(account.DnsName, Timeout);
return reply.Status;
}
}
// Didn't Work - WMI Limitation?
// G# - 2012-06-18
//public static void OnlineRenameComputer(this ActiveDirectoryMachineAccount account, string NewComputerName)
//{
// if (account.IsCriticalSystemObject)
// throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", account.DistinguishedName));
// try
// {
// IPStatus pingResult = account.PingComputer();
// if (pingResult != IPStatus.Success)
// throw new Exception(string.Format("Ping Error Result: {0}", pingResult.ToString()));
// }
// catch (Exception ex)
// {
// throw new Exception(string.Format("Error trying to Ping the Device: {0}; {1}", account.DnsName, ex.Message), ex);
// }
// ConnectionOptions wmiConnectionOptions = new ConnectionOptions()
// {
// Authentication = AuthenticationLevel.PacketPrivacy,
// Impersonation = ImpersonationLevel.Impersonate,
// EnablePrivileges = true,
// Timeout = new TimeSpan(0, 0, 6)
// };
// ManagementPath wmiPath = new ManagementPath()
// {
// Server = account.DnsName,
// NamespacePath = @"root\cimv2",
// ClassName = "Win32_ComputerSystem"
// };
// ManagementScope wmiScope = new ManagementScope(wmiPath, wmiConnectionOptions);
// ObjectGetOptions wmiGetOptions = new ObjectGetOptions() { Timeout = new TimeSpan(0, 1, 0) };
// using (ManagementClass wmiClass = new ManagementClass(wmiScope, wmiPath, wmiGetOptions))
// {
// foreach (ManagementObject wmiWin32ComputerSystem in wmiClass.GetInstances())
// {
// UInt32 result = (UInt32)wmiWin32ComputerSystem.InvokeMethod("Rename", new object[] { NewComputerName });
// if (result != 0)
// throw new Exception(string.Format("Error Renaming Computer; WMI Remote Method 'Rename' returned: {0}", result));
// }
// }
//}
public static void MoveOrganisationUnit(this ActiveDirectoryMachineAccount account, string NewOrganisationUnit)
{
if (account.IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", account.DistinguishedName));
var parentDistinguishedName = account.ParentDistinguishedName();
if (parentDistinguishedName != null && !parentDistinguishedName.Equals(NewOrganisationUnit, StringComparison.InvariantCultureIgnoreCase))
{
string ouPath;
if (string.IsNullOrWhiteSpace(NewOrganisationUnit))
ouPath = string.Format("{0}CN=Computers,{1}", ActiveDirectoryHelpers.DefaultLdapPath, ActiveDirectoryHelpers.DefaultDomainQualifiedName);
else
ouPath = string.Format("{0}{1},{2}", ActiveDirectoryHelpers.DefaultLdapPath, NewOrganisationUnit, ActiveDirectoryHelpers.DefaultDomainQualifiedName);
using (DirectoryEntry ou = new DirectoryEntry(ouPath))
{
using (DirectoryEntry i = new DirectoryEntry(account.Path) { UsePropertyCache = false })
{
i.MoveTo(ou);
}
}
}
}
public static string ParentDistinguishedName(this ActiveDirectoryMachineAccount account)
{
// Determine Parent
if (!string.IsNullOrWhiteSpace(account.DistinguishedName))
return account.DistinguishedName.Substring(0, account.DistinguishedName.IndexOf(",DC=")).Substring(account.DistinguishedName.IndexOf(",") + 1);
else
return null;
}
}
}
@@ -1,14 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
namespace Disco.BI.Interop.ActiveDirectory
{
public class ActiveDirectoryOrganisationalUnit
{
public string Name { get; set; }
public string Path { get; set; }
public List<ActiveDirectoryOrganisationalUnit> Children { get; set; }
}
}
//namespace Disco.BI.Interop.ActiveDirectory
//{
// public class ActiveDirectoryOrganisationalUnit
// {
// public string Name { get; set; }
// public string Path { get; set; }
// public List<ActiveDirectoryOrganisationalUnit> Children { get; set; }
// }
//}
@@ -1,264 +1,264 @@
using Disco.Data.Repository;
using Disco.Services.Logging;
using Disco.Models.Repository;
using Quartz;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.DirectoryServices;
using System.Linq;
using System.Linq.Expressions;
using System.Net.NetworkInformation;
using System.Reflection;
using Disco.Services.Tasks;
namespace Disco.BI.Interop.ActiveDirectory
{
public class ActiveDirectoryUpdateLastNetworkLogonDateJob : ScheduledTask
{
//using Disco.Data.Repository;
//using Disco.Services.Logging;
//using Disco.Models.Repository;
//using Quartz;
//using System;
//using System.Collections;
//using System.Collections.Generic;
//using System.Diagnostics;
//using System.DirectoryServices;
//using System.Linq;
//using System.Linq.Expressions;
//using System.Net.NetworkInformation;
//using System.Reflection;
//using Disco.Services.Tasks;
//namespace Disco.BI.Interop.ActiveDirectory
//{
// public class ActiveDirectoryUpdateLastNetworkLogonDateJob : ScheduledTask
// {
public override string TaskName { get { return "Active Directory - Update Last Network Logon Dates Task"; } }
public override bool SingleInstanceTask { get { return true; } }
public override bool CancelInitiallySupported { get { return false; } }
// public override string TaskName { get { return "Active Directory - Update Last Network Logon Dates Task"; } }
// public override bool SingleInstanceTask { get { return true; } }
// public override bool CancelInitiallySupported { get { return false; } }
public override void InitalizeScheduledTask(DiscoDataContext Database)
{
// ActiveDirectoryUpdateLastNetworkLogonDateJob @ 11:30pm
TriggerBuilder triggerBuilder = TriggerBuilder.Create().
WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(23, 30));
// public override void InitalizeScheduledTask(DiscoDataContext Database)
// {
// // ActiveDirectoryUpdateLastNetworkLogonDateJob @ 11:30pm
// TriggerBuilder triggerBuilder = TriggerBuilder.Create().
// WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(23, 30));
this.ScheduleTask(triggerBuilder);
}
// this.ScheduleTask(triggerBuilder);
// }
protected override void ExecuteTask()
{
int changeCount;
// protected override void ExecuteTask()
// {
// int changeCount;
this.Status.UpdateStatus(1, "Starting", "Connecting to the Database and initializing the environment");
using (DiscoDataContext database = new DiscoDataContext())
{
UpdateLastNetworkLogonDates(database, this.Status);
this.Status.UpdateStatus(95, "Updating Database", "Writing last network logon dates to the Database");
changeCount = database.SaveChanges();
this.Status.Finished(string.Format("{0} Device last network logon dates updated", changeCount), "/Config/SystemConfig");
}
// this.Status.UpdateStatus(1, "Starting", "Connecting to the Database and initializing the environment");
// using (DiscoDataContext database = new DiscoDataContext())
// {
// UpdateLastNetworkLogonDates(database, this.Status);
// this.Status.UpdateStatus(95, "Updating Database", "Writing last network logon dates to the Database");
// changeCount = database.SaveChanges();
// this.Status.Finished(string.Format("{0} Device last network logon dates updated", changeCount), "/Config/SystemConfig");
// }
SystemLog.LogInformation(new string[]
{
"Updated LastNetworkLogon Device Property for Device/s",
changeCount.ToString()
});
}
// SystemLog.LogInformation(new string[]
// {
// "Updated LastNetworkLogon Device Property for Device/s",
// changeCount.ToString()
// });
// }
public static ScheduledTaskStatus ScheduleImmediately()
{
var existingTask = ScheduledTasks.GetTaskStatuses(typeof(ActiveDirectoryUpdateLastNetworkLogonDateJob)).Where(s => s.IsRunning).FirstOrDefault();
if (existingTask != null)
return existingTask;
// public static ScheduledTaskStatus ScheduleImmediately()
// {
// var existingTask = ScheduledTasks.GetTaskStatuses(typeof(ActiveDirectoryUpdateLastNetworkLogonDateJob)).Where(s => s.IsRunning).FirstOrDefault();
// if (existingTask != null)
// return existingTask;
var instance = new ActiveDirectoryUpdateLastNetworkLogonDateJob();
return instance.ScheduleTask();
}
// var instance = new ActiveDirectoryUpdateLastNetworkLogonDateJob();
// return instance.ScheduleTask();
// }
public static bool UpdateLastNetworkLogonDate(Device Device)
{
System.DateTime? computerLastLogonDate = Device.LastNetworkLogonDate;
if (!string.IsNullOrEmpty(Device.ComputerName))
{
foreach (var dcName in ActiveDirectoryHelpers.DefaultDomainDCNames)
{
try
{
Ping p = new Ping();
PingReply pr;
try
{
pr = p.Send(dcName, 500);
}
finally
{
if (p != null)
{
((System.IDisposable)p).Dispose();
}
}
if (pr.Status == IPStatus.Success)
{
using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultDCLdapRoot(dcName))
{
DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectCategory=Computer)(sAMAccountName={0}$))", ActiveDirectoryHelpers.EscapeLdapQuery(Device.ComputerName)), new string[]
{
"lastLogon"
}, SearchScope.Subtree);
SearchResult dResult = dSearcher.FindOne();
if (dResult != null)
{
ResultPropertyValueCollection dProp = dResult.Properties["lastLogon"];
if (dProp != null && dProp.Count > 0)
{
long lastLogonInt = (long)dProp[0];
if (lastLogonInt > 0L)
{
System.DateTime computerNameDate = System.DateTime.FromFileTime(lastLogonInt);
if (computerLastLogonDate.HasValue)
{
if (System.DateTime.Compare(computerLastLogonDate.Value, computerNameDate) < 0)
{
computerLastLogonDate = computerNameDate;
}
}
else
{
computerLastLogonDate = computerNameDate;
}
}
}
}
// public static bool UpdateLastNetworkLogonDate(Device Device)
// {
// System.DateTime? computerLastLogonDate = Device.LastNetworkLogonDate;
// if (!string.IsNullOrEmpty(Device.ComputerName))
// {
// foreach (var dcName in ActiveDirectoryHelpers.DefaultDomainDCNames)
// {
// try
// {
// Ping p = new Ping();
// PingReply pr;
// try
// {
// pr = p.Send(dcName, 500);
// }
// finally
// {
// if (p != null)
// {
// ((System.IDisposable)p).Dispose();
// }
// }
// if (pr.Status == IPStatus.Success)
// {
// using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultDCLdapRoot(dcName))
// {
// DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectCategory=Computer)(sAMAccountName={0}$))", ActiveDirectoryHelpers.EscapeLdapQuery(Device.ComputerName)), new string[]
// {
// "lastLogon"
// }, SearchScope.Subtree);
// SearchResult dResult = dSearcher.FindOne();
// if (dResult != null)
// {
// ResultPropertyValueCollection dProp = dResult.Properties["lastLogon"];
// if (dProp != null && dProp.Count > 0)
// {
// long lastLogonInt = (long)dProp[0];
// if (lastLogonInt > 0L)
// {
// System.DateTime computerNameDate = System.DateTime.FromFileTime(lastLogonInt);
// if (computerLastLogonDate.HasValue)
// {
// if (System.DateTime.Compare(computerLastLogonDate.Value, computerNameDate) < 0)
// {
// computerLastLogonDate = computerNameDate;
// }
// }
// else
// {
// computerLastLogonDate = computerNameDate;
// }
// }
// }
// }
}
}
else
{
SystemLog.LogError(new string[]
{
string.Format("Unable to ping Domain Controller: '{0}' (ref: Disco.BI.Interop.ActiveDirectory.ActiveDirectoryUpdateLastNetworkLogonDateJob.UpdateDeviceLastNetworkLogonDate)", dcName)
});
}
}
catch (System.Exception ex)
{
SystemLog.LogException("UpdateDeviceLastNetworkLogonDate", ex);
}
}
}
bool UpdateLastNetworkLogonDate;
if (computerLastLogonDate.HasValue)
{
if (!Device.LastNetworkLogonDate.HasValue)
{
Device.LastNetworkLogonDate = computerLastLogonDate;
UpdateLastNetworkLogonDate = true;
return UpdateLastNetworkLogonDate;
}
if (System.DateTime.Compare(computerLastLogonDate.Value, Device.LastNetworkLogonDate.Value) > 0)
{
Device.LastNetworkLogonDate = computerLastLogonDate;
UpdateLastNetworkLogonDate = true;
return UpdateLastNetworkLogonDate;
}
}
UpdateLastNetworkLogonDate = false;
return UpdateLastNetworkLogonDate;
}
private static void UpdateLastNetworkLogonDates(DiscoDataContext Database, ScheduledTaskStatus status)
{
System.Collections.Generic.Dictionary<string, System.DateTime> computerLastLogonDates = new System.Collections.Generic.Dictionary<string, System.DateTime>();
// }
// }
// else
// {
// SystemLog.LogError(new string[]
// {
// string.Format("Unable to ping Domain Controller: '{0}' (ref: Disco.BI.Interop.ActiveDirectory.ActiveDirectoryUpdateLastNetworkLogonDateJob.UpdateDeviceLastNetworkLogonDate)", dcName)
// });
// }
// }
// catch (System.Exception ex)
// {
// SystemLog.LogException("UpdateDeviceLastNetworkLogonDate", ex);
// }
// }
// }
// bool UpdateLastNetworkLogonDate;
// if (computerLastLogonDate.HasValue)
// {
// if (!Device.LastNetworkLogonDate.HasValue)
// {
// Device.LastNetworkLogonDate = computerLastLogonDate;
// UpdateLastNetworkLogonDate = true;
// return UpdateLastNetworkLogonDate;
// }
// if (System.DateTime.Compare(computerLastLogonDate.Value, Device.LastNetworkLogonDate.Value) > 0)
// {
// Device.LastNetworkLogonDate = computerLastLogonDate;
// UpdateLastNetworkLogonDate = true;
// return UpdateLastNetworkLogonDate;
// }
// }
// UpdateLastNetworkLogonDate = false;
// return UpdateLastNetworkLogonDate;
// }
// private static void UpdateLastNetworkLogonDates(DiscoDataContext Database, ScheduledTaskStatus status)
// {
// System.Collections.Generic.Dictionary<string, System.DateTime> computerLastLogonDates = new System.Collections.Generic.Dictionary<string, System.DateTime>();
int progressDCCountTotal = ActiveDirectoryHelpers.DefaultDomainDCNames.Count;
int progressDCCount = 0;
double progressDCProgress = 0;
if (progressDCCountTotal > 0)
progressDCProgress = 90 / progressDCCountTotal;
// int progressDCCountTotal = ActiveDirectoryHelpers.DefaultDomainDCNames.Count;
// int progressDCCount = 0;
// double progressDCProgress = 0;
// if (progressDCCountTotal > 0)
// progressDCProgress = 90 / progressDCCountTotal;
foreach (var dcName in ActiveDirectoryHelpers.DefaultDomainDCNames)
{
try
{
PingReply pr;
using (Ping p = new Ping())
{
pr = p.Send(dcName, 2000);
}
if (pr.Status == IPStatus.Success)
{
using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultDCLdapRoot(dcName))
{
double progressDCStart = 5 + (progressDCCount * progressDCProgress);
status.UpdateStatus(progressDCStart, string.Format("Querying Domain Controller: {0}", dcName), "Searching...");
// foreach (var dcName in ActiveDirectoryHelpers.DefaultDomainDCNames)
// {
// try
// {
// PingReply pr;
// using (Ping p = new Ping())
// {
// pr = p.Send(dcName, 2000);
// }
// if (pr.Status == IPStatus.Success)
// {
// using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultDCLdapRoot(dcName))
// {
// double progressDCStart = 5 + (progressDCCount * progressDCProgress);
// status.UpdateStatus(progressDCStart, string.Format("Querying Domain Controller: {0}", dcName), "Searching...");
using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, "(objectCategory=Computer)", new string[] { "sAMAccountName", "lastLogon" }, SearchScope.Subtree))
{
using (SearchResultCollection dResults = dSearcher.FindAll())
{
// using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, "(objectCategory=Computer)", new string[] { "sAMAccountName", "lastLogon" }, SearchScope.Subtree))
// {
// using (SearchResultCollection dResults = dSearcher.FindAll())
// {
int progressItemCount = 0;
double progressItemProgress = dResults.Count == 0 ? 0 : (progressDCProgress / dResults.Count);
// int progressItemCount = 0;
// double progressItemProgress = dResults.Count == 0 ? 0 : (progressDCProgress / dResults.Count);
foreach (SearchResult dResult in dResults)
{
ResultPropertyValueCollection dProp = dResult.Properties["sAMAccountName"];
if (dProp != null && dProp.Count > 0)
{
string computerName = ((string)dProp[0]).TrimEnd(new char[] { '$' }).ToUpper();
// foreach (SearchResult dResult in dResults)
// {
// ResultPropertyValueCollection dProp = dResult.Properties["sAMAccountName"];
// if (dProp != null && dProp.Count > 0)
// {
// string computerName = ((string)dProp[0]).TrimEnd(new char[] { '$' }).ToUpper();
if (progressItemCount % 150 == 0) // Only Update Status every 150 devices
status.UpdateStatus(progressDCStart + (progressItemProgress * progressItemCount), string.Format("Analysing Device: {0}", computerName));
// if (progressItemCount % 150 == 0) // Only Update Status every 150 devices
// status.UpdateStatus(progressDCStart + (progressItemProgress * progressItemCount), string.Format("Analysing Device: {0}", computerName));
dProp = dResult.Properties["lastLogon"];
if (dProp != null && dProp.Count > 0)
{
long lastLogonInt = (long)dProp[0];
if (lastLogonInt > 0L)
{
System.DateTime computerNameDate = System.DateTime.FromFileTime(lastLogonInt);
System.DateTime existingDate;
if (computerLastLogonDates.TryGetValue(computerName, out existingDate))
{
if (System.DateTime.Compare(existingDate, computerNameDate) < 0)
{
computerLastLogonDates[computerName] = computerNameDate;
}
}
else
{
computerLastLogonDates[computerName] = computerNameDate;
}
}
}
}
progressItemCount++;
}
}
}
}
}
else
{
SystemLog.LogError(new string[]
{
string.Format("Unable to ping Domain Controller: '{0}' (ref: Disco.BI.Interop.ActiveDirectory.ActiveDirectoryUpdateLastNetworkLogonDateJob.UpdateLastNetworkLogonDates)", dcName)
});
}
}
catch (System.Exception ex)
{
SystemLog.LogException("UpdateLastNetworkLogonDates", ex);
}
progressDCCount++;
}
// dProp = dResult.Properties["lastLogon"];
// if (dProp != null && dProp.Count > 0)
// {
// long lastLogonInt = (long)dProp[0];
// if (lastLogonInt > 0L)
// {
// System.DateTime computerNameDate = System.DateTime.FromFileTime(lastLogonInt);
// System.DateTime existingDate;
// if (computerLastLogonDates.TryGetValue(computerName, out existingDate))
// {
// if (System.DateTime.Compare(existingDate, computerNameDate) < 0)
// {
// computerLastLogonDates[computerName] = computerNameDate;
// }
// }
// else
// {
// computerLastLogonDates[computerName] = computerNameDate;
// }
// }
// }
// }
// progressItemCount++;
// }
// }
// }
// }
// }
// else
// {
// SystemLog.LogError(new string[]
// {
// string.Format("Unable to ping Domain Controller: '{0}' (ref: Disco.BI.Interop.ActiveDirectory.ActiveDirectoryUpdateLastNetworkLogonDateJob.UpdateLastNetworkLogonDates)", dcName)
// });
// }
// }
// catch (System.Exception ex)
// {
// SystemLog.LogException("UpdateLastNetworkLogonDates", ex);
// }
// progressDCCount++;
// }
foreach (Device d in Database.Devices.Where(device => device.ComputerName != null))
{
DateTime computerLastLogonDate;
if (computerLastLogonDates.TryGetValue(d.ComputerName.ToUpper(), out computerLastLogonDate))
{
if (d.LastNetworkLogonDate.HasValue)
{
// Change accuracy to the second
computerLastLogonDate = new DateTime((computerLastLogonDate.Ticks / 10000000L) * 10000000L);
// foreach (Device d in Database.Devices.Where(device => device.ComputerName != null))
// {
// DateTime computerLastLogonDate;
// if (computerLastLogonDates.TryGetValue(d.ComputerName.ToUpper(), out computerLastLogonDate))
// {
// if (d.LastNetworkLogonDate.HasValue)
// {
// // Change accuracy to the second
// computerLastLogonDate = new DateTime((computerLastLogonDate.Ticks / 10000000L) * 10000000L);
if (System.DateTime.Compare(d.LastNetworkLogonDate.Value, computerLastLogonDate) < 0)
{
d.LastNetworkLogonDate = computerLastLogonDate;
}
}
else
{
d.LastNetworkLogonDate = computerLastLogonDate;
}
}
}
}
}
}
// if (System.DateTime.Compare(d.LastNetworkLogonDate.Value, computerLastLogonDate) < 0)
// {
// d.LastNetworkLogonDate = computerLastLogonDate;
// }
// }
// else
// {
// d.LastNetworkLogonDate = computerLastLogonDate;
// }
// }
// }
// }
// }
//}
@@ -1,37 +1,37 @@
using Disco.Models.Interop.ActiveDirectory;
using System;
using Disco.Models.Repository;
namespace Disco.BI.Interop.ActiveDirectory
{
internal static class ActiveDirectoryUserAccountExtensions
{
public static object GetPropertyValue(this ActiveDirectoryUserAccount account, string PropertyName, int Index = 0)
{
switch (PropertyName.ToLower())
{
case "name":
return account.Name;
case "samaccountname":
return account.SamAccountName;
case "distinguishedname":
return account.DistinguishedName;
case "objectsid":
return account.SecurityIdentifier;
case "sn":
return account.Surname;
case "givenname":
return account.GivenName;
case "mail":
return account.Email;
case "telephonenumber":
return account.Phone;
default:
object[] adProperty;
if (account.LoadedProperties.TryGetValue(PropertyName, out adProperty) && Index <= adProperty.Length)
return adProperty[Index];
else
return null;
}
}
}
}
//using Disco.Models.Interop.ActiveDirectory;
//using System;
//using Disco.Models.Repository;
//namespace Disco.BI.Interop.ActiveDirectory
//{
// internal static class ActiveDirectoryUserAccountExtensions
// {
// public static object GetPropertyValue(this ActiveDirectoryUserAccount account, string PropertyName, int Index = 0)
// {
// switch (PropertyName.ToLower())
// {
// case "name":
// return account.Name;
// case "samaccountname":
// return account.SamAccountName;
// case "distinguishedname":
// return account.DistinguishedName;
// case "objectsid":
// return account.SecurityIdentifier;
// case "sn":
// return account.Surname;
// case "givenname":
// return account.GivenName;
// case "mail":
// return account.Email;
// case "telephonenumber":
// return account.Phone;
// default:
// object[] adProperty;
// if (account.LoadedProperties.TryGetValue(PropertyName, out adProperty) && Index <= adProperty.Length)
// return adProperty[Index];
// else
// return null;
// }
// }
// }
//}
+7 -3
View File
@@ -65,6 +65,10 @@ namespace Disco.BI.Interop.Pdf
DataObjects = new object[DataObjectsIds.Length];
for (int idIndex = 0; idIndex < DataObjectsIds.Length; idIndex++)
{
string dataObjectId = DataObjectsIds[idIndex];
if (!dataObjectId.Contains('\\'))
dataObjectId = Disco.Services.Interop.ActiveDirectory.ActiveDirectory.PrimaryDomain.NetBiosName + @"\" + dataObjectId;
DataObjects[idIndex] = UserService.GetUser(DataObjectsIds[idIndex], Database, true);
if (DataObjects[idIndex] == null)
throw new Exception(string.Format("Unknown Username specified: {0}", DataObjectsIds[idIndex]));
@@ -122,7 +126,7 @@ namespace Disco.BI.Interop.Pdf
if (pdfFieldKey.Equals("DiscoAttachmentId", StringComparison.InvariantCultureIgnoreCase))
{
AcroFields.Item fields = pdfStamper.AcroFields.Fields[pdfFieldKey];
string fieldValue = dt.UniqueIdentifier(Data, CreatorUser.Id, TimeStamp);
string fieldValue = dt.UniqueIdentifier(Data, CreatorUser.UserId, TimeStamp);
if (FlattenFields)
pdfStamper.AcroFields.SetField(pdfFieldKey, String.Empty);
else
@@ -132,7 +136,7 @@ namespace Disco.BI.Interop.Pdf
for (int pdfFieldOrdinal = 0; pdfFieldOrdinal < fields.Size; pdfFieldOrdinal++)
{
AcroFields.FieldPosition pdfFieldPosition = pdfFieldPositions[pdfFieldOrdinal];
string pdfBarcodeContent = dt.UniquePageIdentifier(Data, CreatorUser.Id, TimeStamp, pdfFieldPosition.page);
string pdfBarcodeContent = dt.UniquePageIdentifier(Data, CreatorUser.UserId, TimeStamp, pdfFieldPosition.page);
BarcodeQRCode pdfBarcode = new BarcodeQRCode(pdfBarcodeContent, (int)pdfFieldPosition.position.Width, (int)pdfFieldPosition.position.Height, null);
iTextSharp.text.Image pdfBarcodeImage = pdfBarcode.GetImage();
pdfBarcodeImage.SetAbsolutePosition(pdfFieldPosition.position.Left, pdfFieldPosition.position.Bottom);
@@ -237,7 +241,7 @@ namespace Disco.BI.Interop.Pdf
JobLog jl = new JobLog()
{
JobId = j.Id,
TechUserId = CreatorUser.Id,
TechUserId = CreatorUser.UserId,
Timestamp = DateTime.Now
};
jl.Comments = string.Format("Document Generated{0}{1} [{2}]", Environment.NewLine, dt.Description, dt.Id);
@@ -61,7 +61,7 @@ namespace Disco.BI.Interop.SignalRHandlers
{
User u = (User)e.Entity;
var userDevices = e.Database.Devices.Where(d => d.AssignedUserId == u.Id);
var userDevices = e.Database.Devices.Where(d => d.AssignedUserId == u.UserId);
foreach (var userDevice in userDevices)
{
@@ -76,7 +76,7 @@ namespace Disco.BI.Interop.SignalRHandlers
{
User u = (User)e.Entity;
notificationContext.Connection.Broadcast(u.Id);
notificationContext.Connection.Broadcast(u.UserId);
}
}
}