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
+105 -54
View File
@@ -1,13 +1,14 @@
using Disco.BI.Extensions;
using Disco.BI.Interop.ActiveDirectory;
using Disco.Data.Repository;
using Disco.Models.ClientServices;
using Disco.Models.Interop.ActiveDirectory;
using Disco.Models.Repository;
using Disco.Services.Authorization;
using Disco.Services.Interop.ActiveDirectory;
using Disco.Services.Users;
using System;
using System.Collections.Generic;
using System.DirectoryServices.ActiveDirectory;
using System.Linq;
using System.Text.RegularExpressions;
using Tamir.SharpSsh;
@@ -242,7 +243,7 @@ namespace Disco.BI.DeviceBI
EnrolmentLog.LogSessionTaskAddedDevice(sessionId, Request.DeviceSerialNumber);
DeviceProfile deviceProfile = Database.DeviceProfiles.Find(Database.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId);
var deviceModelResult = Database.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim());
var deviceModelResult = Database.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModelType.Trim());
DeviceModel deviceModel = deviceModelResult.Item1;
if (deviceModelResult.Item2)
EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, deviceModelResult.Item1.Manufacturer, deviceModelResult.Item1.Model);
@@ -252,7 +253,7 @@ namespace Disco.BI.DeviceBI
RepoDevice = new Device
{
SerialNumber = Request.DeviceSerialNumber,
ComputerName = Request.DeviceComputerName,
DeviceDomainId = Request.DeviceComputerName,
DeviceProfile = deviceProfile,
DeviceModel = deviceModel,
AllowUnauthenticatedEnrol = false,
@@ -267,7 +268,7 @@ namespace Disco.BI.DeviceBI
EnrolmentLog.LogSessionTaskUpdatingDevice(sessionId, Request.DeviceSerialNumber);
if (!RepoDevice.DeviceModelId.HasValue || RepoDevice.DeviceModelId.Value == 1)
{
var deviceModelResult = Database.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim());
var deviceModelResult = Database.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModelType.Trim());
DeviceModel deviceModel = deviceModelResult.Item1;
if (deviceModelResult.Item2)
EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, deviceModelResult.Item1.Manufacturer, deviceModelResult.Item1.Model);
@@ -280,7 +281,7 @@ namespace Disco.BI.DeviceBI
{
EnrolmentLog.LogSessionDevice(sessionId, Request.DeviceSerialNumber, RepoDevice.DeviceModelId);
}
RepoDevice.ComputerName = Request.DeviceComputerName;
RepoDevice.DeviceDomainId = Request.DeviceComputerName;
if (!RepoDevice.EnrolledDate.HasValue)
{
RepoDevice.EnrolledDate = DateTime.Now;
@@ -294,14 +295,14 @@ namespace Disco.BI.DeviceBI
//if (RepoDeviceProfileContext.DistributionType == DeviceProfileConfiguration.DeviceProfileDistributionTypes.OneToOne && RepoDevice.AssignedUser != null)
if (RepoDevice.DeviceProfile.DistributionType == DeviceProfile.DistributionTypes.OneToOne && RepoDevice.AssignedUser != null)
{
ActiveDirectoryUserAccount AssignedUserInfo = ActiveDirectory.GetUserAccount(RepoDevice.AssignedUser.Id);
ActiveDirectoryUserAccount AssignedUserInfo = Disco.Services.Interop.ActiveDirectory.ActiveDirectory.RetrieveUserAccount(RepoDevice.AssignedUser.UserId);
EnrolmentLog.LogSessionTaskAssigningUser(sessionId, RepoDevice.SerialNumber, AssignedUserInfo.DisplayName, AssignedUserInfo.SamAccountName, AssignedUserInfo.Domain, AssignedUserInfo.SecurityIdentifier);
response.DeviceAssignedUserUsername = AssignedUserInfo.SamAccountName;
response.DeviceAssignedUserDomain = AssignedUserInfo.Domain;
response.DeviceAssignedUserName = AssignedUserInfo.DisplayName;
response.DeviceAssignedUserSID = AssignedUserInfo.SecurityIdentifier;
}
response.DeviceComputerName = RepoDevice.ComputerName;
response.DeviceComputerName = RepoDevice.DeviceDomainId;
EnrolmentLog.LogSessionProgress(sessionId, 100, "Completed Successfully");
}
catch (EnrolSafeException ex)
@@ -323,14 +324,26 @@ namespace Disco.BI.DeviceBI
}
public static EnrolResponse Enrol(DiscoDataContext Database, string Username, Models.ClientServices.Enrol Request)
{
ActiveDirectoryMachineAccount MachineInfo = null;
ActiveDirectoryMachineAccount adMachineAccount = null;
EnrolResponse response = new EnrolResponse();
AuthorizationToken authenticatedToken = null;
bool isAuthenticated = false;
ActiveDirectoryDomain domain = null;
Lazy<DomainController> domainController = new Lazy<DomainController>(() => {
if (domain == null)
throw new InvalidOperationException("The [domain] variable must be initialized first");
return domain.RetrieveWritableDomainController();
});
string sessionId = System.Guid.NewGuid().ToString("B");
response.SessionId = sessionId;
EnrolmentLog.LogSessionStarting(sessionId, Request.DeviceSerialNumber, EnrolmentTypes.Normal);
EnrolmentLog.LogSessionDeviceInfo(sessionId, Request);
try
{
EnrolmentLog.LogSessionProgress(sessionId, 10, "Loading User Data");
@@ -348,9 +361,9 @@ namespace Disco.BI.DeviceBI
if (!authenticatedToken.Has(Claims.Device.Actions.EnrolDevices))
{
if (!authenticatedToken.Has(Claims.ComputerAccount))
throw new EnrolSafeException(string.Format("Connection not correctly authenticated (SN: {0}; Auth User: {1})", Request.DeviceSerialNumber, authenticatedToken.User.Id));
if (!authenticatedToken.User.Id.Equals(string.Format("{0}$", Request.DeviceComputerName), System.StringComparison.InvariantCultureIgnoreCase))
throw new EnrolSafeException(string.Format("Connection not correctly authenticated (SN: {0}; Auth User: {1})", Request.DeviceSerialNumber, authenticatedToken.User.Id));
throw new EnrolSafeException(string.Format("Connection not correctly authenticated (SN: {0}; Auth User: {1})", Request.DeviceSerialNumber, authenticatedToken.User.UserId));
if (!authenticatedToken.User.UserId.Equals(string.Format("{0}$", Request.DeviceComputerName), System.StringComparison.InvariantCultureIgnoreCase))
throw new EnrolSafeException(string.Format("Connection not correctly authenticated (SN: {0}; Auth User: {1})", Request.DeviceSerialNumber, authenticatedToken.User.UserId));
}
}
else
@@ -380,10 +393,16 @@ namespace Disco.BI.DeviceBI
System.Guid? uuidGuid = null;
System.Guid? macAddressGuid = null;
if (!string.IsNullOrEmpty(Request.DeviceUUID))
uuidGuid = ActiveDirectoryMachineAccountExtensions.NetbootGUIDFromUUID(Request.DeviceUUID);
uuidGuid = ActiveDirectoryExtensions.NetbootGUIDFromUUID(Request.DeviceUUID);
if (!string.IsNullOrEmpty(Request.DeviceLanMacAddress))
macAddressGuid = ActiveDirectoryMachineAccountExtensions.NetbootGUIDFromMACAddress(Request.DeviceLanMacAddress);
MachineInfo = ActiveDirectory.GetMachineAccount(Request.DeviceComputerName, uuidGuid, macAddressGuid);
macAddressGuid = ActiveDirectoryExtensions.NetbootGUIDFromMACAddress(Request.DeviceLanMacAddress);
if (domain == null)
domain = ActiveDirectory.GetDomainByDnsName(Request.DeviceDNSDomainName);
var requestDeviceId = string.Format(@"{0}\{1}", domain.NetBiosName, Request.DeviceComputerName);
adMachineAccount = ActiveDirectory.RetrieveMachineAccount(domainController.Value, requestDeviceId, uuidGuid, macAddressGuid);
}
if (RepoDevice == null)
{
@@ -392,7 +411,7 @@ namespace Disco.BI.DeviceBI
DeviceProfile deviceProfile = Database.DeviceProfiles.Find(Database.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId);
var deviceModelResult = Database.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim());
var deviceModelResult = Database.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModelType.Trim());
DeviceModel deviceModel = deviceModelResult.Item1;
if (deviceModelResult.Item2)
EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, deviceModelResult.Item1.Manufacturer, deviceModelResult.Item1.Model);
@@ -402,7 +421,7 @@ namespace Disco.BI.DeviceBI
RepoDevice = new Device
{
SerialNumber = Request.DeviceSerialNumber,
ComputerName = Request.DeviceComputerName,
DeviceDomainId = Request.DeviceComputerName,
DeviceProfile = deviceProfile,
DeviceModel = deviceModel,
AllowUnauthenticatedEnrol = false,
@@ -423,7 +442,7 @@ namespace Disco.BI.DeviceBI
EnrolmentLog.LogSessionProgress(sessionId, 30, "Existing Device, Updating Disco Instance");
EnrolmentLog.LogSessionTaskUpdatingDevice(sessionId, Request.DeviceSerialNumber);
var deviceModelResult = Database.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim());
var deviceModelResult = Database.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModelType.Trim());
DeviceModel deviceModel = deviceModelResult.Item1;
if (deviceModelResult.Item2)
EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, deviceModelResult.Item1.Manufacturer, deviceModelResult.Item1.Model);
@@ -442,88 +461,120 @@ namespace Disco.BI.DeviceBI
RepoDevice.LastEnrolDate = DateTime.Now;
}
if (MachineInfo == null)
if (adMachineAccount == null)
{
if (isAuthenticated || RepoDevice.AllowUnauthenticatedEnrol)
{
if (RepoDevice.DeviceProfile.ProvisionADAccount)
{
EnrolmentLog.LogSessionProgress(sessionId, 50, "Provisioning an Active Directory Computer Account");
if (string.IsNullOrEmpty(RepoDevice.ComputerName) || RepoDevice.DeviceProfile.EnforceComputerNameConvention)
RepoDevice.ComputerName = RepoDevice.ComputerNameRender(Database);
EnrolmentLog.LogSessionTaskProvisioningADAccount(sessionId, RepoDevice.SerialNumber, RepoDevice.ComputerName);
MachineInfo = ActiveDirectory.GetMachineAccount(RepoDevice.ComputerName);
response.OfflineDomainJoin = ActiveDirectory.OfflineDomainJoinProvision(ref MachineInfo, RepoDevice.ComputerName, RepoDevice.DeviceProfile.OrganisationalUnit, sessionId);
if (string.IsNullOrWhiteSpace(RepoDevice.DeviceProfile.OrganisationalUnit))
throw new InvalidOperationException("No Organisational Unit has been set in the device profile");
if (domain == null)
domain = ActiveDirectory.GetDomainByDistinguishedName(RepoDevice.DeviceProfile.OrganisationalUnit);
if (string.IsNullOrEmpty(RepoDevice.DeviceDomainId) || RepoDevice.DeviceProfile.EnforceComputerNameConvention)
RepoDevice.DeviceDomainId = RepoDevice.ComputerNameRender(Database, domain);
string offlineProvisionDiagnosicInfo;
EnrolmentLog.LogSessionTaskProvisioningADAccount(sessionId, RepoDevice.SerialNumber, RepoDevice.DeviceDomainId);
adMachineAccount = ActiveDirectory.RetrieveMachineAccount(domainController.Value, RepoDevice.DeviceDomainId);
response.OfflineDomainJoin = ActiveDirectory.OfflineDomainJoinProvision(domain, domainController.Value, RepoDevice.DeviceDomainId, RepoDevice.DeviceProfile.OrganisationalUnit, ref adMachineAccount, out offlineProvisionDiagnosicInfo);
EnrolmentLog.LogSessionDiagnosticInformation(sessionId, offlineProvisionDiagnosicInfo);
response.RequireReboot = true;
}
if (MachineInfo != null)
if (adMachineAccount != null)
{
response.DeviceComputerName = MachineInfo.Name;
response.DeviceDomainName = MachineInfo.Domain;
response.DeviceComputerName = adMachineAccount.Name;
response.DeviceDomainName = adMachineAccount.Domain;
}
else
{
response.DeviceComputerName = RepoDevice.ComputerName;
response.DeviceDomainName = RepoDevice.ComputerName;
var computerId = Disco.Services.UserExtensions.SplitUserId(RepoDevice.DeviceDomainId);
response.DeviceDomainName = computerId.Item1;
response.DeviceComputerName = computerId.Item2;
}
}
else
{
RepoDevice.ComputerName = Request.DeviceComputerName;
response.DeviceComputerName = Request.DeviceComputerName;
response.DeviceDomainName = RepoDevice.ComputerName;
response.DeviceDomainName = Request.DeviceDNSDomainName;
}
}
else
{
RepoDevice.ComputerName = MachineInfo.Name;
response.DeviceComputerName = MachineInfo.Name;
response.DeviceDomainName = MachineInfo.Domain;
RepoDevice.DeviceDomainId = adMachineAccount.Name;
response.DeviceComputerName = adMachineAccount.Name;
response.DeviceDomainName = adMachineAccount.Domain;
// Enforce Computer Name Convention
if (!MachineInfo.IsCriticalSystemObject && RepoDevice.DeviceProfile.EnforceComputerNameConvention)
if (!adMachineAccount.IsCriticalSystemObject && RepoDevice.DeviceProfile.EnforceComputerNameConvention)
{
var calculatedComputerName = RepoDevice.ComputerNameRender(Database);
if (!Request.DeviceComputerName.Equals(calculatedComputerName, StringComparison.InvariantCultureIgnoreCase))
if (string.IsNullOrWhiteSpace(RepoDevice.DeviceProfile.OrganisationalUnit))
throw new InvalidOperationException("No Organisational Unit has been set in the device profile");
if (domain == null)
domain = ActiveDirectory.GetDomainByDistinguishedName(RepoDevice.DeviceProfile.OrganisationalUnit);
var calculatedComputerName = RepoDevice.ComputerNameRender(Database, domain);
var computerNameSplit = Disco.Services.UserExtensions.SplitUserId(calculatedComputerName);
if (!Request.DeviceComputerName.Equals(computerNameSplit.Item2, StringComparison.InvariantCultureIgnoreCase))
{
EnrolmentLog.LogSessionProgress(sessionId, 50, string.Format("Renaming Device: {0} -> {1}", Request.DeviceComputerName, calculatedComputerName));
EnrolmentLog.LogSessionTaskRenamingDevice(sessionId, Request.DeviceComputerName, calculatedComputerName);
RepoDevice.ComputerName = calculatedComputerName;
response.DeviceComputerName = calculatedComputerName;
RepoDevice.DeviceDomainId = calculatedComputerName;
response.DeviceDomainName = computerNameSplit.Item1;
response.DeviceComputerName = computerNameSplit.Item2;
// Create New Account
response.OfflineDomainJoin = ActiveDirectory.OfflineDomainJoinProvision(ref MachineInfo, RepoDevice.ComputerName, RepoDevice.DeviceProfile.OrganisationalUnit, sessionId);
string offlineProvisionDiagnosicInfo;
response.OfflineDomainJoin = ActiveDirectory.OfflineDomainJoinProvision(domain, domainController.Value, RepoDevice.DeviceDomainId, RepoDevice.DeviceProfile.OrganisationalUnit, ref adMachineAccount, out offlineProvisionDiagnosicInfo);
EnrolmentLog.LogSessionDiagnosticInformation(sessionId, offlineProvisionDiagnosicInfo);
response.RequireReboot = true;
}
}
// Enforce Organisation Unit
if (!MachineInfo.IsCriticalSystemObject && response.OfflineDomainJoin == null && RepoDevice.DeviceProfile.EnforceOrganisationalUnit)
// Enforce Organisational Unit
if (!adMachineAccount.IsCriticalSystemObject && response.OfflineDomainJoin == null && RepoDevice.DeviceProfile.EnforceOrganisationalUnit)
{
var parentDistinguishedName = MachineInfo.ParentDistinguishedName();
var parentDistinguishedName = adMachineAccount.ParentDistinguishedName();
if (string.IsNullOrWhiteSpace(RepoDevice.DeviceProfile.OrganisationalUnit))
throw new InvalidOperationException(string.Format("The Organisational Unit for the Device Profile '{0}' [{1}] is not set.", RepoDevice.DeviceProfile.Name, RepoDevice.DeviceProfile.Id));
if ((RepoDevice.DeviceProfile.OrganisationalUnit == null && parentDistinguishedName != null
&& parentDistinguishedName.Equals("CN=Computers", StringComparison.InvariantCultureIgnoreCase)) // Null (Default) OU
|| !parentDistinguishedName.Equals(RepoDevice.DeviceProfile.OrganisationalUnit, StringComparison.InvariantCultureIgnoreCase)) // Custom OU
if (!parentDistinguishedName.Equals(RepoDevice.DeviceProfile.OrganisationalUnit, StringComparison.InvariantCultureIgnoreCase)) // Custom OU
{
string newOU = RepoDevice.DeviceProfile.OrganisationalUnit ?? "CN=Computers";
var proposedDomain = ActiveDirectory.GetDomainByDistinguishedName(RepoDevice.DeviceProfile.OrganisationalUnit);
var currentDomain = ActiveDirectory.GetDomainByDistinguishedName(parentDistinguishedName);
if (currentDomain != proposedDomain)
throw new NotSupportedException("Unable to move the devices organisational unit when the source and destination domains are different.");
if (domain == null)
domain = proposedDomain;
else if (domain != proposedDomain)
throw new NotSupportedException("To many domains involved in this enrolment, contact support regarding your scenario.");
EnrolmentLog.LogSessionProgress(sessionId, 65, string.Format("Moving Device Organisation Unit: {0} -> {1}", parentDistinguishedName, newOU));
EnrolmentLog.LogSessionTaskMovingDeviceOrganisationUnit(sessionId, parentDistinguishedName, newOU);
MachineInfo.MoveOrganisationUnit(RepoDevice.DeviceProfile.OrganisationalUnit);
MachineInfo = ActiveDirectory.GetMachineAccount(MachineInfo.SamAccountName);
EnrolmentLog.LogSessionProgress(sessionId, 65, string.Format("Moving Device Organisational Unit: {0} -> {1}", parentDistinguishedName, RepoDevice.DeviceProfile.OrganisationalUnit));
EnrolmentLog.LogSessionTaskMovingDeviceOrganisationUnit(sessionId, parentDistinguishedName, RepoDevice.DeviceProfile.OrganisationalUnit);
adMachineAccount.MoveOrganisationalUnit(domainController.Value, RepoDevice.DeviceProfile.OrganisationalUnit);
adMachineAccount = ActiveDirectory.RetrieveMachineAccount(domainController.Value, adMachineAccount.NetBiosId);
response.RequireReboot = true;
}
}
}
if (MachineInfo != null && !MachineInfo.IsCriticalSystemObject)
if (adMachineAccount != null && !adMachineAccount.IsCriticalSystemObject)
{
EnrolmentLog.LogSessionProgress(sessionId, 75, "Updating Active Directory Computer Account Properties");
MachineInfo.UpdateNetbootGUID(Request.DeviceUUID, Request.DeviceLanMacAddress);
adMachineAccount.UpdateNetbootGUID(Request.DeviceUUID, Request.DeviceLanMacAddress);
if (RepoDevice.AssignedUser != null)
MachineInfo.SetDescription(RepoDevice);
adMachineAccount.SetDescription(RepoDevice);
}
if (RepoDevice.DeviceProfile.DistributionType == DeviceProfile.DistributionTypes.OneToOne)
{
@@ -534,7 +585,7 @@ namespace Disco.BI.DeviceBI
else
{
EnrolmentLog.LogSessionProgress(sessionId, 80, "Retrieving Active Directory Assigned User Account");
ActiveDirectoryUserAccount AssignedUserInfo = ActiveDirectory.GetUserAccount(RepoDevice.AssignedUser.Id);
ActiveDirectoryUserAccount AssignedUserInfo = Services.Interop.ActiveDirectory.ActiveDirectory.RetrieveUserAccount(RepoDevice.AssignedUser.UserId);
EnrolmentLog.LogSessionTaskAssigningUser(sessionId, RepoDevice.SerialNumber, AssignedUserInfo.DisplayName, AssignedUserInfo.SamAccountName, AssignedUserInfo.Domain, AssignedUserInfo.SecurityIdentifier);
response.AllowBootstrapperUninstall = true;
response.DeviceAssignedUserIsLocalAdmin = RepoDevice.DeviceProfile.AssignedUserLocalAdmin;
@@ -1,10 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Disco.BI.Extensions;
using Disco.Models.Repository;
using Disco.BI.Extensions;
using Disco.BI.Interop.ActiveDirectory;
using Disco.Services.Interop.ActiveDirectory;
using System;
namespace Disco.BI.Expressions.Extensions
{
@@ -1,10 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Disco.BI.Extensions;
using Disco.Models.Repository;
using Disco.BI.Extensions;
using Disco.BI.Interop.ActiveDirectory;
using Disco.Services.Interop.ActiveDirectory;
using System;
namespace Disco.BI.Expressions.Extensions
{
@@ -48,7 +48,7 @@ namespace Disco.BI.Extensions
WhoAmIResponse response = new WhoAmIResponse()
{
Username = token.User.Id,
Username = token.User.UserId,
DisplayName = token.User.DisplayName,
Type = token.Has(Claims.ComputerAccount) ? "Computer Account" : "User Account"
};
@@ -1,12 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Disco.Data.Repository;
using Disco.Models.Repository;
using Disco.Data.Repository;
using Disco.BI.Interop.ActiveDirectory;
using Disco.Services.Users;
using Disco.Services.Authorization;
using Disco.Services.Interop.ActiveDirectory;
using Disco.Services.Users;
using System;
using System.Linq;
namespace Disco.BI.Extensions
{
@@ -90,7 +88,7 @@ namespace Disco.BI.Extensions
d.DecommissionReason = Reason;
// Disable AD Account
if (d.ComputerName != null)
if (d.DeviceDomainId != null)
{
var adAccount = d.ActiveDirectoryAccount();
if (adAccount != null && !adAccount.IsCriticalSystemObject)
@@ -117,7 +115,7 @@ namespace Disco.BI.Extensions
d.DecommissionReason = null;
// Enable AD Account
if (d.ComputerName != null)
if (d.DeviceDomainId != null)
{
var adAccount = d.ActiveDirectoryAccount();
if (adAccount != null && !adAccount.IsCriticalSystemObject)
@@ -157,10 +155,10 @@ namespace Disco.BI.Extensions
JobLog jobLog = new JobLog()
{
JobId = j.Id,
TechUserId = UserService.CurrentUser.Id,
TechUserId = UserService.CurrentUser.UserId,
Timestamp = DateTime.Now,
Comments = string.Format("Device Deleted{0}{0}Serial Number: {1}{0}Computer Name: {2}{0}Model: {3}{0}Profile: {4}",
Environment.NewLine, d.SerialNumber, d.ComputerName, d.DeviceModel, d.DeviceProfile)
Environment.NewLine, d.SerialNumber, d.DeviceDomainId, d.DeviceModel, d.DeviceProfile)
};
Database.JobLogs.Add(jobLog);
}
+15 -11
View File
@@ -1,5 +1,4 @@
using System.Linq;
using Disco.BI.Interop.ActiveDirectory;
using Disco.Data.Configuration;
using Disco.Data.Repository;
using Disco.Models.BI.DocumentTemplates;
@@ -10,14 +9,18 @@ using System.IO;
using Disco.Models.Interop.ActiveDirectory;
using Disco.Services.Users;
using Disco.Services.Authorization;
using Disco.Services.Interop.ActiveDirectory;
namespace Disco.BI.Extensions
{
public static class DeviceExtensions
{
public static string ComputerNameRender(this Device device, DiscoDataContext Database)
public static string ComputerNameRender(this Device device, DiscoDataContext Database, ActiveDirectoryDomain Domain)
{
if (Domain == null)
throw new ArgumentNullException("Domain");
DeviceProfile deviceProfile = device.DeviceProfile;
Expressions.Expression computerNameTemplateExpression = null;
computerNameTemplateExpression = Expressions.ExpressionCache.GetValue(DeviceProfileExtensions.ComputerNameExpressionCacheModule, deviceProfile.Id.ToString(), () =>
@@ -40,7 +43,8 @@ namespace Disco.BI.Extensions
{
throw new System.InvalidOperationException("The rendered computer name would be invalid or longer than 24 characters");
}
return rendered.ToString();
return string.Format(@"{0}\{1}", Domain.NetBiosName, rendered);
}
public static System.Collections.Generic.List<DocumentTemplate> AvailableDocumentTemplates(this Device d, DiscoDataContext Database, User User, System.DateTime TimeStamp)
{
@@ -52,7 +56,7 @@ namespace Disco.BI.Extensions
public static bool UpdateLastNetworkLogonDate(this Device Device)
{
return ActiveDirectoryUpdateLastNetworkLogonDateJob.UpdateLastNetworkLogonDate(Device);
return Disco.Services.Interop.ActiveDirectory.Internal.ADUpdateLastNetworkLogonDateJob.UpdateLastNetworkLogonDate(Device);
}
public static DeviceAttachment CreateAttachment(this Device Device, DiscoDataContext Database, User CreatorUser, string Filename, string MimeType, string Comments, Stream Content, DocumentTemplate DocumentTemplate = null, byte[] PdfThumbnail = null)
@@ -63,7 +67,7 @@ namespace Disco.BI.Extensions
DeviceAttachment da = new DeviceAttachment()
{
DeviceSerialNumber = Device.SerialNumber,
TechUserId = CreatorUser.Id,
TechUserId = CreatorUser.UserId,
Filename = Filename,
MimeType = MimeType,
Timestamp = DateTime.Now,
@@ -160,12 +164,12 @@ namespace Disco.BI.Extensions
newDua = new DeviceUserAssignment()
{
DeviceSerialNumber = d.SerialNumber,
AssignedUserId = u.Id,
AssignedUserId = u.UserId,
AssignedDate = DateTime.Now
};
Database.DeviceUserAssignments.Add(newDua);
d.AssignedUserId = u.Id;
d.AssignedUserId = u.UserId;
d.AssignedUser = u;
}
else
@@ -174,9 +178,9 @@ namespace Disco.BI.Extensions
}
// Update AD Account
if (!string.IsNullOrEmpty(d.ComputerName) && d.ComputerName.Length <= 24)
if (!string.IsNullOrEmpty(d.DeviceDomainId))
{
var adMachineAccount = Interop.ActiveDirectory.ActiveDirectory.GetMachineAccount(d.ComputerName);
var adMachineAccount = ActiveDirectory.RetrieveMachineAccount(d.DeviceDomainId);
if (adMachineAccount != null)
{
adMachineAccount.SetDescription(d);
@@ -188,8 +192,8 @@ namespace Disco.BI.Extensions
public static ActiveDirectoryMachineAccount ActiveDirectoryAccount(this Device Device, params string[] AdditionalProperties)
{
if (!string.IsNullOrEmpty(Device.ComputerName))
return Interop.ActiveDirectory.ActiveDirectory.GetMachineAccount(Device.ComputerName, AdditionalProperties: AdditionalProperties);
if (!string.IsNullOrEmpty(Device.DeviceDomainId))
return ActiveDirectory.RetrieveMachineAccount(Device.DeviceDomainId, AdditionalProperties: AdditionalProperties);
else
return null;
}
@@ -136,7 +136,7 @@ namespace Disco.BI.Extensions
if (!(Data is User))
throw new ArgumentException("This Document Template is configured for Users only", "Data");
User d3 = (User)Data;
return d3.Id;
return d3.UserId;
default:
throw new InvalidOperationException("Invalid Document Template Scope");
}
+12 -12
View File
@@ -41,7 +41,7 @@ namespace Disco.BI.Extensions
throw new InvalidOperationException("Holding Device was Denied");
j.DeviceHeld = DateTime.Now;
j.DeviceHeldTechUserId = Technician.Id;
j.DeviceHeldTechUserId = Technician.UserId;
j.DeviceReadyForReturn = null;
j.DeviceReadyForReturnTechUserId = null;
j.DeviceReturnedDate = null;
@@ -64,7 +64,7 @@ namespace Disco.BI.Extensions
throw new InvalidOperationException("Device Ready for Return was Denied");
j.DeviceReadyForReturn = DateTime.Now;
j.DeviceReadyForReturnTechUserId = Technician.Id;
j.DeviceReadyForReturnTechUserId = Technician.UserId;
}
#endregion
@@ -83,7 +83,7 @@ namespace Disco.BI.Extensions
throw new InvalidOperationException("Device Return was Denied");
j.DeviceReturnedDate = DateTime.Now;
j.DeviceReturnedTechUserId = Technician.Id;
j.DeviceReturnedTechUserId = Technician.UserId;
}
#endregion
@@ -106,7 +106,7 @@ namespace Disco.BI.Extensions
JobLog jobLog = new JobLog()
{
JobId = j.Id,
TechUserId = Technician.Id,
TechUserId = Technician.UserId,
Timestamp = DateTime.Now,
Comments = string.Format("Waiting on User Action{0}Reason: {1}", Environment.NewLine, Reason)
};
@@ -133,7 +133,7 @@ namespace Disco.BI.Extensions
JobLog jobLog = new JobLog()
{
JobId = j.Id,
TechUserId = Technician.Id,
TechUserId = Technician.UserId,
Timestamp = DateTime.Now,
Comments = string.Format("User Action Resolved{0}Resolution: {1}", Environment.NewLine, Resolution)
};
@@ -178,7 +178,7 @@ namespace Disco.BI.Extensions
JobLog jobLog = new JobLog()
{
JobId = j.Id,
TechUserId = TechUser.Id,
TechUserId = TechUser.UserId,
Timestamp = DateTime.Now,
Comments = string.Format("Warranty Claim Submitted{0}{0}Provider: {1}{0}Repair Address: {2}{0}Provider Reference: {3}{0}{0}{4}", Environment.NewLine, WarrantyProvider.Manifest.Name, Address.Name, providerRef, FaultDescription)
};
@@ -248,7 +248,7 @@ namespace Disco.BI.Extensions
Database.JobComponents.Add(new JobComponent()
{
Job = j,
TechUserId = techUser.Id,
TechUserId = techUser.UserId,
Cost = component.Cost,
Description = component.Description
});
@@ -258,7 +258,7 @@ namespace Disco.BI.Extensions
JobLog jobLog = new JobLog()
{
JobId = j.Id,
TechUserId = techUser.Id,
TechUserId = techUser.UserId,
Timestamp = DateTime.Now,
Comments = string.Format("Job Type Converted{0}From: {1}{0}To: {2}", Environment.NewLine, Database.JobTypes.Find(JobType.JobTypeIds.HWar), Database.JobTypes.Find(JobType.JobTypeIds.HNWar))
};
@@ -302,7 +302,7 @@ namespace Disco.BI.Extensions
var techUser = UserService.CurrentUser;
j.JobMetaInsurance.ClaimFormSentDate = DateTime.Now;
j.JobMetaInsurance.ClaimFormSentUserId = techUser.Id;
j.JobMetaInsurance.ClaimFormSentUserId = techUser.UserId;
}
#endregion
@@ -356,7 +356,7 @@ namespace Disco.BI.Extensions
throw new InvalidOperationException("Close was Denied");
j.ClosedDate = DateTime.Now;
j.ClosedTechUserId = Technician.Id;
j.ClosedTechUserId = Technician.UserId;
}
private static bool CanCloseNever(this Job j, JobQueueJob IgnoreJobQueueJob = null)
@@ -475,14 +475,14 @@ namespace Disco.BI.Extensions
JobLog jobLog = new JobLog()
{
JobId = j.Id,
TechUserId = Technician.Id,
TechUserId = Technician.UserId,
Timestamp = DateTime.Now,
Comments = string.Format("Job Forcibly Closed{0}Reason: {1}", Environment.NewLine, Reason)
};
Database.JobLogs.Add(jobLog);
j.ClosedDate = DateTime.Now;
j.ClosedTechUserId = Technician.Id;
j.ClosedTechUserId = Technician.UserId;
}
#endregion
+3 -3
View File
@@ -22,7 +22,7 @@ namespace Disco.BI.Extensions
JobAttachment ja = new JobAttachment()
{
JobId = Job.Id,
TechUserId = CreatorUser.Id,
TechUserId = CreatorUser.UserId,
Filename = Filename,
MimeType = MimeType,
Timestamp = DateTime.Now,
@@ -148,7 +148,7 @@ namespace Disco.BI.Extensions
Database.JobLogs.Add(new JobLog()
{
JobId = j.Id,
TechUserId = TechUser.Id,
TechUserId = TechUser.UserId,
Timestamp = DateTime.Now,
Comments = logBuilder.ToString()
});
@@ -182,7 +182,7 @@ namespace Disco.BI.Extensions
Database.JobComponents.Add(new JobComponent()
{
Job = j,
TechUserId = TechUser.Id,
TechUserId = TechUser.UserId,
Cost = c.Cost,
Description = c.Description
});
@@ -149,7 +149,7 @@ namespace Disco.BI.Extensions
throw new InvalidOperationException("Removing job from queue is Denied");
jqj.RemovedDate = DateTime.Now;
jqj.RemovedUserId = Technician.Id;
jqj.RemovedUserId = Technician.UserId;
jqj.RemovedComment = string.IsNullOrWhiteSpace(Comment) ? null : Comment.Trim();
}
#endregion
@@ -201,7 +201,7 @@ namespace Disco.BI.Extensions
JobQueueId = jq.Id,
JobId = j.Id,
AddedDate = DateTime.Now,
AddedUserId = Technician.Id,
AddedUserId = Technician.UserId,
AddedComment = string.IsNullOrWhiteSpace(Comment) ? null : Comment.Trim(),
SLAExpiresDate = SLAExpires,
Priority = Priority
+3 -3
View File
@@ -19,8 +19,8 @@ namespace Disco.BI.Extensions
UserAttachment ua = new UserAttachment()
{
UserId = User.Id,
TechUserId = CreatorUser.Id,
UserId = User.UserId,
TechUserId = CreatorUser.UserId,
Filename = Filename,
MimeType = MimeType,
Timestamp = DateTime.Now,
@@ -59,7 +59,7 @@ namespace Disco.BI.Extensions
}
public static ActiveDirectoryUserAccount ActiveDirectoryAccount(this User User, params string[] AdditionalProperties)
{
return Interop.ActiveDirectory.ActiveDirectory.GetUserAccount(User.Id, AdditionalProperties);
return Disco.Services.Interop.ActiveDirectory.ActiveDirectory.RetrieveUserAccount(User.UserId, AdditionalProperties);
}
public static bool CanCreateJob(this User u)
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);
}
}
}
+4 -4
View File
@@ -15,7 +15,7 @@ namespace Disco.BI.JobBI
Job j = new Job()
{
JobType = type,
OpenedTechUserId = initialTech.Id,
OpenedTechUserId = initialTech.UserId,
OpenedTechUser = initialTech,
OpenedDate = DateTime.Now
};
@@ -31,7 +31,7 @@ namespace Disco.BI.JobBI
if (user != null)
{
j.User = user;
j.UserId = user.Id;
j.UserId = user.UserId;
}
// Sub Types
@@ -61,7 +61,7 @@ namespace Disco.BI.JobBI
JobQueueId = queue.queue.Id,
Job = j,
AddedDate = DateTime.Now,
AddedUserId = initialTech.Id,
AddedUserId = initialTech.UserId,
AddedComment = commentBuilder.ToString(),
SLAExpiresDate = queue.queue.DefaultSLAExpiry.HasValue ? (DateTime?)DateTime.Now.AddMinutes(queue.queue.DefaultSLAExpiry.Value) : null,
Priority = JobQueuePriority.Normal
@@ -110,7 +110,7 @@ namespace Disco.BI.JobBI
Database.JobComponents.Add(new JobComponent()
{
Job = j,
TechUserId = initialTech.Id,
TechUserId = initialTech.UserId,
Cost = c.Cost,
Description = c.Description
});