Permissions & Authorization for Users #24

Initial Release; Includes Database and MVC refactoring
This commit is contained in:
Gary Sharp
2013-10-10 19:13:16 +11:00
parent 172ce5524a
commit a099d68915
458 changed files with 40221 additions and 12130 deletions
+2 -2
View File
@@ -10,9 +10,9 @@ namespace Disco.BI
public static class DataStore public static class DataStore
{ {
public static string CreateLocation(DiscoDataContext dbContext, string SubLocation, DateTime? SubSubLocationTimestamp = null) public static string CreateLocation(DiscoDataContext Database, string SubLocation, DateTime? SubSubLocationTimestamp = null)
{ {
return CreateLocation(dbContext.DiscoConfiguration, SubLocation, SubSubLocationTimestamp); return CreateLocation(Database.DiscoConfiguration, SubLocation, SubSubLocationTimestamp);
} }
public static string CreateLocation(SystemConfiguration DiscoConfiguration, string SubLocation, DateTime? SubSubLocationTimestamp = null) public static string CreateLocation(SystemConfiguration DiscoConfiguration, string SubLocation, DateTime? SubSubLocationTimestamp = null)
{ {
+1 -1
View File
@@ -9,7 +9,7 @@ namespace Disco.BI.DeviceBI
{ {
public static class BatchUtilities public static class BatchUtilities
{ {
public static DeviceBatch DefaultNewDeviceBatch(DiscoDataContext dbContext) public static DeviceBatch DefaultNewDeviceBatch(DiscoDataContext Database)
{ {
return new DeviceBatch() return new DeviceBatch()
{ {
+3 -3
View File
@@ -32,7 +32,7 @@ namespace Disco.BI
if (deviceModel == null) if (deviceModel == null)
{ {
// Create the Device Model in a different DataContext so we don't have to commit unrelated changes // Create the Device Model in a different DataContext so we don't have to commit unrelated changes
using (DiscoDataContext dbContext = new DiscoDataContext()) using (DiscoDataContext database = new DiscoDataContext())
{ {
var addDeviceModel = new DeviceModel var addDeviceModel = new DeviceModel
{ {
@@ -41,8 +41,8 @@ namespace Disco.BI
ModelType = ModelType, ModelType = ModelType,
Description = string.Format("{0} {1}", Manufacturer, Model) Description = string.Format("{0} {1}", Manufacturer, Model)
}; };
dbContext.DeviceModels.Add(addDeviceModel); database.DeviceModels.Add(addDeviceModel);
dbContext.SaveChanges(); database.SaveChanges();
} }
// Obtain the Device Model with the in-scope DataContext // Obtain the Device Model with the in-scope DataContext
+44 -39
View File
@@ -11,6 +11,8 @@ using Disco.Models.Repository;
using Tamir.SharpSsh; using Tamir.SharpSsh;
using Disco.Services.Plugins; using Disco.Services.Plugins;
using Disco.Services.Plugins.Features.CertificateProvider; using Disco.Services.Plugins.Features.CertificateProvider;
using Disco.Services.Users;
using Disco.Services.Authorization;
namespace Disco.BI.DeviceBI namespace Disco.BI.DeviceBI
{ {
@@ -24,7 +26,7 @@ namespace Disco.BI.DeviceBI
} }
private static Regex SshPromptRegEx = new Regex("[\\$,\\#]", RegexOptions.Multiline); private static Regex SshPromptRegEx = new Regex("[\\$,\\#]", RegexOptions.Multiline);
public static MacSecureEnrolResponse MacSecureEnrol(DiscoDataContext dbContext, string Host) public static MacSecureEnrolResponse MacSecureEnrol(DiscoDataContext Database, string Host)
{ {
MacEnrol trustedRequest = new MacEnrol(); MacEnrol trustedRequest = new MacEnrol();
string sessionId = System.Guid.NewGuid().ToString("B"); string sessionId = System.Guid.NewGuid().ToString("B");
@@ -32,8 +34,8 @@ namespace Disco.BI.DeviceBI
try try
{ {
EnrolmentLog.LogSessionStarting(sessionId, Host, EnrolmentTypes.MacSecure); EnrolmentLog.LogSessionStarting(sessionId, Host, EnrolmentTypes.MacSecure);
EnrolmentLog.LogSessionProgress(sessionId, 0, string.Format("Connecting to '{0}' as '{1}'", Host, dbContext.DiscoConfiguration.Bootstrapper.MacSshUsername)); EnrolmentLog.LogSessionProgress(sessionId, 0, string.Format("Connecting to '{0}' as '{1}'", Host, Database.DiscoConfiguration.Bootstrapper.MacSshUsername));
SshShell shell = new SshShell(Host, dbContext.DiscoConfiguration.Bootstrapper.MacSshUsername, dbContext.DiscoConfiguration.Bootstrapper.MacSshPassword); SshShell shell = new SshShell(Host, Database.DiscoConfiguration.Bootstrapper.MacSshUsername, Database.DiscoConfiguration.Bootstrapper.MacSshPassword);
try try
{ {
shell.ExpectPattern = "#"; shell.ExpectPattern = "#";
@@ -55,7 +57,7 @@ namespace Disco.BI.DeviceBI
output = shell.Expect(":"); output = shell.Expect(":");
EnrolmentLog.LogSessionProgress(sessionId, 27, "Connected, Elevating Credentials"); EnrolmentLog.LogSessionProgress(sessionId, 27, "Connected, Elevating Credentials");
EnrolmentLog.LogSessionDiagnosticInformation(sessionId, output); EnrolmentLog.LogSessionDiagnosticInformation(sessionId, output);
shell.WriteLine(dbContext.DiscoConfiguration.Bootstrapper.MacSshPassword); shell.WriteLine(Database.DiscoConfiguration.Bootstrapper.MacSshPassword);
System.Threading.Thread.Sleep(250); System.Threading.Thread.Sleep(250);
output = shell.Expect(SshPromptRegEx); output = shell.Expect(SshPromptRegEx);
sessionElevated = true; sessionElevated = true;
@@ -96,7 +98,7 @@ namespace Disco.BI.DeviceBI
shell.Close(); shell.Close();
} }
EnrolmentLog.LogSessionProgress(sessionId, 100, "Disconnected, Starting Disco Enrolment"); EnrolmentLog.LogSessionProgress(sessionId, 100, "Disconnected, Starting Disco Enrolment");
MacSecureEnrolResponse response = MacSecureEnrolResponse.FromMacEnrolResponse(MacEnrol(dbContext, trustedRequest, true, sessionId)); MacSecureEnrolResponse response = MacSecureEnrolResponse.FromMacEnrolResponse(MacEnrol(Database, trustedRequest, true, sessionId));
EnrolmentLog.LogSessionFinished(sessionId); EnrolmentLog.LogSessionFinished(sessionId);
MacSecureEnrol = response; MacSecureEnrol = response;
} }
@@ -211,7 +213,7 @@ namespace Disco.BI.DeviceBI
#endregion #endregion
public static MacEnrolResponse MacEnrol(DiscoDataContext dbContext, MacEnrol Request, bool Trusted, string OpenSessionId = null) public static MacEnrolResponse MacEnrol(DiscoDataContext Database, MacEnrol Request, bool Trusted, string OpenSessionId = null)
{ {
string sessionId; string sessionId;
if (OpenSessionId == null) if (OpenSessionId == null)
@@ -228,7 +230,7 @@ namespace Disco.BI.DeviceBI
try try
{ {
EnrolmentLog.LogSessionProgress(sessionId, 10, "Querying Database"); EnrolmentLog.LogSessionProgress(sessionId, 10, "Querying Database");
Device RepoDevice = dbContext.Devices.Include("AssignedUser").Include("DeviceProfile").Include("DeviceProfile").Where(d => d.SerialNumber == Request.DeviceSerialNumber).FirstOrDefault(); Device RepoDevice = Database.Devices.Include("AssignedUser").Include("DeviceProfile").Include("DeviceProfile").Where(d => d.SerialNumber == Request.DeviceSerialNumber).FirstOrDefault();
if (!Trusted) if (!Trusted)
{ {
if (RepoDevice == null) if (RepoDevice == null)
@@ -240,9 +242,9 @@ namespace Disco.BI.DeviceBI
{ {
EnrolmentLog.LogSessionProgress(sessionId, 50, "New Device, Building Disco Instance"); EnrolmentLog.LogSessionProgress(sessionId, 50, "New Device, Building Disco Instance");
EnrolmentLog.LogSessionTaskAddedDevice(sessionId, Request.DeviceSerialNumber); EnrolmentLog.LogSessionTaskAddedDevice(sessionId, Request.DeviceSerialNumber);
DeviceProfile deviceProfile = dbContext.DeviceProfiles.Find(dbContext.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId); DeviceProfile deviceProfile = Database.DeviceProfiles.Find(Database.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId);
var deviceModelResult = dbContext.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim()); var deviceModelResult = Database.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim());
DeviceModel deviceModel = deviceModelResult.Item1; DeviceModel deviceModel = deviceModelResult.Item1;
if (deviceModelResult.Item2) if (deviceModelResult.Item2)
EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, deviceModelResult.Item1.Manufacturer, deviceModelResult.Item1.Model); EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, deviceModelResult.Item1.Manufacturer, deviceModelResult.Item1.Model);
@@ -259,7 +261,7 @@ namespace Disco.BI.DeviceBI
CreatedDate = DateTime.Now, CreatedDate = DateTime.Now,
EnrolledDate = DateTime.Now EnrolledDate = DateTime.Now
}; };
dbContext.Devices.Add(RepoDevice); Database.Devices.Add(RepoDevice);
} }
else else
{ {
@@ -267,7 +269,7 @@ namespace Disco.BI.DeviceBI
EnrolmentLog.LogSessionTaskUpdatingDevice(sessionId, Request.DeviceSerialNumber); EnrolmentLog.LogSessionTaskUpdatingDevice(sessionId, Request.DeviceSerialNumber);
if (!RepoDevice.DeviceModelId.HasValue || RepoDevice.DeviceModelId.Value == 1) if (!RepoDevice.DeviceModelId.HasValue || RepoDevice.DeviceModelId.Value == 1)
{ {
var deviceModelResult = dbContext.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim()); var deviceModelResult = Database.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim());
DeviceModel deviceModel = deviceModelResult.Item1; DeviceModel deviceModel = deviceModelResult.Item1;
if (deviceModelResult.Item2) if (deviceModelResult.Item2)
EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, deviceModelResult.Item1.Manufacturer, deviceModelResult.Item1.Model); EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, deviceModelResult.Item1.Manufacturer, deviceModelResult.Item1.Model);
@@ -295,11 +297,11 @@ namespace Disco.BI.DeviceBI
if (RepoDevice.DeviceProfile.DistributionType == DeviceProfile.DistributionTypes.OneToOne && RepoDevice.AssignedUser != null) if (RepoDevice.DeviceProfile.DistributionType == DeviceProfile.DistributionTypes.OneToOne && RepoDevice.AssignedUser != null)
{ {
ActiveDirectoryUserAccount AssignedUserInfo = ActiveDirectory.GetUserAccount(RepoDevice.AssignedUser.Id); ActiveDirectoryUserAccount AssignedUserInfo = ActiveDirectory.GetUserAccount(RepoDevice.AssignedUser.Id);
EnrolmentLog.LogSessionTaskAssigningUser(sessionId, RepoDevice.SerialNumber, AssignedUserInfo.DisplayName, AssignedUserInfo.sAMAccountName, AssignedUserInfo.Domain, AssignedUserInfo.ObjectSid); EnrolmentLog.LogSessionTaskAssigningUser(sessionId, RepoDevice.SerialNumber, AssignedUserInfo.DisplayName, AssignedUserInfo.SamAccountName, AssignedUserInfo.Domain, AssignedUserInfo.SecurityIdentifier);
response.DeviceAssignedUserUsername = AssignedUserInfo.sAMAccountName; response.DeviceAssignedUserUsername = AssignedUserInfo.SamAccountName;
response.DeviceAssignedUserDomain = AssignedUserInfo.Domain; response.DeviceAssignedUserDomain = AssignedUserInfo.Domain;
response.DeviceAssignedUserName = AssignedUserInfo.DisplayName; response.DeviceAssignedUserName = AssignedUserInfo.DisplayName;
response.DeviceAssignedUserSID = AssignedUserInfo.ObjectSid; response.DeviceAssignedUserSID = AssignedUserInfo.SecurityIdentifier;
} }
response.DeviceComputerName = RepoDevice.ComputerName; response.DeviceComputerName = RepoDevice.ComputerName;
EnrolmentLog.LogSessionProgress(sessionId, 100, "Completed Successfully"); EnrolmentLog.LogSessionProgress(sessionId, 100, "Completed Successfully");
@@ -321,11 +323,11 @@ namespace Disco.BI.DeviceBI
} }
return response; return response;
} }
public static EnrolResponse Enrol(DiscoDataContext dbContext, string Username, Models.ClientServices.Enrol Request) public static EnrolResponse Enrol(DiscoDataContext Database, string Username, Models.ClientServices.Enrol Request)
{ {
ActiveDirectoryMachineAccount MachineInfo = null; ActiveDirectoryMachineAccount MachineInfo = null;
EnrolResponse response = new EnrolResponse(); EnrolResponse response = new EnrolResponse();
User authenticatedUser = null; AuthorizationToken authenticatedToken = null;
bool isAuthenticated = false; bool isAuthenticated = false;
string sessionId = System.Guid.NewGuid().ToString("B"); string sessionId = System.Guid.NewGuid().ToString("B");
response.SessionId = sessionId; response.SessionId = sessionId;
@@ -336,21 +338,21 @@ namespace Disco.BI.DeviceBI
EnrolmentLog.LogSessionProgress(sessionId, 10, "Loading User Data"); EnrolmentLog.LogSessionProgress(sessionId, 10, "Loading User Data");
if (!string.IsNullOrWhiteSpace(Username)) if (!string.IsNullOrWhiteSpace(Username))
{ {
authenticatedUser = UserBI.UserCache.GetUser(Username, dbContext); authenticatedToken = UserService.GetAuthorization(Username, Database);
isAuthenticated = (authenticatedUser != null); isAuthenticated = (authenticatedToken != null);
} }
EnrolmentLog.LogSessionProgress(sessionId, 13, "Loading Device Data"); EnrolmentLog.LogSessionProgress(sessionId, 13, "Loading Device Data");
Device RepoDevice = dbContext.Devices.Include("AssignedUser").Include("DeviceModel").Include("DeviceProfile").Where(d => d.SerialNumber == Request.DeviceSerialNumber).FirstOrDefault(); Device RepoDevice = Database.Devices.Include("AssignedUser").Include("DeviceModel").Include("DeviceProfile").Where(d => d.SerialNumber == Request.DeviceSerialNumber).FirstOrDefault();
EnrolmentLog.LogSessionProgress(sessionId, 15, "Discovering User/Device Disco Permissions"); EnrolmentLog.LogSessionProgress(sessionId, 15, "Discovering User/Device Disco Permissions");
if (isAuthenticated) if (isAuthenticated)
{ {
if (authenticatedUser.Type != "Admin") if (!authenticatedToken.Has(Claims.Device.Actions.EnrolDevices))
{ {
if (authenticatedUser.Type != "Computer") if (authenticatedToken.Has(Claims.ComputerAccount))
throw new EnrolSafeException(string.Format("Connection not correctly authenticated (SN: {0}; Auth User: {1}; User Type: {2})", Request.DeviceSerialNumber, authenticatedUser.Id, authenticatedUser.Type)); throw new EnrolSafeException(string.Format("Connection not correctly authenticated (SN: {0}; Auth User: {1})", Request.DeviceSerialNumber, authenticatedToken.User.Id));
if (!authenticatedUser.Id.Equals(string.Format("{0}$", Request.DeviceComputerName), System.StringComparison.InvariantCultureIgnoreCase)) 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}; User Type: {2})", Request.DeviceSerialNumber, authenticatedUser.Id, authenticatedUser.Type)); throw new EnrolSafeException(string.Format("Connection not correctly authenticated (SN: {0}; Auth User: {1})", Request.DeviceSerialNumber, authenticatedToken.User.Id));
} }
} }
else else
@@ -375,10 +377,10 @@ namespace Disco.BI.DeviceBI
{ {
EnrolmentLog.LogSessionProgress(sessionId, 30, "New Device, Creating Disco Instance"); EnrolmentLog.LogSessionProgress(sessionId, 30, "New Device, Creating Disco Instance");
EnrolmentLog.LogSessionTaskAddedDevice(sessionId, Request.DeviceSerialNumber); EnrolmentLog.LogSessionTaskAddedDevice(sessionId, Request.DeviceSerialNumber);
DeviceProfile deviceProfile = dbContext.DeviceProfiles.Find(dbContext.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId); DeviceProfile deviceProfile = Database.DeviceProfiles.Find(Database.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId);
var deviceModelResult = dbContext.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim()); var deviceModelResult = Database.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim());
DeviceModel deviceModel = deviceModelResult.Item1; DeviceModel deviceModel = deviceModelResult.Item1;
if (deviceModelResult.Item2) if (deviceModelResult.Item2)
EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, deviceModelResult.Item1.Manufacturer, deviceModelResult.Item1.Model); EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, deviceModelResult.Item1.Manufacturer, deviceModelResult.Item1.Model);
@@ -396,14 +398,14 @@ namespace Disco.BI.DeviceBI
EnrolledDate = DateTime.Now, EnrolledDate = DateTime.Now,
LastEnrolDate = DateTime.Now LastEnrolDate = DateTime.Now
}; };
dbContext.Devices.Add(RepoDevice); Database.Devices.Add(RepoDevice);
} }
else else
{ {
EnrolmentLog.LogSessionProgress(sessionId, 30, "Existing Device, Updating Disco Instance"); EnrolmentLog.LogSessionProgress(sessionId, 30, "Existing Device, Updating Disco Instance");
EnrolmentLog.LogSessionTaskUpdatingDevice(sessionId, Request.DeviceSerialNumber); EnrolmentLog.LogSessionTaskUpdatingDevice(sessionId, Request.DeviceSerialNumber);
var deviceModelResult = dbContext.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim()); var deviceModelResult = Database.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim());
DeviceModel deviceModel = deviceModelResult.Item1; DeviceModel deviceModel = deviceModelResult.Item1;
if (deviceModelResult.Item2) if (deviceModelResult.Item2)
EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, deviceModelResult.Item1.Manufacturer, deviceModelResult.Item1.Model); EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, deviceModelResult.Item1.Manufacturer, deviceModelResult.Item1.Model);
@@ -425,7 +427,7 @@ namespace Disco.BI.DeviceBI
{ {
EnrolmentLog.LogSessionProgress(sessionId, 50, "Provisioning an Active Directory Computer Account"); EnrolmentLog.LogSessionProgress(sessionId, 50, "Provisioning an Active Directory Computer Account");
if (string.IsNullOrEmpty(RepoDevice.ComputerName) || RepoDevice.DeviceProfile.EnforceComputerNameConvention) if (string.IsNullOrEmpty(RepoDevice.ComputerName) || RepoDevice.DeviceProfile.EnforceComputerNameConvention)
RepoDevice.ComputerName = RepoDevice.ComputerNameRender(dbContext); RepoDevice.ComputerName = RepoDevice.ComputerNameRender(Database);
EnrolmentLog.LogSessionTaskProvisioningADAccount(sessionId, RepoDevice.SerialNumber, RepoDevice.ComputerName); EnrolmentLog.LogSessionTaskProvisioningADAccount(sessionId, RepoDevice.SerialNumber, RepoDevice.ComputerName);
MachineInfo = ActiveDirectory.GetMachineAccount(RepoDevice.ComputerName); MachineInfo = ActiveDirectory.GetMachineAccount(RepoDevice.ComputerName);
response.OfflineDomainJoin = ActiveDirectory.OfflineDomainJoinProvision(ref MachineInfo, RepoDevice.ComputerName, RepoDevice.DeviceProfile.OrganisationalUnit, sessionId); response.OfflineDomainJoin = ActiveDirectory.OfflineDomainJoinProvision(ref MachineInfo, RepoDevice.ComputerName, RepoDevice.DeviceProfile.OrganisationalUnit, sessionId);
@@ -458,7 +460,7 @@ namespace Disco.BI.DeviceBI
// Enforce Computer Name Convention // Enforce Computer Name Convention
if (RepoDevice.DeviceProfile.EnforceComputerNameConvention) if (RepoDevice.DeviceProfile.EnforceComputerNameConvention)
{ {
var calculatedComputerName = RepoDevice.ComputerNameRender(dbContext); var calculatedComputerName = RepoDevice.ComputerNameRender(Database);
if (!Request.DeviceComputerName.Equals(calculatedComputerName, StringComparison.InvariantCultureIgnoreCase)) if (!Request.DeviceComputerName.Equals(calculatedComputerName, StringComparison.InvariantCultureIgnoreCase))
{ {
EnrolmentLog.LogSessionProgress(sessionId, 50, string.Format("Renaming Device: {0} -> {1}", Request.DeviceComputerName, calculatedComputerName)); EnrolmentLog.LogSessionProgress(sessionId, 50, string.Format("Renaming Device: {0} -> {1}", Request.DeviceComputerName, calculatedComputerName));
@@ -476,15 +478,18 @@ namespace Disco.BI.DeviceBI
// Enforce Organisation Unit // Enforce Organisation Unit
if (response.OfflineDomainJoin == null && RepoDevice.DeviceProfile.EnforceOrganisationalUnit) if (response.OfflineDomainJoin == null && RepoDevice.DeviceProfile.EnforceOrganisationalUnit)
{ {
if ((RepoDevice.DeviceProfile.OrganisationalUnit == null && MachineInfo.ParentDistinguishedName.Equals("CN=Computers", StringComparison.InvariantCultureIgnoreCase)) // Null (Default) OU var parentDistinguishedName = MachineInfo.ParentDistinguishedName();
|| !MachineInfo.ParentDistinguishedName.Equals(RepoDevice.DeviceProfile.OrganisationalUnit, StringComparison.InvariantCultureIgnoreCase)) // Custom OU
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
{ {
string newOU = RepoDevice.DeviceProfile.OrganisationalUnit ?? "CN=Computers"; string newOU = RepoDevice.DeviceProfile.OrganisationalUnit ?? "CN=Computers";
EnrolmentLog.LogSessionProgress(sessionId, 65, string.Format("Moving Device Organisation Unit: {0} -> {1}", MachineInfo.ParentDistinguishedName, newOU)); EnrolmentLog.LogSessionProgress(sessionId, 65, string.Format("Moving Device Organisation Unit: {0} -> {1}", parentDistinguishedName, newOU));
EnrolmentLog.LogSessionTaskMovingDeviceOrganisationUnit(sessionId, MachineInfo.ParentDistinguishedName, newOU); EnrolmentLog.LogSessionTaskMovingDeviceOrganisationUnit(sessionId, parentDistinguishedName, newOU);
MachineInfo.MoveOrganisationUnit(RepoDevice.DeviceProfile.OrganisationalUnit); MachineInfo.MoveOrganisationUnit(RepoDevice.DeviceProfile.OrganisationalUnit);
MachineInfo = ActiveDirectory.GetMachineAccount(MachineInfo.sAMAccountName); MachineInfo = ActiveDirectory.GetMachineAccount(MachineInfo.SamAccountName);
response.RequireReboot = true; response.RequireReboot = true;
} }
} }
@@ -507,12 +512,12 @@ namespace Disco.BI.DeviceBI
{ {
EnrolmentLog.LogSessionProgress(sessionId, 80, "Retrieving Active Directory Assigned User Account"); EnrolmentLog.LogSessionProgress(sessionId, 80, "Retrieving Active Directory Assigned User Account");
ActiveDirectoryUserAccount AssignedUserInfo = ActiveDirectory.GetUserAccount(RepoDevice.AssignedUser.Id); ActiveDirectoryUserAccount AssignedUserInfo = ActiveDirectory.GetUserAccount(RepoDevice.AssignedUser.Id);
EnrolmentLog.LogSessionTaskAssigningUser(sessionId, RepoDevice.SerialNumber, AssignedUserInfo.DisplayName, AssignedUserInfo.sAMAccountName, AssignedUserInfo.Domain, AssignedUserInfo.ObjectSid); EnrolmentLog.LogSessionTaskAssigningUser(sessionId, RepoDevice.SerialNumber, AssignedUserInfo.DisplayName, AssignedUserInfo.SamAccountName, AssignedUserInfo.Domain, AssignedUserInfo.SecurityIdentifier);
response.AllowBootstrapperUninstall = true; response.AllowBootstrapperUninstall = true;
response.DeviceAssignedUserUsername = AssignedUserInfo.sAMAccountName; response.DeviceAssignedUserUsername = AssignedUserInfo.SamAccountName;
response.DeviceAssignedUserDomain = AssignedUserInfo.Domain; response.DeviceAssignedUserDomain = AssignedUserInfo.Domain;
response.DeviceAssignedUserName = AssignedUserInfo.DisplayName; response.DeviceAssignedUserName = AssignedUserInfo.DisplayName;
response.DeviceAssignedUserSID = AssignedUserInfo.ObjectSid; response.DeviceAssignedUserSID = AssignedUserInfo.SecurityIdentifier;
} }
} }
else else
@@ -523,7 +528,7 @@ namespace Disco.BI.DeviceBI
{ {
EnrolmentLog.LogSessionProgress(sessionId, 90, "Provisioning a Wireless Certificate"); EnrolmentLog.LogSessionProgress(sessionId, 90, "Provisioning a Wireless Certificate");
var allocationResult = RepoDevice.AllocateCertificate(dbContext); var allocationResult = RepoDevice.AllocateCertificate(Database);
var deviceCertificate = allocationResult.Item1; var deviceCertificate = allocationResult.Item1;
if (deviceCertificate != null) if (deviceCertificate != null)
{ {
+13 -12
View File
@@ -2,6 +2,7 @@
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Models.BI.Device; using Disco.Models.BI.Device;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Services.Users;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
@@ -24,13 +25,13 @@ namespace Disco.BI.DeviceBI.Importing
return (ImportDeviceSession)HttpRuntime.Cache.Get(parseKey); return (ImportDeviceSession)HttpRuntime.Cache.Get(parseKey);
} }
internal static bool ImportRecord(this ImportDevice device, DiscoDataContext dbContext, PopulateRecordReferences references) internal static bool ImportRecord(this ImportDevice device, DiscoDataContext Database, PopulateRecordReferences references)
{ {
// Skips If Errors // Skips If Errors
if (device.Errors == null || device.Errors.Count == 0) if (device.Errors == null || device.Errors.Count == 0)
{ {
// Re-Populate & Skip If Errors // Re-Populate & Skip If Errors
device.PopulateRecord(dbContext, references); device.PopulateRecord(Database, references);
if (device.Errors == null || device.Errors.Count == 0) if (device.Errors == null || device.Errors.Count == 0)
{ {
Device discoDevice = device.Device; Device discoDevice = device.Device;
@@ -44,7 +45,7 @@ namespace Disco.BI.DeviceBI.Importing
CreatedDate = DateTime.Now, CreatedDate = DateTime.Now,
AllowUnauthenticatedEnrol = true, AllowUnauthenticatedEnrol = true,
}; };
dbContext.Devices.Add(discoDevice); Database.Devices.Add(discoDevice);
} }
if (discoDevice.DeviceModelId != device.DeviceModelId) if (discoDevice.DeviceModelId != device.DeviceModelId)
@@ -60,10 +61,10 @@ namespace Disco.BI.DeviceBI.Importing
if (discoDevice.AssignedUserId != device.AssignedUserId) if (discoDevice.AssignedUserId != device.AssignedUserId)
{ {
discoDevice.AssignDevice(dbContext, device.AssignedUser); discoDevice.AssignDevice(Database, device.AssignedUser);
} }
dbContext.SaveChanges(); Database.SaveChanges();
return true; return true;
} }
@@ -71,16 +72,16 @@ namespace Disco.BI.DeviceBI.Importing
return false; return false;
} }
internal static PopulateRecordReferences GetPopulateRecordReferences(DiscoDataContext dbContext) internal static PopulateRecordReferences GetPopulateRecordReferences(DiscoDataContext Database)
{ {
return new PopulateRecordReferences( return new PopulateRecordReferences(
dbContext.DeviceModels.ToDictionary(dm => dm.Id), Database.DeviceModels.ToDictionary(dm => dm.Id),
dbContext.DeviceProfiles.ToDictionary(dp => dp.Id), Database.DeviceProfiles.ToDictionary(dp => dp.Id),
dbContext.DeviceBatches.ToDictionary(db => db.Id) Database.DeviceBatches.ToDictionary(db => db.Id)
); );
} }
internal static void PopulateRecord(this ImportDevice device, DiscoDataContext dbContext, PopulateRecordReferences references) internal static void PopulateRecord(this ImportDevice device, DiscoDataContext Database, PopulateRecordReferences references)
{ {
var deviceModels = references.Item1; var deviceModels = references.Item1;
@@ -90,7 +91,7 @@ namespace Disco.BI.DeviceBI.Importing
// SERIAL NUMBER - Existing Device // SERIAL NUMBER - Existing Device
if (!device.Errors.ContainsKey("SerialNumber")) if (!device.Errors.ContainsKey("SerialNumber"))
{ {
device.Device = dbContext.Devices.Find(device.SerialNumber); device.Device = Database.Devices.Find(device.SerialNumber);
if (device.Device != null && device.Device.DecommissionedDate.HasValue) if (device.Device != null && device.Device.DecommissionedDate.HasValue)
device.Errors.Add("SerialNumber", "The device is decommissioned"); device.Errors.Add("SerialNumber", "The device is decommissioned");
} }
@@ -135,7 +136,7 @@ namespace Disco.BI.DeviceBI.Importing
{ {
try try
{ {
device.AssignedUser = UserBI.UserCache.GetUser(device.AssignedUserId, dbContext, true); device.AssignedUser = UserService.GetUser(device.AssignedUserId, Database, true);
} }
catch (ArgumentException) catch (ArgumentException)
{ {
@@ -45,14 +45,14 @@ namespace Disco.BI.DeviceBI.Importing
this.Status.UpdateStatus(20, "Parsing CSV File", string.Format("Linking {0} Records", records.Count)); this.Status.UpdateStatus(20, "Parsing CSV File", string.Format("Linking {0} Records", records.Count));
using (DiscoDataContext dbContext = new DiscoDataContext()) using (DiscoDataContext database = new DiscoDataContext())
{ {
var populateReferences = Import.GetPopulateRecordReferences(dbContext); var populateReferences = Import.GetPopulateRecordReferences(database);
DateTime lastUpdate = DateTime.Now; DateTime lastUpdate = DateTime.Now;
foreach (var record in records) foreach (var record in records)
{ {
record.PopulateRecord(dbContext, populateReferences); record.PopulateRecord(database, populateReferences);
if (DateTime.Now.Subtract(lastUpdate).TotalSeconds > 1) if (DateTime.Now.Subtract(lastUpdate).TotalSeconds > 1)
{ {
@@ -35,14 +35,14 @@ namespace Disco.BI.DeviceBI.Importing
this.Status.UpdateStatus(0, "Processing Device Import", "Importing Devices"); this.Status.UpdateStatus(0, "Processing Device Import", "Importing Devices");
using (DiscoDataContext dbContext = new DiscoDataContext()) using (DiscoDataContext database = new DiscoDataContext())
{ {
var populateReferences = Import.GetPopulateRecordReferences(dbContext); var populateReferences = Import.GetPopulateRecordReferences(database);
DateTime lastUpdate = DateTime.Now; DateTime lastUpdate = DateTime.Now;
foreach (var record in records) foreach (var record in records)
{ {
if (record.ImportRecord(dbContext, populateReferences)) if (record.ImportRecord(database, populateReferences))
recordsImported++; recordsImported++;
if (DateTime.Now.Subtract(lastUpdate).TotalSeconds > 1) if (DateTime.Now.Subtract(lastUpdate).TotalSeconds > 1)
@@ -19,26 +19,26 @@ namespace Disco.BI.DeviceBI.Migration
public override bool CancelInitiallySupported { get { return false; } } public override bool CancelInitiallySupported { get { return false; } }
#region Required Helpers #region Required Helpers
private static string RequiredFilePath(DiscoDataContext dbContext) private static string RequiredFilePath(DiscoDataContext Database)
{ {
if (dbContext.DiscoConfiguration.DataStoreLocation != null) if (Database.DiscoConfiguration.DataStoreLocation != null)
return System.IO.Path.Combine(dbContext.DiscoConfiguration.DataStoreLocation, "_LogMacAddressImportingRequired.txt"); return System.IO.Path.Combine(Database.DiscoConfiguration.DataStoreLocation, "_LogMacAddressImportingRequired.txt");
else else
return null; return null;
} }
public static bool IsRequired(DiscoDataContext dbContext) public static bool IsRequired(DiscoDataContext Database)
{ {
var requiredFilePath = RequiredFilePath(dbContext); var requiredFilePath = RequiredFilePath(Database);
if (requiredFilePath == null) if (requiredFilePath == null)
return false; return false;
else else
return System.IO.File.Exists(requiredFilePath); return System.IO.File.Exists(requiredFilePath);
} }
public static void SetRequired(DiscoDataContext dbContext) public static void SetRequired(DiscoDataContext Database)
{ {
var requiredFilePath = RequiredFilePath(dbContext); var requiredFilePath = RequiredFilePath(Database);
if (requiredFilePath != null) if (requiredFilePath != null)
{ {
@@ -49,9 +49,9 @@ namespace Disco.BI.DeviceBI.Migration
} }
#endregion #endregion
public override void InitalizeScheduledTask(DiscoDataContext dbContext) public override void InitalizeScheduledTask(DiscoDataContext Database)
{ {
if (IsRequired(dbContext)) if (IsRequired(Database))
{ {
// Schedule in 15mins // Schedule in 15mins
var trigger = TriggerBuilder.Create() var trigger = TriggerBuilder.Create()
@@ -73,7 +73,7 @@ namespace Disco.BI.DeviceBI.Migration
protected override void ExecuteTask() protected override void ExecuteTask()
{ {
using (DiscoDataContext dbContext = new DiscoDataContext()) using (DiscoDataContext database = new DiscoDataContext())
{ {
Status.UpdateStatus(0, "Importing MAC Addresses", "Querying Logs for Details"); Status.UpdateStatus(0, "Importing MAC Addresses", "Querying Logs for Details");
// Load Logs // Load Logs
@@ -82,7 +82,7 @@ namespace Disco.BI.DeviceBI.Migration
Module = DeviceBI.EnrolmentLog.Current.ModuleId, Module = DeviceBI.EnrolmentLog.Current.ModuleId,
EventTypes = new List<int>() { (int)DeviceBI.EnrolmentLog.EventTypeIds.SessionDeviceInfo } EventTypes = new List<int>() { (int)DeviceBI.EnrolmentLog.EventTypeIds.SessionDeviceInfo }
}; };
var results = logRetriever.Query(dbContext); var results = logRetriever.Query(database);
Status.UpdateStatus(50, string.Format("Passing {0} logs", results.Count)); Status.UpdateStatus(50, string.Format("Passing {0} logs", results.Count));
@@ -93,7 +93,7 @@ namespace Disco.BI.DeviceBI.Migration
Status.UpdateStatus(75, string.Format("Importing {0} details", addresses.Count)); Status.UpdateStatus(75, string.Format("Importing {0} details", addresses.Count));
var devices = dbContext.Devices.Include("DeviceDetails").ToList(); var devices = database.Devices.Include("DeviceDetails").ToList();
Tuple<string, string> addressResult; Tuple<string, string> addressResult;
foreach (var device in devices) foreach (var device in devices)
@@ -109,10 +109,10 @@ namespace Disco.BI.DeviceBI.Migration
Status.UpdateStatus(90, "Saving to Database"); Status.UpdateStatus(90, "Saving to Database");
dbContext.SaveChanges(); database.SaveChanges();
// Finished - Remove Placeholder File // Finished - Remove Placeholder File
var requiredFilePath = RequiredFilePath(dbContext); var requiredFilePath = RequiredFilePath(database);
if (System.IO.File.Exists(requiredFilePath)) if (System.IO.File.Exists(requiredFilePath))
System.IO.File.Delete(requiredFilePath); System.IO.File.Delete(requiredFilePath);
} }
+9 -9
View File
@@ -29,7 +29,7 @@ namespace Disco.BI.DeviceBI
}).ToList(); }).ToList();
} }
public static List<DeviceSearchResultItem> Search(DiscoDataContext dbContext, string Term, int? LimitCount = null, bool SearchDetails = false) public static List<DeviceSearchResultItem> Search(DiscoDataContext Database, string Term, int? LimitCount = null, bool SearchDetails = false)
{ {
IQueryable<Device> query; IQueryable<Device> query;
@@ -37,7 +37,7 @@ namespace Disco.BI.DeviceBI
if (SearchDetails) if (SearchDetails)
{ {
query = dbContext.Devices.Where(d => query = Database.Devices.Where(d =>
d.AssetNumber.Contains(Term) || d.AssetNumber.Contains(Term) ||
d.ComputerName.Contains(Term) || d.ComputerName.Contains(Term) ||
d.SerialNumber.Contains(Term) || d.SerialNumber.Contains(Term) ||
@@ -48,7 +48,7 @@ namespace Disco.BI.DeviceBI
} }
else else
{ {
query = dbContext.Devices.Where(d => query = Database.Devices.Where(d =>
d.AssetNumber.Contains(Term) || d.AssetNumber.Contains(Term) ||
d.ComputerName.Contains(Term) || d.ComputerName.Contains(Term) ||
d.SerialNumber.Contains(Term) || d.SerialNumber.Contains(Term) ||
@@ -59,17 +59,17 @@ namespace Disco.BI.DeviceBI
return Search_SelectDeviceSearchResultItem(query, LimitCount); return Search_SelectDeviceSearchResultItem(query, LimitCount);
} }
public static List<DeviceSearchResultItem> SearchDeviceModel(DiscoDataContext dbContext, int DeviceModelId, int? LimitCount = null) public static List<DeviceSearchResultItem> SearchDeviceModel(DiscoDataContext Database, int DeviceModelId, int? LimitCount = null)
{ {
return Search_SelectDeviceSearchResultItem(dbContext.Devices.Where(d => d.DeviceModelId == DeviceModelId), LimitCount); return Search_SelectDeviceSearchResultItem(Database.Devices.Where(d => d.DeviceModelId == DeviceModelId), LimitCount);
} }
public static List<DeviceSearchResultItem> SearchDeviceProfile(DiscoDataContext dbContext, int DeviceProfileId, int? LimitCount = null) public static List<DeviceSearchResultItem> SearchDeviceProfile(DiscoDataContext Database, int DeviceProfileId, int? LimitCount = null)
{ {
return Search_SelectDeviceSearchResultItem(dbContext.Devices.Where(d => d.DeviceProfileId == DeviceProfileId), LimitCount); return Search_SelectDeviceSearchResultItem(Database.Devices.Where(d => d.DeviceProfileId == DeviceProfileId), LimitCount);
} }
public static List<DeviceSearchResultItem> SearchDeviceBatch(DiscoDataContext dbContext, int DeviceBatchId, int? LimitCount = null) public static List<DeviceSearchResultItem> SearchDeviceBatch(DiscoDataContext Database, int DeviceBatchId, int? LimitCount = null)
{ {
return Search_SelectDeviceSearchResultItem(dbContext.Devices.Where(d => d.DeviceBatchId == DeviceBatchId), LimitCount); return Search_SelectDeviceSearchResultItem(Database.Devices.Where(d => d.DeviceBatchId == DeviceBatchId), LimitCount);
} }
} }
@@ -16,7 +16,7 @@ namespace Disco.BI.DocumentTemplateBI
{ {
private static ConcurrentDictionary<string, List<RectangleF>> _Cache = new ConcurrentDictionary<string, List<RectangleF>>(); private static ConcurrentDictionary<string, List<RectangleF>> _Cache = new ConcurrentDictionary<string, List<RectangleF>>();
public static List<RectangleF> GetLocations(DocumentTemplate dt, DiscoDataContext dbContext) public static List<RectangleF> GetLocations(DocumentTemplate dt, DiscoDataContext Database)
{ {
// Check Cache // Check Cache
List<RectangleF> locations; List<RectangleF> locations;
@@ -25,7 +25,7 @@ namespace Disco.BI.DocumentTemplateBI
return locations; return locations;
} }
// Generate Cache // Generate Cache
return GenerateLocations(dt, dbContext); return GenerateLocations(dt, Database);
} }
public static bool InvalidateLocations(DocumentTemplate dt) public static bool InvalidateLocations(DocumentTemplate dt)
@@ -47,9 +47,9 @@ namespace Disco.BI.DocumentTemplateBI
return _Cache.TryAdd(DocumentTemplateId, Locations); return _Cache.TryAdd(DocumentTemplateId, Locations);
} }
internal static List<RectangleF> GenerateLocations(DocumentTemplate dt, DiscoDataContext dbContext) internal static List<RectangleF> GenerateLocations(DocumentTemplate dt, DiscoDataContext Database)
{ {
string templateFilename = dt.RepositoryFilename(dbContext); string templateFilename = dt.RepositoryFilename(Database);
PdfReader pdfReader = new PdfReader(templateFilename); PdfReader pdfReader = new PdfReader(templateFilename);
List<RectangleF> locations = new List<RectangleF>(); List<RectangleF> locations = new List<RectangleF>();
@@ -115,7 +115,7 @@ namespace Disco.BI.DocumentTemplateBI
} }
throw new System.ArgumentException(string.Format("Invalid Document Unique Identifier Version ({0})", s[1]), "UniqueIdentifier"); throw new System.ArgumentException(string.Format("Invalid Document Unique Identifier Version ({0})", s[1]), "UniqueIdentifier");
} }
public bool LoadComponents(DiscoDataContext Context) public bool LoadComponents(DiscoDataContext Database)
{ {
bool LoadComponents; bool LoadComponents;
if (!this._loadedComponentsOk.HasValue) if (!this._loadedComponentsOk.HasValue)
@@ -142,7 +142,7 @@ namespace Disco.BI.DocumentTemplateBI
} }
else else
{ {
this._documentTemplate = Context.DocumentTemplates.Find(this.TemplateTypeId); this._documentTemplate = Database.DocumentTemplates.Find(this.TemplateTypeId);
if (this._documentTemplate != null) if (this._documentTemplate != null)
{ {
scopeType = this._documentTemplate.Scope; scopeType = this._documentTemplate.Scope;
@@ -158,7 +158,7 @@ namespace Disco.BI.DocumentTemplateBI
switch (scopeType) switch (scopeType)
{ {
case DocumentTemplate.DocumentTemplateScopes.Device: case DocumentTemplate.DocumentTemplateScopes.Device:
Device d = Context.Devices.Find(this.DataId); Device d = Database.Devices.Find(this.DataId);
if (d != null) if (d != null)
{ {
this._data = d; this._data = d;
@@ -169,7 +169,7 @@ namespace Disco.BI.DocumentTemplateBI
} }
break; break;
case DocumentTemplate.DocumentTemplateScopes.Job: case DocumentTemplate.DocumentTemplateScopes.Job:
Job i = Context.Jobs.Find(int.Parse(this.DataId)); Job i = Database.Jobs.Find(int.Parse(this.DataId));
if (i != null) if (i != null)
{ {
this._data = i; this._data = i;
@@ -180,7 +180,7 @@ namespace Disco.BI.DocumentTemplateBI
} }
break; break;
case DocumentTemplate.DocumentTemplateScopes.User: case DocumentTemplate.DocumentTemplateScopes.User:
User u = Context.Users.Find(this.DataId); User u = Database.Users.Find(this.DataId);
if (u != null) if (u != null)
{ {
this._data = u; this._data = u;
@@ -17,14 +17,14 @@ namespace Disco.BI.DocumentTemplateBI.Importer
public const string WatcherFilter = "*.pdf"; public const string WatcherFilter = "*.pdf";
public string DropBoxLocation { get; private set; } public string DropBoxLocation { get; private set; }
public DocumentDropBoxMonitor(DiscoDataContext Context, ISchedulerFactory SchedulerFactory, Cache HttpCache) public DocumentDropBoxMonitor(DiscoDataContext Database, ISchedulerFactory SchedulerFactory, Cache HttpCache)
{ {
if (Context == null) if (Database == null)
throw new System.ArgumentNullException("Context"); throw new System.ArgumentNullException("Context");
this._httpCache = HttpCache; this._httpCache = HttpCache;
var location = DataStore.CreateLocation(Context, "DocumentDropBox"); var location = DataStore.CreateLocation(Database, "DocumentDropBox");
this.DropBoxLocation = location.EndsWith(@"\") ? location : string.Concat(location, @"\"); this.DropBoxLocation = location.EndsWith(@"\") ? location : string.Concat(location, @"\");
this._scheduler = SchedulerFactory.GetScheduler(); this._scheduler = SchedulerFactory.GetScheduler();
@@ -13,7 +13,7 @@ namespace Disco.BI.DocumentTemplateBI.Importer
public override bool SingleInstanceTask { get { return true; } } public override bool SingleInstanceTask { get { return true; } }
public override bool CancelInitiallySupported { get { return false; } } public override bool CancelInitiallySupported { get { return false; } }
public override void InitalizeScheduledTask(DiscoDataContext dbContext) public override void InitalizeScheduledTask(DiscoDataContext Database)
{ {
// Trigger Daily @ 12:30am // Trigger Daily @ 12:30am
TriggerBuilder triggerBuilder = TriggerBuilder.Create().WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(0, 30)); TriggerBuilder triggerBuilder = TriggerBuilder.Create().WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(0, 30));
@@ -24,9 +24,9 @@ namespace Disco.BI.DocumentTemplateBI.Importer
protected override void ExecuteTask() protected override void ExecuteTask()
{ {
string dataStoreLocation; string dataStoreLocation;
using (DiscoDataContext dbContext = new DiscoDataContext()) using (DiscoDataContext database = new DiscoDataContext())
{ {
dataStoreLocation = DataStore.CreateLocation(dbContext, "Cache\\DocumentDropBox_SessionPages"); dataStoreLocation = DataStore.CreateLocation(database, "Cache\\DocumentDropBox_SessionPages");
} }
int deleteCount = 0; int deleteCount = 0;
@@ -40,12 +40,12 @@ namespace Disco.BI.DocumentTemplateBI.Importer
try try
{ {
using (DiscoDataContext dbContext = new DiscoDataContext()) using (DiscoDataContext database = new DiscoDataContext())
{ {
if (retryCount < 18) if (retryCount < 18)
{ {
context.JobDetail.JobDataMap["RetryCount"] = (++retryCount); context.JobDetail.JobDataMap["RetryCount"] = (++retryCount);
bool processResult = Interop.Pdf.PdfImporter.ProcessPdfAttachment(filename, dbContext, sessionId, httpCache); bool processResult = Interop.Pdf.PdfImporter.ProcessPdfAttachment(filename, database, sessionId, httpCache);
if (processResult) if (processResult)
{ {
@@ -60,7 +60,7 @@ namespace Disco.BI.DocumentTemplateBI.Importer
{ {
try try
{ {
string folderError = DataStore.CreateLocation(dbContext, "DocumentDropBox_Errors"); string folderError = DataStore.CreateLocation(database, "DocumentDropBox_Errors");
string filenameError = Path.Combine(folderError, Path.GetFileName(filename)); string filenameError = Path.Combine(folderError, Path.GetFileName(filename));
int filenameErrorCount = 0; int filenameErrorCount = 0;
while (File.Exists(filenameError)) while (File.Exists(filenameError))
@@ -85,7 +85,7 @@ namespace Disco.BI.DocumentTemplateBI.Importer
{ {
try try
{ {
string folderError = DataStore.CreateLocation(dbContext, "DocumentDropBox_Errors"); string folderError = DataStore.CreateLocation(database, "DocumentDropBox_Errors");
string filenameError = Path.Combine(folderError, Path.GetFileName(filename)); string filenameError = Path.Combine(folderError, Path.GetFileName(filename));
int filenameErrorCount = 0; int filenameErrorCount = 0;
while (File.Exists(filenameError)) while (File.Exists(filenameError))
+2 -2
View File
@@ -167,14 +167,14 @@ namespace Disco.BI.Expressions
return e; return e;
} }
public static IDictionary StandardVariables(DocumentTemplate AttachmentType, DiscoDataContext DataContext, User User, System.DateTime TimeStamp, DocumentState DocumentState) public static IDictionary StandardVariables(DocumentTemplate AttachmentType, DiscoDataContext Database, User User, System.DateTime TimeStamp, DocumentState DocumentState)
{ {
return new Hashtable return new Hashtable
{ {
{ {
"DataContext", "DataContext",
DataContext Database
}, },
{ {
@@ -17,7 +17,7 @@ namespace Disco.BI.Expressions
public override bool SingleInstanceTask { get { return true; } } public override bool SingleInstanceTask { get { return true; } }
public override bool CancelInitiallySupported { get { return false; } } public override bool CancelInitiallySupported { get { return false; } }
public override void InitalizeScheduledTask(DiscoDataContext dbContext) public override void InitalizeScheduledTask(DiscoDataContext Database)
{ {
// Run in Background 1 Second after Scheduled (on App Startup) // Run in Background 1 Second after Scheduled (on App Startup)
TriggerBuilder triggerBuilder = TriggerBuilder.Create().StartAt(new DateTimeOffset(DateTime.Now).AddSeconds(5)); TriggerBuilder triggerBuilder = TriggerBuilder.Create().StartAt(new DateTimeOffset(DateTime.Now).AddSeconds(5));
@@ -28,9 +28,9 @@ namespace Disco.BI.Expressions
protected override void ExecuteTask() protected override void ExecuteTask()
{ {
// Cache Document Template Filter Expressions // Cache Document Template Filter Expressions
using (DiscoDataContext dbContext = new DiscoDataContext()) using (DiscoDataContext database = new DiscoDataContext())
{ {
foreach (var documentTemplate in dbContext.DocumentTemplates.Where(dt => dt.FilterExpression != null && dt.FilterExpression != string.Empty)) foreach (var documentTemplate in database.DocumentTemplates.Where(dt => dt.FilterExpression != null && dt.FilterExpression != string.Empty))
{ {
if (!string.IsNullOrWhiteSpace(documentTemplate.FilterExpression)) if (!string.IsNullOrWhiteSpace(documentTemplate.FilterExpression))
documentTemplate.FilterExpressionFromCache(); documentTemplate.FilterExpressionFromCache();
+10 -10
View File
@@ -26,39 +26,39 @@ namespace Disco.BI.Expressions.Extensions
string AbsoluteFilePath = System.IO.Path.Combine(DataStoreLocation, RelativeFilePath); string AbsoluteFilePath = System.IO.Path.Combine(DataStoreLocation, RelativeFilePath);
return new FileImageExpressionResult(AbsoluteFilePath); return new FileImageExpressionResult(AbsoluteFilePath);
} }
public static FileImageExpressionResult JobAttachmentFirstImage(Job Job, DiscoDataContext dbContext) public static FileImageExpressionResult JobAttachmentFirstImage(Job Job, DiscoDataContext Database)
{ {
var attachment = Job.JobAttachments.FirstOrDefault(ja => ja.MimeType.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase)); var attachment = Job.JobAttachments.FirstOrDefault(ja => ja.MimeType.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase));
if (attachment != null) if (attachment != null)
{ {
var filename = attachment.RepositoryFilename(dbContext); var filename = attachment.RepositoryFilename(Database);
return new FileImageExpressionResult(filename); return new FileImageExpressionResult(filename);
} }
else else
return null; return null;
} }
public static FileImageExpressionResult JobAttachmentLastImage(Job Job, DiscoDataContext dbContext) public static FileImageExpressionResult JobAttachmentLastImage(Job Job, DiscoDataContext Database)
{ {
var attachment = Job.JobAttachments.LastOrDefault(ja => ja.MimeType.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase)); var attachment = Job.JobAttachments.LastOrDefault(ja => ja.MimeType.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase));
if (attachment != null) if (attachment != null)
{ {
var filename = attachment.RepositoryFilename(dbContext); var filename = attachment.RepositoryFilename(Database);
return new FileImageExpressionResult(filename); return new FileImageExpressionResult(filename);
} }
else else
return null; return null;
} }
public static FileImageExpressionResult JobAttachmentImage(JobAttachment JobAttachment, DiscoDataContext dbContext) public static FileImageExpressionResult JobAttachmentImage(JobAttachment JobAttachment, DiscoDataContext Database)
{ {
if (JobAttachment == null) if (JobAttachment == null)
throw new ArgumentNullException("JobAttachment"); throw new ArgumentNullException("JobAttachment");
if (!JobAttachment.MimeType.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase)) if (!JobAttachment.MimeType.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase))
throw new ArgumentException("Invalid Image MimeType for Attachment"); throw new ArgumentException("Invalid Image MimeType for Attachment");
var filename = JobAttachment.RepositoryFilename(dbContext); var filename = JobAttachment.RepositoryFilename(Database);
return new FileImageExpressionResult(filename); return new FileImageExpressionResult(filename);
} }
public static FileMontageImageExpressionResult JobAttachmentImageMontage(Job Job, DiscoDataContext dbContext) public static FileMontageImageExpressionResult JobAttachmentImageMontage(Job Job, DiscoDataContext Database)
{ {
if (Job == null) if (Job == null)
throw new ArgumentNullException("Job"); throw new ArgumentNullException("Job");
@@ -69,14 +69,14 @@ namespace Disco.BI.Expressions.Extensions
if (attachments.Count > 0) if (attachments.Count > 0)
{ {
var attachmentFilepaths = attachments.Select(a => a.RepositoryFilename(dbContext)).ToList(); var attachmentFilepaths = attachments.Select(a => a.RepositoryFilename(Database)).ToList();
return new FileMontageImageExpressionResult(attachmentFilepaths); return new FileMontageImageExpressionResult(attachmentFilepaths);
} }
else else
return null; return null;
} }
public static FileMontageImageExpressionResult JobAttachmentsImageMontage(ArrayList JobAttachments, DiscoDataContext dbContext) public static FileMontageImageExpressionResult JobAttachmentsImageMontage(ArrayList JobAttachments, DiscoDataContext Database)
{ {
if (JobAttachments == null) if (JobAttachments == null)
throw new ArgumentNullException("JobAttachments"); throw new ArgumentNullException("JobAttachments");
@@ -85,7 +85,7 @@ namespace Disco.BI.Expressions.Extensions
if (attachments.Count > 0) if (attachments.Count > 0)
{ {
var attachmentFilepaths = attachments.Select(a => a.RepositoryFilename(dbContext)).ToList(); var attachmentFilepaths = attachments.Select(a => a.RepositoryFilename(Database)).ToList();
return new FileMontageImageExpressionResult(attachmentFilepaths); return new FileMontageImageExpressionResult(attachmentFilepaths);
} }
@@ -4,6 +4,8 @@ using System.Linq;
using System.Text; using System.Text;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Services.Users;
using Disco.Services.Authorization;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
@@ -13,39 +15,60 @@ namespace Disco.BI.Extensions
#region Delete #region Delete
public static bool CanDelete(this DeviceAttachment da) public static bool CanDelete(this DeviceAttachment da)
{ {
return true; // Placeholder - Currently Can Always Delete; if (UserService.CurrentAuthorization.Has(Claims.Device.Actions.RemoveAnyAttachments))
return true;
if (UserService.CurrentAuthorization.Has(Claims.Device.Actions.RemoveOwnAttachments)
&& da.TechUserId == UserService.CurrentUserId)
return true;
return false;
} }
public static void OnDelete(this DeviceAttachment da, DiscoDataContext dbContext) public static void OnDelete(this DeviceAttachment da, DiscoDataContext Database)
{ {
if (!da.CanDelete()) if (!da.CanDelete())
throw new InvalidOperationException("Deletion of Attachment is Denied"); throw new InvalidOperationException("Deletion of Attachment is Denied");
da.RepositoryDelete(dbContext); da.RepositoryDelete(Database);
dbContext.DeviceAttachments.Remove(da); Database.DeviceAttachments.Remove(da);
} }
public static bool CanDelete(this JobAttachment ja) public static bool CanDelete(this JobAttachment ja)
{ {
return true; // Placeholder - Currently Can Always Delete; if (UserService.CurrentAuthorization.Has(Claims.Job.Actions.RemoveAnyAttachments))
return true;
if (UserService.CurrentAuthorization.Has(Claims.Job.Actions.RemoveOwnAttachments)
&& ja.TechUserId == UserService.CurrentUserId)
return true;
return false;
} }
public static void OnDelete(this JobAttachment ja, DiscoDataContext dbContext) public static void OnDelete(this JobAttachment ja, DiscoDataContext Database)
{ {
if (!ja.CanDelete()) if (!ja.CanDelete())
throw new InvalidOperationException("Deletion of Attachment is Denied"); throw new InvalidOperationException("Deletion of Attachment is Denied");
ja.RepositoryDelete(dbContext); ja.RepositoryDelete(Database);
dbContext.JobAttachments.Remove(ja); Database.JobAttachments.Remove(ja);
} }
public static bool CanDelete(this UserAttachment ua) public static bool CanDelete(this UserAttachment ua)
{ {
return true; // Placeholder - Currently Can Always Delete; if (UserService.CurrentAuthorization.Has(Claims.User.Actions.RemoveAnyAttachments))
return true;
if (UserService.CurrentAuthorization.Has(Claims.User.Actions.RemoveOwnAttachments)
&& ua.TechUserId == UserService.CurrentUserId)
return true;
return false;
} }
public static void OnDelete(this UserAttachment ua, DiscoDataContext dbContext) public static void OnDelete(this UserAttachment ua, DiscoDataContext Database)
{ {
if (!ua.CanDelete()) if (!ua.CanDelete())
throw new InvalidOperationException("Deletion of Attachment is Denied"); throw new InvalidOperationException("Deletion of Attachment is Denied");
ua.RepositoryDelete(dbContext); ua.RepositoryDelete(Database);
dbContext.UserAttachments.Remove(ua); Database.UserAttachments.Remove(ua);
} }
#endregion #endregion
+53 -52
View File
@@ -6,16 +6,17 @@ using Disco.Models.Repository;
using Disco.Data.Repository; using Disco.Data.Repository;
using System.IO; using System.IO;
using Disco.BI.DocumentTemplateBI; using Disco.BI.DocumentTemplateBI;
using Disco.Services.Users;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
public static class AttachmentExtensions public static class AttachmentExtensions
{ {
public static bool ImportPdfAttachment(this DocumentUniqueIdentifier UniqueIdentifier, DiscoDataContext dbContext, System.IO.Stream PdfContent, byte[] PdfThumbnail) public static bool ImportPdfAttachment(this DocumentUniqueIdentifier UniqueIdentifier, DiscoDataContext Database, System.IO.Stream PdfContent, byte[] PdfThumbnail)
{ {
UniqueIdentifier.LoadComponents(dbContext); UniqueIdentifier.LoadComponents(Database);
DocumentTemplate documentTemplate = UniqueIdentifier.DocumentTemplate; DocumentTemplate documentTemplate = UniqueIdentifier.DocumentTemplate;
string filename; string filename;
string comments; string comments;
@@ -31,25 +32,25 @@ namespace Disco.BI.Extensions
comments = string.Format("Generated: {0:s}", UniqueIdentifier.TimeStamp); comments = string.Format("Generated: {0:s}", UniqueIdentifier.TimeStamp);
} }
User creatorUser = UserBI.UserCache.GetUser(UniqueIdentifier.CreatorId, dbContext); User creatorUser = UserService.GetUser(UniqueIdentifier.CreatorId, Database);
if (creatorUser == null) if (creatorUser == null)
{ {
// No Creator User (or Username invalid) // No Creator User (or Username invalid)
creatorUser = UserBI.UserCache.CurrentUser; creatorUser = UserService.CurrentUser;
} }
switch (UniqueIdentifier.DataScope) switch (UniqueIdentifier.DataScope)
{ {
case DocumentTemplate.DocumentTemplateScopes.Device: case DocumentTemplate.DocumentTemplateScopes.Device:
Device d = (Device)UniqueIdentifier.Data; Device d = (Device)UniqueIdentifier.Data;
d.CreateAttachment(dbContext, creatorUser, filename, DocumentTemplate.PdfMimeType, comments, PdfContent, documentTemplate, PdfThumbnail); d.CreateAttachment(Database, creatorUser, filename, DocumentTemplate.PdfMimeType, comments, PdfContent, documentTemplate, PdfThumbnail);
return true; return true;
case DocumentTemplate.DocumentTemplateScopes.Job: case DocumentTemplate.DocumentTemplateScopes.Job:
Job j = (Job)UniqueIdentifier.Data; Job j = (Job)UniqueIdentifier.Data;
j.CreateAttachment(dbContext, creatorUser, filename, DocumentTemplate.PdfMimeType, comments, PdfContent, documentTemplate, PdfThumbnail); j.CreateAttachment(Database, creatorUser, filename, DocumentTemplate.PdfMimeType, comments, PdfContent, documentTemplate, PdfThumbnail);
return true; return true;
case DocumentTemplate.DocumentTemplateScopes.User: case DocumentTemplate.DocumentTemplateScopes.User:
User u = (User)UniqueIdentifier.Data; User u = (User)UniqueIdentifier.Data;
u.CreateAttachment(dbContext, creatorUser, filename, DocumentTemplate.PdfMimeType, comments, PdfContent, documentTemplate, PdfThumbnail); u.CreateAttachment(Database, creatorUser, filename, DocumentTemplate.PdfMimeType, comments, PdfContent, documentTemplate, PdfThumbnail);
return true; return true;
default: default:
return false; return false;
@@ -57,47 +58,47 @@ namespace Disco.BI.Extensions
} }
public static string RepositoryFilename(this DeviceAttachment da, DiscoDataContext dbContext) public static string RepositoryFilename(this DeviceAttachment da, DiscoDataContext Database)
{ {
return Path.Combine(DataStore.CreateLocation(dbContext, "DeviceAttachments", da.Timestamp), string.Format("{0}_{1}_file", da.DeviceSerialNumber, da.Id)); return Path.Combine(DataStore.CreateLocation(Database, "DeviceAttachments", da.Timestamp), string.Format("{0}_{1}_file", da.DeviceSerialNumber, da.Id));
} }
public static string RepositoryFilename(this JobAttachment ja, DiscoDataContext dbContext) public static string RepositoryFilename(this JobAttachment ja, DiscoDataContext Database)
{ {
return Path.Combine(DataStore.CreateLocation(dbContext, "JobAttachments", ja.Timestamp), string.Format("{0}_{1}_file", ja.JobId, ja.Id)); return Path.Combine(DataStore.CreateLocation(Database, "JobAttachments", ja.Timestamp), string.Format("{0}_{1}_file", ja.JobId, ja.Id));
} }
public static string RepositoryFilename(this UserAttachment ua, DiscoDataContext dbContext) public static string RepositoryFilename(this UserAttachment ua, DiscoDataContext Database)
{ {
return Path.Combine(DataStore.CreateLocation(dbContext, "UserAttachments", ua.Timestamp), string.Format("{0}_{1}_file", ua.UserId, ua.Id)); return Path.Combine(DataStore.CreateLocation(Database, "UserAttachments", ua.Timestamp), string.Format("{0}_{1}_file", ua.UserId, ua.Id));
} }
private static string RepositoryThumbnailFilenameInternal(string DirectoryPath, string Filename) private static string RepositoryThumbnailFilenameInternal(string DirectoryPath, string Filename)
{ {
return Path.Combine(DirectoryPath, Filename); return Path.Combine(DirectoryPath, Filename);
} }
public static string RepositoryThumbnailFilename(this DeviceAttachment da, DiscoDataContext dbContext) public static string RepositoryThumbnailFilename(this DeviceAttachment da, DiscoDataContext Database)
{ {
return RepositoryThumbnailFilenameInternal(DataStore.CreateLocation(dbContext, "DeviceAttachments", da.Timestamp), string.Format("{0}_{1}_thumb.jpg", da.DeviceSerialNumber, da.Id)); return RepositoryThumbnailFilenameInternal(DataStore.CreateLocation(Database, "DeviceAttachments", da.Timestamp), string.Format("{0}_{1}_thumb.jpg", da.DeviceSerialNumber, da.Id));
} }
public static string RepositoryThumbnailFilename(this JobAttachment ja, DiscoDataContext dbContext) public static string RepositoryThumbnailFilename(this JobAttachment ja, DiscoDataContext Database)
{ {
return RepositoryThumbnailFilenameInternal(DataStore.CreateLocation(dbContext, "JobAttachments", ja.Timestamp), string.Format("{0}_{1}_thumb.jpg", ja.JobId, ja.Id)); return RepositoryThumbnailFilenameInternal(DataStore.CreateLocation(Database, "JobAttachments", ja.Timestamp), string.Format("{0}_{1}_thumb.jpg", ja.JobId, ja.Id));
} }
public static string RepositoryThumbnailFilename(this UserAttachment ua, DiscoDataContext dbContext) public static string RepositoryThumbnailFilename(this UserAttachment ua, DiscoDataContext Database)
{ {
return RepositoryThumbnailFilenameInternal(DataStore.CreateLocation(dbContext, "UserAttachments", ua.Timestamp), string.Format("{0}_{1}_thumb.jpg", ua.UserId, ua.Id)); return RepositoryThumbnailFilenameInternal(DataStore.CreateLocation(Database, "UserAttachments", ua.Timestamp), string.Format("{0}_{1}_thumb.jpg", ua.UserId, ua.Id));
} }
public static void RepositoryDelete(this DeviceAttachment da, DiscoDataContext dbContext) public static void RepositoryDelete(this DeviceAttachment da, DiscoDataContext Database)
{ {
RepositoryDelete(da.RepositoryFilename(dbContext), da.RepositoryThumbnailFilename(dbContext)); RepositoryDelete(da.RepositoryFilename(Database), da.RepositoryThumbnailFilename(Database));
} }
public static void RepositoryDelete(this JobAttachment ja, DiscoDataContext dbContext) public static void RepositoryDelete(this JobAttachment ja, DiscoDataContext Database)
{ {
RepositoryDelete(ja.RepositoryFilename(dbContext), ja.RepositoryThumbnailFilename(dbContext)); RepositoryDelete(ja.RepositoryFilename(Database), ja.RepositoryThumbnailFilename(Database));
} }
public static void RepositoryDelete(this UserAttachment ua, DiscoDataContext dbContext) public static void RepositoryDelete(this UserAttachment ua, DiscoDataContext Database)
{ {
RepositoryDelete(ua.RepositoryFilename(dbContext), ua.RepositoryThumbnailFilename(dbContext)); RepositoryDelete(ua.RepositoryFilename(Database), ua.RepositoryThumbnailFilename(Database));
} }
private static void RepositoryDelete(params string[] filePaths) private static void RepositoryDelete(params string[] filePaths)
{ {
@@ -108,39 +109,39 @@ namespace Disco.BI.Extensions
} }
} }
public static string SaveAttachment(this DeviceAttachment da, DiscoDataContext dbContext, Stream FileContent) public static string SaveAttachment(this DeviceAttachment da, DiscoDataContext Database, Stream FileContent)
{ {
string filePath = da.RepositoryFilename(dbContext); string filePath = da.RepositoryFilename(Database);
SaveAttachment(filePath, FileContent); SaveAttachment(filePath, FileContent);
return filePath; return filePath;
} }
public static string SaveAttachment(this JobAttachment ja, DiscoDataContext dbContext, Stream FileContent) public static string SaveAttachment(this JobAttachment ja, DiscoDataContext Database, Stream FileContent)
{ {
string filePath = ja.RepositoryFilename(dbContext); string filePath = ja.RepositoryFilename(Database);
SaveAttachment(filePath, FileContent); SaveAttachment(filePath, FileContent);
return filePath; return filePath;
} }
public static string SaveAttachment(this UserAttachment ua, DiscoDataContext dbContext, Stream FileContent) public static string SaveAttachment(this UserAttachment ua, DiscoDataContext Database, Stream FileContent)
{ {
string filePath = ua.RepositoryFilename(dbContext); string filePath = ua.RepositoryFilename(Database);
SaveAttachment(filePath, FileContent); SaveAttachment(filePath, FileContent);
return filePath; return filePath;
} }
public static string SaveThumbnailAttachment(this DeviceAttachment da, DiscoDataContext dbContext, byte[] FileContent) public static string SaveThumbnailAttachment(this DeviceAttachment da, DiscoDataContext Database, byte[] FileContent)
{ {
string filePath = da.RepositoryThumbnailFilename(dbContext); string filePath = da.RepositoryThumbnailFilename(Database);
File.WriteAllBytes(filePath, FileContent); File.WriteAllBytes(filePath, FileContent);
return filePath; return filePath;
} }
public static string SaveThumbnailAttachment(this JobAttachment ja, DiscoDataContext dbContext, byte[] FileContent) public static string SaveThumbnailAttachment(this JobAttachment ja, DiscoDataContext Database, byte[] FileContent)
{ {
string filePath = ja.RepositoryThumbnailFilename(dbContext); string filePath = ja.RepositoryThumbnailFilename(Database);
File.WriteAllBytes(filePath, FileContent); File.WriteAllBytes(filePath, FileContent);
return filePath; return filePath;
} }
public static string SaveThumbnailAttachment(this UserAttachment ua, DiscoDataContext dbContext, byte[] FileContent) public static string SaveThumbnailAttachment(this UserAttachment ua, DiscoDataContext Database, byte[] FileContent)
{ {
string filePath = ua.RepositoryThumbnailFilename(dbContext); string filePath = ua.RepositoryThumbnailFilename(Database);
File.WriteAllBytes(filePath, FileContent); File.WriteAllBytes(filePath, FileContent);
return filePath; return filePath;
} }
@@ -154,39 +155,39 @@ namespace Disco.BI.Extensions
} }
} }
public static string GenerateThumbnail(this DeviceAttachment da, DiscoDataContext dbContext) public static string GenerateThumbnail(this DeviceAttachment da, DiscoDataContext Database)
{ {
string filePath = da.RepositoryThumbnailFilename(dbContext); string filePath = da.RepositoryThumbnailFilename(Database);
AttachmentBI.Utilities.GenerateThumbnail(da.RepositoryFilename(dbContext), da.MimeType, filePath); AttachmentBI.Utilities.GenerateThumbnail(da.RepositoryFilename(Database), da.MimeType, filePath);
return filePath; return filePath;
} }
public static string GenerateThumbnail(this JobAttachment ja, DiscoDataContext dbContext) public static string GenerateThumbnail(this JobAttachment ja, DiscoDataContext Database)
{ {
string filePath = ja.RepositoryThumbnailFilename(dbContext); string filePath = ja.RepositoryThumbnailFilename(Database);
AttachmentBI.Utilities.GenerateThumbnail(ja.RepositoryFilename(dbContext), ja.MimeType, filePath); AttachmentBI.Utilities.GenerateThumbnail(ja.RepositoryFilename(Database), ja.MimeType, filePath);
return filePath; return filePath;
} }
public static string GenerateThumbnail(this UserAttachment ua, DiscoDataContext dbContext) public static string GenerateThumbnail(this UserAttachment ua, DiscoDataContext Database)
{ {
string filePath = ua.RepositoryThumbnailFilename(dbContext); string filePath = ua.RepositoryThumbnailFilename(Database);
AttachmentBI.Utilities.GenerateThumbnail(ua.RepositoryFilename(dbContext), ua.MimeType, filePath); AttachmentBI.Utilities.GenerateThumbnail(ua.RepositoryFilename(Database), ua.MimeType, filePath);
return filePath; return filePath;
} }
public static string GenerateThumbnail(this DeviceAttachment da, DiscoDataContext dbContext, Stream SourceFile) public static string GenerateThumbnail(this DeviceAttachment da, DiscoDataContext Database, Stream SourceFile)
{ {
string filePath = da.RepositoryThumbnailFilename(dbContext); string filePath = da.RepositoryThumbnailFilename(Database);
AttachmentBI.Utilities.GenerateThumbnail(SourceFile, da.MimeType, filePath); AttachmentBI.Utilities.GenerateThumbnail(SourceFile, da.MimeType, filePath);
return filePath; return filePath;
} }
public static string GenerateThumbnail(this JobAttachment ja, DiscoDataContext dbContext, Stream SourceFile) public static string GenerateThumbnail(this JobAttachment ja, DiscoDataContext Database, Stream SourceFile)
{ {
string filePath = ja.RepositoryThumbnailFilename(dbContext); string filePath = ja.RepositoryThumbnailFilename(Database);
AttachmentBI.Utilities.GenerateThumbnail(SourceFile, ja.MimeType, filePath); AttachmentBI.Utilities.GenerateThumbnail(SourceFile, ja.MimeType, filePath);
return filePath; return filePath;
} }
public static string GenerateThumbnail(this UserAttachment ua, DiscoDataContext dbContext, Stream SourceFile) public static string GenerateThumbnail(this UserAttachment ua, DiscoDataContext Database, Stream SourceFile)
{ {
string filePath = ua.RepositoryThumbnailFilename(dbContext); string filePath = ua.RepositoryThumbnailFilename(Database);
AttachmentBI.Utilities.GenerateThumbnail(SourceFile, ua.MimeType, filePath); AttachmentBI.Utilities.GenerateThumbnail(SourceFile, ua.MimeType, filePath);
return filePath; return filePath;
} }
@@ -0,0 +1,28 @@
using Disco.Data.Repository;
using Disco.Models.Authorization;
using Disco.Models.Repository;
using Disco.Services.Users;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.BI.Extensions
{
public static class AuthorizationRoleExtensions
{
public static void Delete(this IRoleToken roleToken, DiscoDataContext Database)
{
var role = Database.AuthorizationRoles.Find(roleToken.Role.Id);
UserService.DeleteAuthorizationRole(Database, roleToken.Role);
}
public static void Delete(this AuthorizationRole role, DiscoDataContext Database)
{
UserService.DeleteAuthorizationRole(Database, role);
}
}
}
@@ -6,6 +6,7 @@ using Disco.Models.ClientServices;
using System.Web; using System.Web;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Services.Users;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
@@ -20,10 +21,10 @@ namespace Disco.BI.Extensions
if (HttpContext.Current.Request.IsAuthenticated) if (HttpContext.Current.Request.IsAuthenticated)
username = HttpContext.Current.User.Identity.Name; username = HttpContext.Current.User.Identity.Name;
using (DiscoDataContext dbContext = new DiscoDataContext()) using (DiscoDataContext database = new DiscoDataContext())
{ {
EnrolResponse response = DeviceBI.DeviceEnrol.Enrol(dbContext, username, request); EnrolResponse response = DeviceBI.DeviceEnrol.Enrol(database, username, request);
dbContext.SaveChanges(); database.SaveChanges();
return response; return response;
} }
} }
@@ -40,14 +41,14 @@ namespace Disco.BI.Extensions
if (username == null) if (username == null)
throw new InvalidOperationException("Unauthenticated Http Context"); throw new InvalidOperationException("Unauthenticated Http Context");
using (DiscoDataContext dbContext = new DiscoDataContext()) using (DiscoDataContext database = new DiscoDataContext())
{ {
User user = UserBI.UserCache.GetUser(username, dbContext, true); User user = UserService.GetUser(username, database, true);
WhoAmIResponse response = new WhoAmIResponse() WhoAmIResponse response = new WhoAmIResponse()
{ {
Username = user.Id, Username = user.Id,
DisplayName = user.DisplayName, DisplayName = user.DisplayName,
Type = user.Type Type = "TODO!"
}; };
return response; return response;
} }
@@ -58,10 +59,10 @@ namespace Disco.BI.Extensions
if (HttpContext.Current == null) if (HttpContext.Current == null)
throw new PlatformNotSupportedException("This function can only be accessed from within ASP.NET"); throw new PlatformNotSupportedException("This function can only be accessed from within ASP.NET");
using (DiscoDataContext dbContext = new DiscoDataContext()) using (DiscoDataContext database = new DiscoDataContext())
{ {
MacEnrolResponse response = DeviceBI.DeviceEnrol.MacEnrol(dbContext, request, false); MacEnrolResponse response = DeviceBI.DeviceEnrol.MacEnrol(database, request, false);
dbContext.SaveChanges(); database.SaveChanges();
return response; return response;
} }
} }
@@ -5,6 +5,8 @@ using System.Text;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.BI.Interop.ActiveDirectory; using Disco.BI.Interop.ActiveDirectory;
using Disco.Services.Users;
using Disco.Services.Authorization;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
@@ -17,36 +19,57 @@ namespace Disco.BI.Extensions
public static bool CanCreateJob(this Device d) public static bool CanCreateJob(this Device d)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.Create))
return false;
return !d.IsDecommissioned(); return !d.IsDecommissioned();
} }
public static bool CanUpdateAssignment(this Device d) public static bool CanUpdateAssignment(this Device d)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Device.Actions.AssignUser))
return false;
return !d.IsDecommissioned(); return !d.IsDecommissioned();
} }
public static bool CanUpdateDeviceProfile(this Device d) public static bool CanUpdateDeviceProfile(this Device d)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Device.Properties.DeviceProfile))
return false;
return !d.IsDecommissioned(); return !d.IsDecommissioned();
} }
public static bool CanUpdateDeviceBatch(this Device d) public static bool CanUpdateDeviceBatch(this Device d)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Device.Properties.DeviceBatch))
return false;
return !d.IsDecommissioned(); return !d.IsDecommissioned();
} }
public static bool CanUpdateTrustEnrol(this Device d) public static bool CanUpdateTrustEnrol(this Device d)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Device.Actions.AllowUnauthenticatedEnrol))
return false;
return !d.IsDecommissioned() && !d.AllowUnauthenticatedEnrol; return !d.IsDecommissioned() && !d.AllowUnauthenticatedEnrol;
} }
public static bool CanUpdateUntrustEnrol(this Device d) public static bool CanUpdateUntrustEnrol(this Device d)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Device.Actions.AllowUnauthenticatedEnrol))
return false;
return !d.IsDecommissioned() && d.AllowUnauthenticatedEnrol; return !d.IsDecommissioned() && d.AllowUnauthenticatedEnrol;
} }
#region Decommission #region Decommission
public static bool CanDecommission(this Device d) public static bool CanDecommission(this Device d)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Device.Actions.Decommission))
return false;
if (d.DecommissionedDate.HasValue) if (d.DecommissionedDate.HasValue)
return false; // Already Decommissioned return false; // Already Decommissioned
@@ -80,6 +103,9 @@ namespace Disco.BI.Extensions
#region Recommission #region Recommission
public static bool CanRecommission(this Device d) public static bool CanRecommission(this Device d)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Device.Actions.Recommission))
return false;
return d.DecommissionedDate.HasValue; return d.DecommissionedDate.HasValue;
} }
public static void OnRecommission(this Device d) public static void OnRecommission(this Device d)
@@ -105,17 +131,20 @@ namespace Disco.BI.Extensions
#region Delete #region Delete
public static bool CanDelete(this Device d) public static bool CanDelete(this Device d)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Device.Actions.Delete))
return false;
return d.DecommissionedDate.HasValue; return d.DecommissionedDate.HasValue;
} }
public static void OnDelete(this Device d, DiscoDataContext dbContext) public static void OnDelete(this Device d, DiscoDataContext Database)
{ {
// Delete Jobs // Delete Jobs
foreach (Job j in dbContext.Jobs.Where(i => i.DeviceSerialNumber == d.SerialNumber)) foreach (Job j in Database.Jobs.Where(i => i.DeviceSerialNumber == d.SerialNumber))
{ {
if (j.UserId == null) if (j.UserId == null)
{ // No User associated, thus must Delete whole Job { // No User associated, thus must Delete whole Job
if (j.CanDelete()) if (j.CanDelete())
j.OnDelete(dbContext); j.OnDelete(Database);
else else
throw new InvalidOperationException(string.Format("Deletion of Device is Denied (See Job# {0})", j.Id)); throw new InvalidOperationException(string.Format("Deletion of Device is Denied (See Job# {0})", j.Id));
} }
@@ -128,35 +157,35 @@ namespace Disco.BI.Extensions
JobLog jobLog = new JobLog() JobLog jobLog = new JobLog()
{ {
JobId = j.Id, JobId = j.Id,
TechUserId = UserBI.UserCache.CurrentUser.Id, TechUserId = UserService.CurrentUser.Id,
Timestamp = DateTime.Now, Timestamp = DateTime.Now,
Comments = string.Format("Device Deleted{0}{0}Serial Number: {1}{0}Computer Name: {2}{0}Model: {3}{0}Profile: {4}", 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.ComputerName, d.DeviceModel, d.DeviceProfile)
}; };
dbContext.JobLogs.Add(jobLog); Database.JobLogs.Add(jobLog);
} }
} }
// Disable Wireless Certificates // Disable Wireless Certificates
foreach (var wc in dbContext.DeviceCertificates.Where(i => i.DeviceSerialNumber == d.SerialNumber)) foreach (var wc in Database.DeviceCertificates.Where(i => i.DeviceSerialNumber == d.SerialNumber))
{ {
wc.DeviceSerialNumber = null; wc.DeviceSerialNumber = null;
wc.Enabled = false; wc.Enabled = false;
} }
// Delete Device Details // Delete Device Details
foreach (var dd in dbContext.DeviceDetails.Where(i => i.DeviceSerialNumber == d.SerialNumber)) foreach (var dd in Database.DeviceDetails.Where(i => i.DeviceSerialNumber == d.SerialNumber))
dbContext.DeviceDetails.Remove(dd); Database.DeviceDetails.Remove(dd);
// Delete Device Attachments // Delete Device Attachments
foreach (var da in dbContext.DeviceAttachments.Where(i => i.DeviceSerialNumber == d.SerialNumber)) foreach (var da in Database.DeviceAttachments.Where(i => i.DeviceSerialNumber == d.SerialNumber))
{ {
da.RepositoryDelete(dbContext); da.RepositoryDelete(Database);
dbContext.DeviceAttachments.Remove(da); Database.DeviceAttachments.Remove(da);
} }
// Delete Device User Assignments // Delete Device User Assignments
foreach (var dua in dbContext.DeviceUserAssignments.Where(i => i.DeviceSerialNumber == d.SerialNumber)) foreach (var dua in Database.DeviceUserAssignments.Where(i => i.DeviceSerialNumber == d.SerialNumber))
dbContext.DeviceUserAssignments.Remove(dua); Database.DeviceUserAssignments.Remove(dua);
dbContext.Devices.Remove(d); Database.Devices.Remove(d);
} }
#endregion #endregion
} }
@@ -4,28 +4,33 @@ using System.Linq;
using System.Text; using System.Text;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Services.Users;
using Disco.Services.Authorization;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
public static class DeviceBatchExtensions public static class DeviceBatchExtensions
{ {
public static bool CanDelete(this DeviceBatch db, DiscoDataContext dbContext) public static bool CanDelete(this DeviceBatch db, DiscoDataContext Database)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Config.DeviceBatch.Delete))
return false;
// Can't Delete if Contains Devices // Can't Delete if Contains Devices
var deviceCount = dbContext.Devices.Count(d => d.DeviceBatchId == db.Id); var deviceCount = Database.Devices.Count(d => d.DeviceBatchId == db.Id);
if (deviceCount > 0) if (deviceCount > 0)
return false; return false;
return true; return true;
} }
public static void Delete(this DeviceBatch db, DiscoDataContext dbContext) public static void Delete(this DeviceBatch db, DiscoDataContext Database)
{ {
if (!db.CanDelete(dbContext)) if (!db.CanDelete(Database))
throw new InvalidOperationException("The state of this Device Batch doesn't allow it to be deleted"); throw new InvalidOperationException("The state of this Device Batch doesn't allow it to be deleted");
// Delete Batch // Delete Batch
dbContext.DeviceBatches.Remove(db); Database.DeviceBatches.Remove(db);
} }
} }
} }
@@ -11,16 +11,10 @@ namespace Disco.BI.Extensions
public static class DeviceCertificateExtensions public static class DeviceCertificateExtensions
{ {
public static Tuple<DeviceCertificate, List<string>> AllocateCertificate(this Device device, DiscoDataContext dbContext) public static Tuple<DeviceCertificate, List<string>> AllocateCertificate(this Device device, DiscoDataContext Database)
{ {
if (!string.IsNullOrEmpty(device.DeviceProfile.CertificateProviderId)) if (!string.IsNullOrEmpty(device.DeviceProfile.CertificateProviderId))
{ {
// REMOVED 2012-07-18 G# - Plugin is responsible for checking
//var deviceCertificates = dbContext.DeviceCertificates.Where(c =>
// c.DeviceSerialNumber == device.SerialNumber &&
// c.ProviderId == device.DeviceProfile.CertificateProviderId &&
// c.Enabled == true).ToList();
// Load Plugin // Load Plugin
PluginFeatureManifest featureManifest = Plugins.GetPluginFeature(device.DeviceProfile.CertificateProviderId, typeof(CertificateProviderFeature)); PluginFeatureManifest featureManifest = Plugins.GetPluginFeature(device.DeviceProfile.CertificateProviderId, typeof(CertificateProviderFeature));
@@ -32,7 +26,7 @@ namespace Disco.BI.Extensions
// return new Tuple<DeviceCertificate, List<string>>(deviceCertificates[0], providerPlugin.RemoveExistingCertificateNames()); // return new Tuple<DeviceCertificate, List<string>>(deviceCertificates[0], providerPlugin.RemoveExistingCertificateNames());
//else //else
return providerFeature.AllocateCertificate(dbContext, device); return providerFeature.AllocateCertificate(Database, device);
} }
} }
+38 -22
View File
@@ -8,13 +8,15 @@ using System.Collections.Generic;
using System; using System;
using System.IO; using System.IO;
using Disco.Models.Interop.ActiveDirectory; using Disco.Models.Interop.ActiveDirectory;
using Disco.Services.Users;
using Disco.Services.Authorization;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
public static class DeviceExtensions public static class DeviceExtensions
{ {
public static string ComputerNameRender(this Device device, DiscoDataContext context) public static string ComputerNameRender(this Device device, DiscoDataContext Database)
{ {
DeviceProfile deviceProfile = device.DeviceProfile; DeviceProfile deviceProfile = device.DeviceProfile;
Expressions.Expression computerNameTemplateExpression = null; Expressions.Expression computerNameTemplateExpression = null;
@@ -24,7 +26,7 @@ namespace Disco.BI.Extensions
//return Expressions.Expression.TokenizeSingleDynamic(null, deviceProfile.Configuration(context).ComputerNameTemplate, 0); //return Expressions.Expression.TokenizeSingleDynamic(null, deviceProfile.Configuration(context).ComputerNameTemplate, 0);
return Expressions.Expression.TokenizeSingleDynamic(null, deviceProfile.ComputerNameTemplate, 0); return Expressions.Expression.TokenizeSingleDynamic(null, deviceProfile.ComputerNameTemplate, 0);
}); });
System.Collections.IDictionary evaluatorVariables = Expressions.Expression.StandardVariables(null, context, UserBI.UserCache.CurrentUser, System.DateTime.Now, null); System.Collections.IDictionary evaluatorVariables = Expressions.Expression.StandardVariables(null, Database, UserService.CurrentUser, System.DateTime.Now, null);
string rendered; string rendered;
try try
{ {
@@ -40,12 +42,12 @@ namespace Disco.BI.Extensions
} }
return rendered.ToString(); return rendered.ToString();
} }
public static System.Collections.Generic.List<DocumentTemplate> AvailableDocumentTemplates(this Device d, DiscoDataContext Context, User User, System.DateTime TimeStamp) public static System.Collections.Generic.List<DocumentTemplate> AvailableDocumentTemplates(this Device d, DiscoDataContext Database, User User, System.DateTime TimeStamp)
{ {
List<DocumentTemplate> ats = Context.DocumentTemplates List<DocumentTemplate> ats = Database.DocumentTemplates
.Where(at => at.Scope == Disco.Models.Repository.DocumentTemplate.DocumentTemplateScopes.Device).ToList(); .Where(at => at.Scope == Disco.Models.Repository.DocumentTemplate.DocumentTemplateScopes.Device).ToList();
return ats.Where(at => at.FilterExpressionMatches(d, Context, User, TimeStamp, DocumentState.DefaultState())).ToList(); return ats.Where(at => at.FilterExpressionMatches(d, Database, User, TimeStamp, DocumentState.DefaultState())).ToList();
} }
public static bool UpdateLastNetworkLogonDate(this Device Device) public static bool UpdateLastNetworkLogonDate(this Device Device)
@@ -53,7 +55,7 @@ namespace Disco.BI.Extensions
return ActiveDirectoryUpdateLastNetworkLogonDateJob.UpdateLastNetworkLogonDate(Device); return ActiveDirectoryUpdateLastNetworkLogonDateJob.UpdateLastNetworkLogonDate(Device);
} }
public static DeviceAttachment CreateAttachment(this Device Device, DiscoDataContext dbContext, User CreatorUser, string Filename, string MimeType, string Comments, Stream Content, DocumentTemplate DocumentTemplate = null, byte[] PdfThumbnail = null) 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)
{ {
if (string.IsNullOrEmpty(MimeType) || MimeType.Equals("unknown/unknown", StringComparison.InvariantCultureIgnoreCase)) if (string.IsNullOrEmpty(MimeType) || MimeType.Equals("unknown/unknown", StringComparison.InvariantCultureIgnoreCase))
MimeType = Interop.MimeTypes.ResolveMimeType(Filename); MimeType = Interop.MimeTypes.ResolveMimeType(Filename);
@@ -71,20 +73,20 @@ namespace Disco.BI.Extensions
if (DocumentTemplate != null) if (DocumentTemplate != null)
da.DocumentTemplateId = DocumentTemplate.Id; da.DocumentTemplateId = DocumentTemplate.Id;
dbContext.DeviceAttachments.Add(da); Database.DeviceAttachments.Add(da);
dbContext.SaveChanges(); Database.SaveChanges();
da.SaveAttachment(dbContext, Content); da.SaveAttachment(Database, Content);
Content.Position = 0; Content.Position = 0;
if (PdfThumbnail == null) if (PdfThumbnail == null)
da.GenerateThumbnail(dbContext, Content); da.GenerateThumbnail(Database, Content);
else else
da.SaveThumbnailAttachment(dbContext, PdfThumbnail); da.SaveThumbnailAttachment(Database, PdfThumbnail);
return da; return da;
} }
public static Device AddOffline(this Device d, DiscoDataContext dbContext) public static Device AddOffline(this Device d, DiscoDataContext Database)
{ {
// Just Include: // Just Include:
// - Serial Number // - Serial Number
@@ -93,17 +95,31 @@ namespace Disco.BI.Extensions
// - Assigned User Id // - Assigned User Id
// - Batch // - Batch
// Enforce Authorization
var auth = UserService.CurrentAuthorization;
if (!auth.Has(Claims.Device.Properties.AssetNumber))
d.AssetNumber = null;
if (!auth.Has(Claims.Device.Properties.Location))
d.Location = null;
if (!auth.Has(Claims.Device.Properties.DeviceBatch))
d.DeviceBatchId = null;
if (!auth.Has(Claims.Device.Properties.DeviceProfile))
d.DeviceProfileId = Database.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId;
if (!auth.Has(Claims.Device.Actions.AssignUser))
d.AssignedUserId = null;
// Batch // Batch
DeviceBatch db = default(DeviceBatch); DeviceBatch db = default(DeviceBatch);
if (d.DeviceBatchId.HasValue) if (d.DeviceBatchId.HasValue)
db = dbContext.DeviceBatches.Find(d.DeviceBatchId.Value); db = Database.DeviceBatches.Find(d.DeviceBatchId.Value);
// Default Device Model // Default Device Model
DeviceModel dm = default(DeviceModel); DeviceModel dm = default(DeviceModel);
if (db != null && db.DefaultDeviceModelId.HasValue) if (db != null && db.DefaultDeviceModelId.HasValue)
dm = dbContext.DeviceModels.Find(db.DefaultDeviceModelId); // From Batch dm = Database.DeviceModels.Find(db.DefaultDeviceModelId); // From Batch
else else
dm = dbContext.DeviceModels.Find(1); // Default dm = Database.DeviceModels.Find(1); // Default
Device d2 = new Device() Device d2 = new Device()
{ {
@@ -112,7 +128,7 @@ namespace Disco.BI.Extensions
Location = d.Location, Location = d.Location,
CreatedDate = DateTime.Now, CreatedDate = DateTime.Now,
DeviceProfileId = d.DeviceProfileId, DeviceProfileId = d.DeviceProfileId,
DeviceProfile = dbContext.DeviceProfiles.Find(d.DeviceProfileId), DeviceProfile = Database.DeviceProfiles.Find(d.DeviceProfileId),
AllowUnauthenticatedEnrol = true, AllowUnauthenticatedEnrol = true,
DeviceModelId = dm.Id, DeviceModelId = dm.Id,
DeviceModel = dm, DeviceModel = dm,
@@ -120,22 +136,22 @@ namespace Disco.BI.Extensions
DeviceBatch = db DeviceBatch = db
}; };
dbContext.Devices.Add(d2); Database.Devices.Add(d2);
if (!string.IsNullOrEmpty(d.AssignedUserId)) if (!string.IsNullOrEmpty(d.AssignedUserId))
{ {
User u = UserBI.UserCache.GetUser(d.AssignedUserId, dbContext, true); User u = UserService.GetUser(d.AssignedUserId, Database, true);
d2.AssignDevice(dbContext, u); d2.AssignDevice(Database, u);
} }
return d2; return d2;
} }
public static DeviceUserAssignment AssignDevice(this Device d, DiscoDataContext dbContext, User u) public static DeviceUserAssignment AssignDevice(this Device d, DiscoDataContext Database, User u)
{ {
DeviceUserAssignment newDua = default(DeviceUserAssignment); DeviceUserAssignment newDua = default(DeviceUserAssignment);
// Mark existing assignments as Unassigned // Mark existing assignments as Unassigned
foreach (var dua in dbContext.DeviceUserAssignments.Where(m => m.DeviceSerialNumber == d.SerialNumber && !m.UnassignedDate.HasValue)) foreach (var dua in Database.DeviceUserAssignments.Where(m => m.DeviceSerialNumber == d.SerialNumber && !m.UnassignedDate.HasValue))
dua.UnassignedDate = DateTime.Now; dua.UnassignedDate = DateTime.Now;
if (u != null) if (u != null)
@@ -147,7 +163,7 @@ namespace Disco.BI.Extensions
AssignedUserId = u.Id, AssignedUserId = u.Id,
AssignedDate = DateTime.Now AssignedDate = DateTime.Now
}; };
dbContext.DeviceUserAssignments.Add(newDua); Database.DeviceUserAssignments.Add(newDua);
d.AssignedUserId = u.Id; d.AssignedUserId = u.Id;
d.AssignedUser = u; d.AssignedUser = u;
@@ -6,6 +6,8 @@ using Disco.Models.Repository;
using System.IO; using System.IO;
using System.Drawing; using System.Drawing;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Services.Users;
using Disco.Services.Authorization;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
@@ -73,22 +75,24 @@ namespace Disco.BI.Extensions
} }
#region Actions #region Actions
// Added 2012-11-26 G# - Need ability to delete Device Models public static bool CanDelete(this DeviceModel dm, DiscoDataContext Database)
public static bool CanDelete(this DeviceModel dm, DiscoDataContext dbContext)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Config.DeviceModel.Delete))
return false;
// Can't Delete Default Model (Id: 1) // Can't Delete Default Model (Id: 1)
if (dm.Id == 1) if (dm.Id == 1)
return false; return false;
// Can't Delete if Contains Devices // Can't Delete if Contains Devices
if (dbContext.Devices.Count(d => d.DeviceModelId == dm.Id) > 0) if (Database.Devices.Count(d => d.DeviceModelId == dm.Id) > 0)
return false; return false;
return true; return true;
} }
public static void Delete(this DeviceModel dm, DiscoDataContext dbContext) public static void Delete(this DeviceModel dm, DiscoDataContext Database)
{ {
if (!dm.CanDelete(dbContext)) if (!dm.CanDelete(Database))
throw new InvalidOperationException("The state of this Device Model doesn't allow it to be deleted"); throw new InvalidOperationException("The state of this Device Model doesn't allow it to be deleted");
// Delete Image // Delete Image
@@ -97,13 +101,13 @@ namespace Disco.BI.Extensions
File.Delete(deviceModelImagePath); File.Delete(deviceModelImagePath);
// Delete any Device Model Components // Delete any Device Model Components
foreach (var deviceModelComponent in dbContext.DeviceComponents.Where(dc => dc.DeviceModelId == dm.Id).ToList()) foreach (var deviceModelComponent in Database.DeviceComponents.Where(dc => dc.DeviceModelId == dm.Id).ToList())
{ {
dbContext.DeviceComponents.Remove(deviceModelComponent); Database.DeviceComponents.Remove(deviceModelComponent);
} }
// Delete Model // Delete Model
dbContext.DeviceModels.Remove(dm); Database.DeviceModels.Remove(dm);
} }
// End Added 2012-11-26 G# // End Added 2012-11-26 G#
#endregion #endregion
@@ -6,6 +6,8 @@ using Disco.Models.Repository;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Data.Configuration.Modules; using Disco.Data.Configuration.Modules;
using Disco.Models.BI.Config; using Disco.Models.BI.Config;
using Disco.Services.Users;
using Disco.Services.Authorization;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
@@ -18,11 +20,11 @@ namespace Disco.BI.Extensions
Expressions.ExpressionCache.InvalidateKey(ComputerNameExpressionCacheModule, deviceProfile.Id.ToString()); Expressions.ExpressionCache.InvalidateKey(ComputerNameExpressionCacheModule, deviceProfile.Id.ToString());
} }
public static OrganisationAddress DefaultOrganisationAddressDetails(this DeviceProfile deviceProfile, DiscoDataContext dbContext) public static OrganisationAddress DefaultOrganisationAddressDetails(this DeviceProfile deviceProfile, DiscoDataContext Database)
{ {
if (deviceProfile.DefaultOrganisationAddress.HasValue) if (deviceProfile.DefaultOrganisationAddress.HasValue)
{ {
return dbContext.DiscoConfiguration.OrganisationAddresses.GetAddress(deviceProfile.DefaultOrganisationAddress.Value); return Database.DiscoConfiguration.OrganisationAddresses.GetAddress(deviceProfile.DefaultOrganisationAddress.Value);
} }
else else
{ {
@@ -30,38 +32,35 @@ namespace Disco.BI.Extensions
} }
} }
public static bool CanDelete(this DeviceProfile dp, DiscoDataContext dbContext) public static bool CanDelete(this DeviceProfile dp, DiscoDataContext Database)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Config.DeviceProfile.Delete))
return false;
// Can't Delete Default Profile (Id: 1) // Can't Delete Default Profile (Id: 1)
if (dp.Id == 1) if (dp.Id == 1)
return false; return false;
// Can't Delete if Contains Devices // Can't Delete if Contains Devices
if (dbContext.Devices.Count(d => d.DeviceProfileId == dp.Id) > 0) if (Database.Devices.Count(d => d.DeviceProfileId == dp.Id) > 0)
return false; return false;
return true; return true;
} }
public static void Delete(this DeviceProfile dp, DiscoDataContext dbContext) public static void Delete(this DeviceProfile dp, DiscoDataContext Database)
{ {
if (!dp.CanDelete(dbContext)) if (!dp.CanDelete(Database))
throw new InvalidOperationException("The state of this Device Profile doesn't allow it to be deleted"); throw new InvalidOperationException("The state of this Device Profile doesn't allow it to be deleted");
// Update Defaults // Update Defaults
if (dbContext.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId == dp.Id) if (Database.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId == dp.Id)
dbContext.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId = 1; Database.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId = 1;
if (dbContext.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId == dp.Id) if (Database.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId == dp.Id)
dbContext.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId = 1; Database.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId = 1;
// Delete Profile // Delete Profile
dbContext.DeviceProfiles.Remove(dp); Database.DeviceProfiles.Remove(dp);
} }
// Removed 2012-06-14 G# - Properties moved to DeviceProfile model & DB Migrated in DBv3.
//public static DeviceProfileConfiguration Configuration(this DeviceProfile dp, DiscoDataContext dbContext)
//{
// return dbContext.DiscoConfiguration.DeviceProfiles.DeviceProfile(dp);
//}
} }
} }
@@ -19,13 +19,13 @@ namespace Disco.BI.Extensions
{ {
private const string DocumentTemplateExpressionCacheTemplate = "DocumentTemplate_{0}"; private const string DocumentTemplateExpressionCacheTemplate = "DocumentTemplate_{0}";
public static string RepositoryFilename(this DocumentTemplate dt, DiscoDataContext dbContext) public static string RepositoryFilename(this DocumentTemplate dt, DiscoDataContext Database)
{ {
return System.IO.Path.Combine(DataStore.CreateLocation(dbContext, "DocumentTemplates"), string.Format("{0}.pdf", dt.Id)); return System.IO.Path.Combine(DataStore.CreateLocation(Database, "DocumentTemplates"), string.Format("{0}.pdf", dt.Id));
} }
public static string SavePdfTemplate(this DocumentTemplate dt, DiscoDataContext dbContext, Stream TemplateFile) public static string SavePdfTemplate(this DocumentTemplate dt, DiscoDataContext Database, Stream TemplateFile)
{ {
string filePath = dt.RepositoryFilename(dbContext); string filePath = dt.RepositoryFilename(Database);
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write)) using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{ {
TemplateFile.CopyTo(fs); TemplateFile.CopyTo(fs);
@@ -39,14 +39,14 @@ namespace Disco.BI.Extensions
return Interop.Pdf.PdfImporter.GetPageImages(pdfReader, PageNumber); return Interop.Pdf.PdfImporter.GetPageImages(pdfReader, PageNumber);
} }
public static ConcurrentDictionary<string, Expression> PdfExpressionsFromCache(this DocumentTemplate dt, DiscoDataContext dbContext) public static ConcurrentDictionary<string, Expression> PdfExpressionsFromCache(this DocumentTemplate dt, DiscoDataContext Database)
{ {
string cacheModuleKey = string.Format(DocumentTemplateExpressionCacheTemplate, dt.Id); string cacheModuleKey = string.Format(DocumentTemplateExpressionCacheTemplate, dt.Id);
var module = Expressions.ExpressionCache.GetModule(cacheModuleKey); var module = Expressions.ExpressionCache.GetModule(cacheModuleKey);
if (module == null) if (module == null)
{ {
// Cache // Cache
string templateFilename = dt.RepositoryFilename(dbContext); string templateFilename = dt.RepositoryFilename(Database);
PdfReader pdfReader = new PdfReader(templateFilename); PdfReader pdfReader = new PdfReader(templateFilename);
int pdfFieldOrdinal = 0; int pdfFieldOrdinal = 0;
foreach (string pdfFieldKey in pdfReader.AcroFields.Fields.Keys) foreach (string pdfFieldKey in pdfReader.AcroFields.Fields.Keys)
@@ -61,21 +61,21 @@ namespace Disco.BI.Extensions
return module; return module;
} }
public static List<BI.Expressions.Expression> ExtractPdfExpressions(this DocumentTemplate dt, DiscoDataContext dbContext) public static List<BI.Expressions.Expression> ExtractPdfExpressions(this DocumentTemplate dt, DiscoDataContext Database)
{ {
return dt.PdfExpressionsFromCache(dbContext).Values.OrderBy(e => e.Ordinal).ToList(); return dt.PdfExpressionsFromCache(Database).Values.OrderBy(e => e.Ordinal).ToList();
} }
public static System.IO.Stream GeneratePdfBulk(this DocumentTemplate dt, DiscoDataContext dbContext, User CreatorUser, System.DateTime Timestamp, params string[] DataObjectsIds) public static System.IO.Stream GeneratePdfBulk(this DocumentTemplate dt, DiscoDataContext Database, User CreatorUser, System.DateTime Timestamp, params string[] DataObjectsIds)
{ {
return Interop.Pdf.PdfGenerator.GenerateBulkFromTemplate(dt, dbContext, CreatorUser, Timestamp, DataObjectsIds); return Interop.Pdf.PdfGenerator.GenerateBulkFromTemplate(dt, Database, CreatorUser, Timestamp, DataObjectsIds);
} }
public static System.IO.Stream GeneratePdfBulk(this DocumentTemplate dt, DiscoDataContext dbContext, User CreatorUser, System.DateTime Timestamp, params object[] DataObjects) public static System.IO.Stream GeneratePdfBulk(this DocumentTemplate dt, DiscoDataContext Database, User CreatorUser, System.DateTime Timestamp, params object[] DataObjects)
{ {
return Interop.Pdf.PdfGenerator.GenerateBulkFromTemplate(dt, dbContext, CreatorUser, Timestamp, DataObjects); return Interop.Pdf.PdfGenerator.GenerateBulkFromTemplate(dt, Database, CreatorUser, Timestamp, DataObjects);
} }
public static System.IO.Stream GeneratePdf(this DocumentTemplate dt, DiscoDataContext dbContext, object Data, User CreatorUser, System.DateTime TimeStamp, DocumentState State, bool FlattenFields = false) public static System.IO.Stream GeneratePdf(this DocumentTemplate dt, DiscoDataContext Database, object Data, User CreatorUser, System.DateTime TimeStamp, DocumentState State, bool FlattenFields = false)
{ {
return Interop.Pdf.PdfGenerator.GenerateFromTemplate(dt, dbContext, Data, CreatorUser, TimeStamp, State, FlattenFields); return Interop.Pdf.PdfGenerator.GenerateFromTemplate(dt, Database, Data, CreatorUser, TimeStamp, State, FlattenFields);
} }
public static Expression FilterExpressionFromCache(this DocumentTemplate dt) public static Expression FilterExpressionFromCache(this DocumentTemplate dt)
@@ -86,12 +86,12 @@ namespace Disco.BI.Extensions
{ {
ExpressionCache.InvalidateKey("DocumentTemplateFilterExpression", dt.Id); ExpressionCache.InvalidateKey("DocumentTemplateFilterExpression", dt.Id);
} }
public static bool FilterExpressionMatches(this DocumentTemplate dt, object Data, DiscoDataContext DataContext, User User, System.DateTime TimeStamp, DocumentState State) public static bool FilterExpressionMatches(this DocumentTemplate dt, object Data, DiscoDataContext Database, User User, System.DateTime TimeStamp, DocumentState State)
{ {
if (!string.IsNullOrEmpty(dt.FilterExpression)) if (!string.IsNullOrEmpty(dt.FilterExpression))
{ {
Expression compiledExpression = dt.FilterExpressionFromCache(); Expression compiledExpression = dt.FilterExpressionFromCache();
System.Collections.IDictionary evaluatorVariables = Expression.StandardVariables(dt, DataContext, User, TimeStamp, State); System.Collections.IDictionary evaluatorVariables = Expression.StandardVariables(dt, Database, User, TimeStamp, State);
try try
{ {
object er = compiledExpression.EvaluateFirst<object>(Data, evaluatorVariables); object er = compiledExpression.EvaluateFirst<object>(Data, evaluatorVariables);
@@ -170,14 +170,14 @@ namespace Disco.BI.Extensions
Page Page
); );
} }
public static List<RectangleF> QRCodeLocations(this DocumentTemplate dt, DiscoDataContext dbContext) public static List<RectangleF> QRCodeLocations(this DocumentTemplate dt, DiscoDataContext Database)
{ {
return DocumentTemplateBI.DocumentTemplateQRCodeLocationCache.GetLocations(dt, dbContext); return DocumentTemplateBI.DocumentTemplateQRCodeLocationCache.GetLocations(dt, Database);
} }
public static void Delete(this DocumentTemplate dt, DiscoDataContext Context) public static void Delete(this DocumentTemplate dt, DiscoDataContext Database)
{ {
// Find & Rename all references // Find & Rename all references
foreach (DeviceAttachment a in Context.DeviceAttachments.Where(a => a.DocumentTemplateId == dt.Id)) foreach (DeviceAttachment a in Database.DeviceAttachments.Where(a => a.DocumentTemplateId == dt.Id))
{ {
a.Comments = string.Format("{0} - {1}", dt.Description, a.Comments); a.Comments = string.Format("{0} - {1}", dt.Description, a.Comments);
if (a.Comments.Length > 500) if (a.Comments.Length > 500)
@@ -185,7 +185,7 @@ namespace Disco.BI.Extensions
a.DocumentTemplateId = null; a.DocumentTemplateId = null;
a.DocumentTemplate = null; a.DocumentTemplate = null;
} }
foreach (JobAttachment a in Context.JobAttachments.Where(a => a.DocumentTemplateId == dt.Id)) foreach (JobAttachment a in Database.JobAttachments.Where(a => a.DocumentTemplateId == dt.Id))
{ {
a.Comments = string.Format("{0} - {1}", dt.Description, a.Comments); a.Comments = string.Format("{0} - {1}", dt.Description, a.Comments);
if (a.Comments.Length > 500) if (a.Comments.Length > 500)
@@ -193,7 +193,7 @@ namespace Disco.BI.Extensions
a.DocumentTemplateId = null; a.DocumentTemplateId = null;
a.DocumentTemplate = null; a.DocumentTemplate = null;
} }
foreach (UserAttachment a in Context.UserAttachments.Where(a => a.DocumentTemplateId == dt.Id)) foreach (UserAttachment a in Database.UserAttachments.Where(a => a.DocumentTemplateId == dt.Id))
{ {
a.Comments = string.Format("{0} - {1}", dt.Description, a.Comments); a.Comments = string.Format("{0} - {1}", dt.Description, a.Comments);
if (a.Comments.Length > 500) if (a.Comments.Length > 500)
@@ -206,7 +206,7 @@ namespace Disco.BI.Extensions
dt.JobSubTypes.Clear(); dt.JobSubTypes.Clear();
// Delete Template // Delete Template
string templateRepositoryFilename = dt.RepositoryFilename(Context); string templateRepositoryFilename = dt.RepositoryFilename(Database);
if (System.IO.File.Exists(templateRepositoryFilename)) if (System.IO.File.Exists(templateRepositoryFilename))
System.IO.File.Delete(templateRepositoryFilename); System.IO.File.Delete(templateRepositoryFilename);
@@ -214,7 +214,7 @@ namespace Disco.BI.Extensions
dt.FilterExpressionInvalidateCache(); dt.FilterExpressionInvalidateCache();
// Delete Document Template from Repository // Delete Document Template from Repository
Context.DocumentTemplates.Remove(dt); Database.DocumentTemplates.Remove(dt);
} }
} }
} }
+73 -29
View File
@@ -6,6 +6,8 @@ using Disco.Models.BI.Config;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Services.Plugins; using Disco.Services.Plugins;
using Disco.Services.Plugins.Features.WarrantyProvider; using Disco.Services.Plugins.Features.WarrantyProvider;
using Disco.Services.Users;
using Disco.Services.Authorization;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
@@ -15,6 +17,9 @@ namespace Disco.BI.Extensions
#region Device Held #region Device Held
public static bool CanDeviceHeld(this Job j) public static bool CanDeviceHeld(this Job j)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Job.Properties.DeviceHeld))
return false;
return (!j.ClosedDate.HasValue) && (j.DeviceSerialNumber != null) && return (!j.ClosedDate.HasValue) && (j.DeviceSerialNumber != null) &&
(!j.DeviceHeld.HasValue || j.DeviceReturnedDate.HasValue); (!j.DeviceHeld.HasValue || j.DeviceReturnedDate.HasValue);
} }
@@ -35,6 +40,9 @@ namespace Disco.BI.Extensions
#region Device Ready for Return #region Device Ready for Return
public static bool CanDeviceReadyForReturn(this Job j) public static bool CanDeviceReadyForReturn(this Job j)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Job.Properties.DeviceReadyForReturn))
return false;
return (!j.ClosedDate.HasValue) && j.DeviceHeld.HasValue && return (!j.ClosedDate.HasValue) && j.DeviceHeld.HasValue &&
!j.DeviceReadyForReturn.HasValue && !j.DeviceReturnedDate.HasValue; !j.DeviceReadyForReturn.HasValue && !j.DeviceReturnedDate.HasValue;
} }
@@ -51,6 +59,9 @@ namespace Disco.BI.Extensions
#region Device Returned #region Device Returned
public static bool CanDeviceReturned(this Job j) public static bool CanDeviceReturned(this Job j)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Job.Properties.DeviceReturned))
return false;
return (!j.ClosedDate.HasValue) && j.DeviceHeld.HasValue && return (!j.ClosedDate.HasValue) && j.DeviceHeld.HasValue &&
!j.DeviceReturnedDate.HasValue; !j.DeviceReturnedDate.HasValue;
} }
@@ -67,9 +78,12 @@ namespace Disco.BI.Extensions
#region Waiting For User Action #region Waiting For User Action
public static bool CanWaitingForUserAction(this Job j) public static bool CanWaitingForUserAction(this Job j)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Job.Properties.WaitingForUserAction))
return false;
return !j.ClosedDate.HasValue && (j.UserId != null) && !j.WaitingForUserAction.HasValue; return !j.ClosedDate.HasValue && (j.UserId != null) && !j.WaitingForUserAction.HasValue;
} }
public static void OnWaitingForUserAction(this Job j, DiscoDataContext dbContext, User Technician, string Reason) public static void OnWaitingForUserAction(this Job j, DiscoDataContext Database, User Technician, string Reason)
{ {
if (!j.CanWaitingForUserAction()) if (!j.CanWaitingForUserAction())
throw new InvalidOperationException("Waiting for User Action was Denied"); throw new InvalidOperationException("Waiting for User Action was Denied");
@@ -84,16 +98,19 @@ namespace Disco.BI.Extensions
Timestamp = DateTime.Now, Timestamp = DateTime.Now,
Comments = string.Format("Waiting on User Action{0}Reason: {1}", Environment.NewLine, Reason) Comments = string.Format("Waiting on User Action{0}Reason: {1}", Environment.NewLine, Reason)
}; };
dbContext.JobLogs.Add(jobLog); Database.JobLogs.Add(jobLog);
} }
#endregion #endregion
#region Not Waiting For User Action #region Not Waiting For User Action
public static bool CanNotWaitingForUserAction(this Job j) public static bool CanNotWaitingForUserAction(this Job j)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Job.Properties.NotWaitingForUserAction))
return false;
return j.WaitingForUserAction.HasValue; return j.WaitingForUserAction.HasValue;
} }
public static void OnNotWaitingForUserAction(this Job j, DiscoDataContext dbContext, User Technician, string Resolution) public static void OnNotWaitingForUserAction(this Job j, DiscoDataContext Database, User Technician, string Resolution)
{ {
if (!j.CanNotWaitingForUserAction()) if (!j.CanNotWaitingForUserAction())
throw new InvalidOperationException("Not Waiting for User Action was Denied"); throw new InvalidOperationException("Not Waiting for User Action was Denied");
@@ -108,31 +125,34 @@ namespace Disco.BI.Extensions
Timestamp = DateTime.Now, Timestamp = DateTime.Now,
Comments = string.Format("User Action Resolved{0}Resolution: {1}", Environment.NewLine, Resolution) Comments = string.Format("User Action Resolved{0}Resolution: {1}", Environment.NewLine, Resolution)
}; };
dbContext.JobLogs.Add(jobLog); Database.JobLogs.Add(jobLog);
} }
#endregion #endregion
#region Log Warranty #region Log Warranty
public static bool CanLogWarranty(this Job j) public static bool CanLogWarranty(this Job j)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.LogWarranty))
return false;
return !j.ClosedDate.HasValue && return !j.ClosedDate.HasValue &&
(j.DeviceSerialNumber != null) && (j.DeviceSerialNumber != null) &&
j.JobTypeId == JobType.JobTypeIds.HWar && j.JobTypeId == JobType.JobTypeIds.HWar &&
string.IsNullOrEmpty(j.JobMetaWarranty.ExternalReference); string.IsNullOrEmpty(j.JobMetaWarranty.ExternalReference);
} }
public static void OnLogWarranty(this Job j, DiscoDataContext dbContext, string FaultDescription, PluginFeatureManifest WarrantyProviderDefinition, OrganisationAddress Address, User TechUser, Dictionary<string, string> WarrantyProviderProperties) public static void OnLogWarranty(this Job j, DiscoDataContext Database, string FaultDescription, PluginFeatureManifest WarrantyProviderDefinition, OrganisationAddress Address, User TechUser, Dictionary<string, string> WarrantyProviderProperties)
{ {
if (!j.CanLogWarranty()) if (!j.CanLogWarranty())
throw new InvalidOperationException("Log Warranty was Denied"); throw new InvalidOperationException("Log Warranty was Denied");
if (string.IsNullOrWhiteSpace(FaultDescription)) if (string.IsNullOrWhiteSpace(FaultDescription))
FaultDescription = j.GenerateFaultDescriptionFooter(dbContext, WarrantyProviderDefinition); FaultDescription = j.GenerateFaultDescriptionFooter(Database, WarrantyProviderDefinition);
else else
FaultDescription = string.Concat(FaultDescription, Environment.NewLine, Environment.NewLine, j.GenerateFaultDescriptionFooter(dbContext, WarrantyProviderDefinition)); FaultDescription = string.Concat(FaultDescription, Environment.NewLine, Environment.NewLine, j.GenerateFaultDescriptionFooter(Database, WarrantyProviderDefinition));
using (WarrantyProviderFeature WarrantyProvider = WarrantyProviderDefinition.CreateInstance<WarrantyProviderFeature>()) using (WarrantyProviderFeature WarrantyProvider = WarrantyProviderDefinition.CreateInstance<WarrantyProviderFeature>())
{ {
string providerRef = WarrantyProvider.SubmitJob(dbContext, j, Address, TechUser, FaultDescription, WarrantyProviderProperties); string providerRef = WarrantyProvider.SubmitJob(Database, j, Address, TechUser, FaultDescription, WarrantyProviderProperties);
j.JobMetaWarranty.ExternalLoggedDate = DateTime.Now; j.JobMetaWarranty.ExternalLoggedDate = DateTime.Now;
j.JobMetaWarranty.ExternalName = WarrantyProvider.WarrantyProviderId; j.JobMetaWarranty.ExternalName = WarrantyProvider.WarrantyProviderId;
@@ -150,7 +170,7 @@ namespace Disco.BI.Extensions
Timestamp = DateTime.Now, 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) 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)
}; };
dbContext.JobLogs.Add(jobLog); Database.JobLogs.Add(jobLog);
} }
} }
#endregion #endregion
@@ -158,32 +178,35 @@ namespace Disco.BI.Extensions
#region Convert HWar to HNWar #region Convert HWar to HNWar
public static bool CanConvertHWarToHNWar(this Job j) public static bool CanConvertHWarToHNWar(this Job j)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.ConvertHWarToHNWar))
return false;
return !j.ClosedDate.HasValue && (j.DeviceSerialNumber != null) && return !j.ClosedDate.HasValue && (j.DeviceSerialNumber != null) &&
j.JobTypeId == JobType.JobTypeIds.HWar && string.IsNullOrEmpty(j.JobMetaWarranty.ExternalReference); j.JobTypeId == JobType.JobTypeIds.HWar && string.IsNullOrEmpty(j.JobMetaWarranty.ExternalReference);
} }
public static void OnConvertHWarToHNWar(this Job j, DiscoDataContext dbContext) public static void OnConvertHWarToHNWar(this Job j, DiscoDataContext Database)
{ {
if (!j.CanConvertHWarToHNWar()) if (!j.CanConvertHWarToHNWar())
throw new InvalidOperationException("Convert HWar to HNWar was Denied"); throw new InvalidOperationException("Convert HWar to HNWar was Denied");
var techUser = UserBI.UserCache.CurrentUser; var techUser = UserService.CurrentUser;
// Remove JobMetaWarranty // Remove JobMetaWarranty
if (j.JobMetaWarranty != null) if (j.JobMetaWarranty != null)
dbContext.JobMetaWarranties.Remove(j.JobMetaWarranty); Database.JobMetaWarranties.Remove(j.JobMetaWarranty);
// Add JobMetaNonWarranty // Add JobMetaNonWarranty
var metaHNWar = new JobMetaNonWarranty() { Job = j }; var metaHNWar = new JobMetaNonWarranty() { Job = j };
dbContext.JobMetaNonWarranties.Add(metaHNWar); Database.JobMetaNonWarranties.Add(metaHNWar);
// Swap Job Sub Types // Swap Job Sub Types
List<string> jobSubTypes = j.JobSubTypes.Select(jst => jst.Id).ToList(); List<string> jobSubTypes = j.JobSubTypes.Select(jst => jst.Id).ToList();
j.JobSubTypes.Clear(); j.JobSubTypes.Clear();
foreach (var jst in dbContext.JobSubTypes.Where(i => i.JobTypeId == JobType.JobTypeIds.HNWar && jobSubTypes.Contains(i.Id))) foreach (var jst in Database.JobSubTypes.Where(i => i.JobTypeId == JobType.JobTypeIds.HNWar && jobSubTypes.Contains(i.Id)))
j.JobSubTypes.Add(jst); j.JobSubTypes.Add(jst);
// Add Components // Add Components
var components = dbContext.DeviceComponents.Include("JobSubTypes").Where(c => !c.DeviceModelId.HasValue || c.DeviceModelId == j.Device.DeviceModelId); var components = Database.DeviceComponents.Include("JobSubTypes").Where(c => !c.DeviceModelId.HasValue || c.DeviceModelId == j.Device.DeviceModelId);
var jobComponents = new List<DeviceComponent>(); var jobComponents = new List<DeviceComponent>();
foreach (var component in components) foreach (var component in components)
{ {
@@ -210,7 +233,7 @@ namespace Disco.BI.Extensions
} }
foreach (var component in jobComponents) foreach (var component in jobComponents)
{ {
dbContext.JobComponents.Add(new JobComponent() Database.JobComponents.Add(new JobComponent()
{ {
Job = j, Job = j,
TechUserId = techUser.Id, TechUserId = techUser.Id,
@@ -225,9 +248,9 @@ namespace Disco.BI.Extensions
JobId = j.Id, JobId = j.Id,
TechUserId = techUser.Id, TechUserId = techUser.Id,
Timestamp = DateTime.Now, Timestamp = DateTime.Now,
Comments = string.Format("Job Type Converted{0}From: {1}{0}To: {2}", Environment.NewLine, dbContext.JobTypes.Find(JobType.JobTypeIds.HWar), dbContext.JobTypes.Find(JobType.JobTypeIds.HNWar)) 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))
}; };
dbContext.JobLogs.Add(jobLog); Database.JobLogs.Add(jobLog);
j.JobTypeId = JobType.JobTypeIds.HNWar; j.JobTypeId = JobType.JobTypeIds.HNWar;
} }
@@ -252,6 +275,9 @@ namespace Disco.BI.Extensions
#region Insurance Claim Form Sent #region Insurance Claim Form Sent
public static bool CanInsuranceClaimFormSent(this Job j) public static bool CanInsuranceClaimFormSent(this Job j)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Job.Properties.NonWarrantyProperties.InsuranceClaimFormSent))
return false;
return (j.JobTypeId == JobType.JobTypeIds.HNWar) && return (j.JobTypeId == JobType.JobTypeIds.HNWar) &&
j.JobMetaNonWarranty.IsInsuranceClaim && j.JobMetaNonWarranty.IsInsuranceClaim &&
!j.JobMetaInsurance.ClaimFormSentDate.HasValue; !j.JobMetaInsurance.ClaimFormSentDate.HasValue;
@@ -261,7 +287,7 @@ namespace Disco.BI.Extensions
if (!j.CanInsuranceClaimFormSent()) if (!j.CanInsuranceClaimFormSent())
throw new InvalidOperationException("Insurance Claim Form Sent was Denied"); throw new InvalidOperationException("Insurance Claim Form Sent was Denied");
var techUser = UserBI.UserCache.CurrentUser; var techUser = UserService.CurrentUser;
j.JobMetaInsurance.ClaimFormSentDate = DateTime.Now; j.JobMetaInsurance.ClaimFormSentDate = DateTime.Now;
j.JobMetaInsurance.ClaimFormSentUserId = techUser.Id; j.JobMetaInsurance.ClaimFormSentUserId = techUser.Id;
@@ -271,6 +297,9 @@ namespace Disco.BI.Extensions
#region Log Repair #region Log Repair
public static bool CanLogRepair(this Job j) public static bool CanLogRepair(this Job j)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.LogRepair))
return false;
return (j.JobTypeId == JobType.JobTypeIds.HNWar) && return (j.JobTypeId == JobType.JobTypeIds.HNWar) &&
(j.DeviceSerialNumber != null) && (j.DeviceSerialNumber != null) &&
!j.JobMetaNonWarranty.RepairerLoggedDate.HasValue && !j.JobMetaNonWarranty.RepairerLoggedDate.HasValue &&
@@ -292,6 +321,9 @@ namespace Disco.BI.Extensions
#region Repair Complete #region Repair Complete
public static bool CanRepairComplete(this Job j) public static bool CanRepairComplete(this Job j)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Job.Properties.NonWarrantyProperties.RepairerCompletedDate))
return false;
return (j.JobTypeId == JobType.JobTypeIds.HNWar) && return (j.JobTypeId == JobType.JobTypeIds.HNWar) &&
j.JobMetaNonWarranty.RepairerLoggedDate.HasValue && j.JobMetaNonWarranty.RepairerLoggedDate.HasValue &&
!j.JobMetaNonWarranty.RepairerCompletedDate.HasValue; !j.JobMetaNonWarranty.RepairerCompletedDate.HasValue;
@@ -308,6 +340,9 @@ namespace Disco.BI.Extensions
#region Close #region Close
public static bool CanClose(this Job j) public static bool CanClose(this Job j)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.Close))
return false;
if (j.ClosedDate.HasValue) if (j.ClosedDate.HasValue)
return false; // Job already Closed return false; // Job already Closed
@@ -352,6 +387,9 @@ namespace Disco.BI.Extensions
#region Force Close #region Force Close
public static bool CanForceClose(this Job j) public static bool CanForceClose(this Job j)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.ForceClose))
return false;
var canCloseNormally = j.CanClose(); var canCloseNormally = j.CanClose();
if (canCloseNormally) if (canCloseNormally)
@@ -389,7 +427,7 @@ namespace Disco.BI.Extensions
return false; return false;
} }
public static void OnForceClose(this Job j, DiscoDataContext dbContext, User Technician, string Reason) public static void OnForceClose(this Job j, DiscoDataContext Database, User Technician, string Reason)
{ {
if (!j.CanForceClose()) if (!j.CanForceClose())
throw new InvalidOperationException("Force Close was Denied"); throw new InvalidOperationException("Force Close was Denied");
@@ -402,7 +440,7 @@ namespace Disco.BI.Extensions
Timestamp = DateTime.Now, Timestamp = DateTime.Now,
Comments = string.Format("Job Forcibly Closed{0}Reason: {1}", Environment.NewLine, Reason) Comments = string.Format("Job Forcibly Closed{0}Reason: {1}", Environment.NewLine, Reason)
}; };
dbContext.JobLogs.Add(jobLog); Database.JobLogs.Add(jobLog);
j.ClosedDate = DateTime.Now; j.ClosedDate = DateTime.Now;
j.ClosedTechUserId = Technician.Id; j.ClosedTechUserId = Technician.Id;
@@ -412,6 +450,9 @@ namespace Disco.BI.Extensions
#region Reopen #region Reopen
public static bool CanReopen(this Job j) public static bool CanReopen(this Job j)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.Reopen))
return false;
return j.ClosedDate.HasValue; return j.ClosedDate.HasValue;
} }
public static void OnReopen(this Job j) public static void OnReopen(this Job j)
@@ -427,47 +468,50 @@ namespace Disco.BI.Extensions
#region Delete #region Delete
public static bool CanDelete(this Job j) public static bool CanDelete(this Job j)
{ {
if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.Delete))
return false;
return j.ClosedDate.HasValue; return j.ClosedDate.HasValue;
} }
public static void OnDelete(this Job j, DiscoDataContext dbContext) public static void OnDelete(this Job j, DiscoDataContext Database)
{ {
// Job Sub Types // Job Sub Types
j.JobSubTypes.Clear(); j.JobSubTypes.Clear();
// Job Attachments // Job Attachments
foreach (var ja in j.JobAttachments.ToArray()) foreach (var ja in j.JobAttachments.ToArray())
ja.OnDelete(dbContext); ja.OnDelete(Database);
j.JobAttachments.Clear(); j.JobAttachments.Clear();
// Job Components // Job Components
foreach (var jc in j.JobComponents.ToArray()) foreach (var jc in j.JobComponents.ToArray())
dbContext.JobComponents.Remove(jc); Database.JobComponents.Remove(jc);
j.JobComponents.Clear(); j.JobComponents.Clear();
// Job Logs // Job Logs
foreach (var jl in j.JobLogs.ToArray()) foreach (var jl in j.JobLogs.ToArray())
dbContext.JobLogs.Remove(jl); Database.JobLogs.Remove(jl);
j.JobLogs.Clear(); j.JobLogs.Clear();
// Job Meta // Job Meta
if (j.JobMetaInsurance != null) if (j.JobMetaInsurance != null)
{ {
dbContext.JobMetaInsurances.Remove(j.JobMetaInsurance); Database.JobMetaInsurances.Remove(j.JobMetaInsurance);
j.JobMetaInsurance = null; j.JobMetaInsurance = null;
} }
if (j.JobMetaNonWarranty != null) if (j.JobMetaNonWarranty != null)
{ {
dbContext.JobMetaNonWarranties.Remove(j.JobMetaNonWarranty); Database.JobMetaNonWarranties.Remove(j.JobMetaNonWarranty);
j.JobMetaNonWarranty = null; j.JobMetaNonWarranty = null;
} }
if (j.JobMetaWarranty != null) if (j.JobMetaWarranty != null)
{ {
dbContext.JobMetaWarranties.Remove(j.JobMetaWarranty); Database.JobMetaWarranties.Remove(j.JobMetaWarranty);
j.JobMetaWarranty = null; j.JobMetaWarranty = null;
} }
// Job // Job
dbContext.Jobs.Remove(j); Database.Jobs.Remove(j);
} }
#endregion #endregion
} }
+15 -15
View File
@@ -13,7 +13,7 @@ namespace Disco.BI.Extensions
{ {
public static class JobExtensions public static class JobExtensions
{ {
public static JobAttachment CreateAttachment(this Job Job, DiscoDataContext dbContext, User CreatorUser, string Filename, string MimeType, string Comments, Stream Content, DocumentTemplate DocumentTemplate = null, byte[] PdfThumbnail = null) public static JobAttachment CreateAttachment(this Job Job, DiscoDataContext Database, User CreatorUser, string Filename, string MimeType, string Comments, Stream Content, DocumentTemplate DocumentTemplate = null, byte[] PdfThumbnail = null)
{ {
if (string.IsNullOrEmpty(MimeType) || MimeType.Equals("unknown/unknown", StringComparison.InvariantCultureIgnoreCase)) if (string.IsNullOrEmpty(MimeType) || MimeType.Equals("unknown/unknown", StringComparison.InvariantCultureIgnoreCase))
MimeType = Interop.MimeTypes.ResolveMimeType(Filename); MimeType = Interop.MimeTypes.ResolveMimeType(Filename);
@@ -31,15 +31,15 @@ namespace Disco.BI.Extensions
if (DocumentTemplate != null) if (DocumentTemplate != null)
ja.DocumentTemplateId = DocumentTemplate.Id; ja.DocumentTemplateId = DocumentTemplate.Id;
dbContext.JobAttachments.Add(ja); Database.JobAttachments.Add(ja);
dbContext.SaveChanges(); Database.SaveChanges();
ja.SaveAttachment(dbContext, Content); ja.SaveAttachment(Database, Content);
Content.Position = 0; Content.Position = 0;
if (PdfThumbnail == null) if (PdfThumbnail == null)
ja.GenerateThumbnail(dbContext, Content); ja.GenerateThumbnail(Database, Content);
else else
ja.SaveThumbnailAttachment(dbContext, PdfThumbnail); ja.SaveThumbnailAttachment(Database, PdfThumbnail);
return ja; return ja;
} }
@@ -146,9 +146,9 @@ namespace Disco.BI.Extensions
return Job.JobStatusIds.Open; return Job.JobStatusIds.Open;
} }
public static List<DocumentTemplate> AvailableDocumentTemplates(this Job j, DiscoDataContext dbContext, User User, DateTime TimeStamp) public static List<DocumentTemplate> AvailableDocumentTemplates(this Job j, DiscoDataContext Database, User User, DateTime TimeStamp)
{ {
var dts = dbContext.DocumentTemplates.Include("JobSubTypes") var dts = Database.DocumentTemplates.Include("JobSubTypes")
.Where(dt => dt.Scope == DocumentTemplate.DocumentTemplateScopes.Job) .Where(dt => dt.Scope == DocumentTemplate.DocumentTemplateScopes.Job)
.ToList(); .ToList();
@@ -171,7 +171,7 @@ namespace Disco.BI.Extensions
} }
// Evaluate Filters // Evaluate Filters
dts = dts.Where(dt => dt.FilterExpressionMatches(j, dbContext, User, TimeStamp, DocumentState.DefaultState())).ToList(); dts = dts.Where(dt => dt.FilterExpressionMatches(j, Database, User, TimeStamp, DocumentState.DefaultState())).ToList();
return dts; return dts;
} }
@@ -188,7 +188,7 @@ namespace Disco.BI.Extensions
return d; return d;
} }
public static string GenerateFaultDescription(this Job j, DiscoDataContext dbContext) public static string GenerateFaultDescription(this Job j, DiscoDataContext Database)
{ {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
@@ -199,14 +199,14 @@ namespace Disco.BI.Extensions
return sb.ToString(); return sb.ToString();
} }
public static string GenerateFaultDescriptionFooter(this Job j, DiscoDataContext dbContext, PluginFeatureManifest WarrantyProviderDefinition) public static string GenerateFaultDescriptionFooter(this Job j, DiscoDataContext Database, PluginFeatureManifest WarrantyProviderDefinition)
{ {
var versionDisco = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; var versionDisco = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
return string.Format("Automation by Disco v{0}.{1}.{2:0000}.{3:0000} (Provider: {4} v{5})", return string.Format("Automation by Disco v{0}.{1}.{2:0000}.{3:0000} (Provider: {4} v{5})",
versionDisco.Major, versionDisco.Minor, versionDisco.Build, versionDisco.Revision, WarrantyProviderDefinition.Id, WarrantyProviderDefinition.PluginManifest.Version.ToString(4)); versionDisco.Major, versionDisco.Minor, versionDisco.Build, versionDisco.Revision, WarrantyProviderDefinition.Id, WarrantyProviderDefinition.PluginManifest.Version.ToString(4));
} }
public static void UpdateSubTypes(this Job j, DiscoDataContext dbContext, List<JobSubType> SubTypes, bool AddComponents, User TechUser) public static void UpdateSubTypes(this Job j, DiscoDataContext Database, List<JobSubType> SubTypes, bool AddComponents, User TechUser)
{ {
if (SubTypes == null || SubTypes.Count == 0) if (SubTypes == null || SubTypes.Count == 0)
throw new ArgumentException("The Job must contain at least one Sub Type"); throw new ArgumentException("The Job must contain at least one Sub Type");
@@ -246,7 +246,7 @@ namespace Disco.BI.Extensions
foreach (var t in addedSubTypes) foreach (var t in addedSubTypes)
logBuilder.Append("- ").AppendLine(t.ToString()); logBuilder.Append("- ").AppendLine(t.ToString());
} }
dbContext.JobLogs.Add(new JobLog() Database.JobLogs.Add(new JobLog()
{ {
JobId = j.Id, JobId = j.Id,
TechUserId = TechUser.Id, TechUserId = TechUser.Id,
@@ -258,7 +258,7 @@ namespace Disco.BI.Extensions
// Add Components // Add Components
if (AddComponents && addedSubTypes.Count > 0 && j.DeviceSerialNumber != null) if (AddComponents && addedSubTypes.Count > 0 && j.DeviceSerialNumber != null)
{ {
var components = dbContext.DeviceComponents.Include("JobSubTypes").Where(c => !c.DeviceModelId.HasValue || c.DeviceModelId == j.Device.DeviceModelId); var components = Database.DeviceComponents.Include("JobSubTypes").Where(c => !c.DeviceModelId.HasValue || c.DeviceModelId == j.Device.DeviceModelId);
var addedComponents = new List<DeviceComponent>(); var addedComponents = new List<DeviceComponent>();
foreach (var c in components) foreach (var c in components)
{ {
@@ -280,7 +280,7 @@ namespace Disco.BI.Extensions
{ {
if (!j.JobComponents.Any(jc => jc.Description.Equals(c.Description, StringComparison.InvariantCultureIgnoreCase))) if (!j.JobComponents.Any(jc => jc.Description.Equals(c.Description, StringComparison.InvariantCultureIgnoreCase)))
{ // Job Component with matching Description doesn't exist. { // Job Component with matching Description doesn't exist.
dbContext.JobComponents.Add(new JobComponent() Database.JobComponents.Add(new JobComponent()
{ {
Job = j, Job = j,
TechUserId = TechUser.Id, TechUserId = TechUser.Id,
+83 -5
View File
@@ -5,16 +5,94 @@ using System.Text;
using Disco.Models.BI.Job; using Disco.Models.BI.Job;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Services.Users;
using Disco.Services.Authorization;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
public static class JobTableExtensions public static class JobTableExtensions
{ {
private static List<string> FilterAllowedTypes(AuthorizationToken Authorization)
{
if (!Authorization.HasAll(Claims.Job.Types.ShowHMisc, Claims.Job.Types.ShowHNWar, Claims.Job.Types.ShowHWar, Claims.Job.Types.ShowSApp, Claims.Job.Types.ShowSImg, Claims.Job.Types.ShowSOS, Claims.Job.Types.ShowUMgmt))
{
// Must Filter
List<string> allowedTypes = new List<string>(6);
if (Authorization.Has(Claims.Job.Types.ShowHMisc))
allowedTypes.Add(JobType.JobTypeIds.HMisc);
if (Authorization.Has(Claims.Job.Types.ShowHNWar))
allowedTypes.Add(JobType.JobTypeIds.HNWar);
if (Authorization.Has(Claims.Job.Types.ShowHWar))
allowedTypes.Add(JobType.JobTypeIds.HWar);
if (Authorization.Has(Claims.Job.Types.ShowSApp))
allowedTypes.Add(JobType.JobTypeIds.SApp);
if (Authorization.Has(Claims.Job.Types.ShowSImg))
allowedTypes.Add(JobType.JobTypeIds.SImg);
if (Authorization.Has(Claims.Job.Types.ShowSOS))
allowedTypes.Add(JobType.JobTypeIds.SOS);
if (Authorization.Has(Claims.Job.Types.ShowUMgmt))
allowedTypes.Add(JobType.JobTypeIds.UMgmt);
public static List<JobTableModel.JobTableItemModel> DetermineItems(this JobTableModel model, DiscoDataContext dbContext, IQueryable<Job> Jobs) return allowedTypes;
}
return null;
}
public static IQueryable<Job> FilterPermissions(this JobTableModel model, IQueryable<Job> Jobs, AuthorizationToken Authorization)
{
var allowedTypes = FilterAllowedTypes(Authorization);
if (allowedTypes != null)
{
return Jobs.Where(j => allowedTypes.Contains(j.JobTypeId));
}
return Jobs;
}
public static List<JobTableModel.JobTableItemModel> PermissionsFiltered(this List<JobTableModel.JobTableItemModel> Items, AuthorizationToken Authorization)
{
if (Items != null && Items.Count > 0)
{
var allowedTypes = FilterAllowedTypes(Authorization);
if (allowedTypes != null)
{
return Items.Where(j => allowedTypes.Contains(j.TypeId)).ToList();
}
}
return Items;
}
public static List<JobTableModel.JobTableItemModel> DetermineItems(this JobTableModel model, DiscoDataContext Database, IQueryable<Job> Jobs)
{ {
List<JobTableModel.JobTableItemModel> items; List<JobTableModel.JobTableItemModel> items;
// Permissions
var auth = UserService.CurrentAuthorization;
if (!auth.HasAll(Claims.Job.Types.ShowHMisc, Claims.Job.Types.ShowHNWar, Claims.Job.Types.ShowHWar, Claims.Job.Types.ShowSApp, Claims.Job.Types.ShowSImg, Claims.Job.Types.ShowSOS, Claims.Job.Types.ShowUMgmt))
{
// Must Filter
List<string> allowedTypes = new List<string>(6);
if (auth.Has(Claims.Job.Types.ShowHMisc))
allowedTypes.Add(JobType.JobTypeIds.HMisc);
if (auth.Has(Claims.Job.Types.ShowHNWar))
allowedTypes.Add(JobType.JobTypeIds.HNWar);
if (auth.Has(Claims.Job.Types.ShowHWar))
allowedTypes.Add(JobType.JobTypeIds.HWar);
if (auth.Has(Claims.Job.Types.ShowSApp))
allowedTypes.Add(JobType.JobTypeIds.SApp);
if (auth.Has(Claims.Job.Types.ShowSImg))
allowedTypes.Add(JobType.JobTypeIds.SImg);
if (auth.Has(Claims.Job.Types.ShowSOS))
allowedTypes.Add(JobType.JobTypeIds.SOS);
if (auth.Has(Claims.Job.Types.ShowUMgmt))
allowedTypes.Add(JobType.JobTypeIds.UMgmt);
Jobs = Jobs.Where(j => allowedTypes.Contains(j.JobTypeId));
}
if (model.ShowStatus) if (model.ShowStatus)
{ {
@@ -86,18 +164,18 @@ namespace Disco.BI.Extensions
} }
if (!model.ShowDeviceAddress.HasValue) if (!model.ShowDeviceAddress.HasValue)
model.ShowDeviceAddress = dbContext.DiscoConfiguration.MultiSiteMode; model.ShowDeviceAddress = Database.DiscoConfiguration.MultiSiteMode;
foreach (var j in items) foreach (var j in items)
if (j.DeviceAddressId.HasValue) if (j.DeviceAddressId.HasValue)
j.DeviceAddress = dbContext.DiscoConfiguration.OrganisationAddresses.GetAddress(j.DeviceAddressId.Value).Name; j.DeviceAddress = Database.DiscoConfiguration.OrganisationAddresses.GetAddress(j.DeviceAddressId.Value).Name;
return items; return items;
} }
public static void Fill(this JobTableModel model, DiscoDataContext dbContext, IQueryable<Job> Jobs) public static void Fill(this JobTableModel model, DiscoDataContext Database, IQueryable<Job> Jobs)
{ {
model.Items = model.DetermineItems(dbContext, Jobs); model.Items = model.DetermineItems(Database, Jobs);
} }
} }
} }
+9 -9
View File
@@ -12,7 +12,7 @@ namespace Disco.BI.Extensions
{ {
public static class UserExtensions public static class UserExtensions
{ {
public static UserAttachment CreateAttachment(this User User, DiscoDataContext dbContext, User CreatorUser, string Filename, string MimeType, string Comments, Stream Content, DocumentTemplate DocumentTemplate = null, byte[] PdfThumbnail = null) public static UserAttachment CreateAttachment(this User User, DiscoDataContext Database, User CreatorUser, string Filename, string MimeType, string Comments, Stream Content, DocumentTemplate DocumentTemplate = null, byte[] PdfThumbnail = null)
{ {
if (string.IsNullOrEmpty(MimeType) || MimeType.Equals("unknown/unknown", StringComparison.InvariantCultureIgnoreCase)) if (string.IsNullOrEmpty(MimeType) || MimeType.Equals("unknown/unknown", StringComparison.InvariantCultureIgnoreCase))
MimeType = Interop.MimeTypes.ResolveMimeType(Filename); MimeType = Interop.MimeTypes.ResolveMimeType(Filename);
@@ -30,25 +30,25 @@ namespace Disco.BI.Extensions
if (DocumentTemplate != null) if (DocumentTemplate != null)
ua.DocumentTemplateId = DocumentTemplate.Id; ua.DocumentTemplateId = DocumentTemplate.Id;
dbContext.UserAttachments.Add(ua); Database.UserAttachments.Add(ua);
dbContext.SaveChanges(); Database.SaveChanges();
ua.SaveAttachment(dbContext, Content); ua.SaveAttachment(Database, Content);
Content.Position = 0; Content.Position = 0;
if (PdfThumbnail == null) if (PdfThumbnail == null)
ua.GenerateThumbnail(dbContext, Content); ua.GenerateThumbnail(Database, Content);
else else
ua.SaveThumbnailAttachment(dbContext, PdfThumbnail); ua.SaveThumbnailAttachment(Database, PdfThumbnail);
return ua; return ua;
} }
public static List<DocumentTemplate> AvailableDocumentTemplates(this User u, DiscoDataContext dbContext, User User, DateTime TimeStamp) public static List<DocumentTemplate> AvailableDocumentTemplates(this User u, DiscoDataContext Database, User User, DateTime TimeStamp)
{ {
var dts = dbContext.DocumentTemplates.Include("JobSubTypes") var dts = Database.DocumentTemplates.Include("JobSubTypes")
.Where(dt => dt.Scope == DocumentTemplate.DocumentTemplateScopes.User) .Where(dt => dt.Scope == DocumentTemplate.DocumentTemplateScopes.User)
.ToArray() .ToArray()
.Where(dt => dt.FilterExpressionMatches(u, dbContext, User, TimeStamp, DocumentState.DefaultState())).ToList(); .Where(dt => dt.FilterExpressionMatches(u, Database, User, TimeStamp, DocumentState.DefaultState())).ToList();
return dts; return dts;
} }
@@ -12,6 +12,17 @@ namespace Disco.BI.Interop.ActiveDirectory
{ {
public static class ActiveDirectory public static class ActiveDirectory
{ {
#region Machine Accounts
private static readonly string[] MachineLoadProperties = {
"name",
"distinguishedName",
"sAMAccountName",
"objectSid",
"dNSHostName",
"netbootGUID",
"isCriticalSystemObject"
};
public static ActiveDirectoryMachineAccount GetMachineAccount(string ComputerName, System.Guid? UUIDNetbootGUID = null, System.Guid? MacAddressNetbootGUID = null, params string[] AdditionalProperties) public static ActiveDirectoryMachineAccount GetMachineAccount(string ComputerName, System.Guid? UUIDNetbootGUID = null, System.Guid? MacAddressNetbootGUID = null, params string[] AdditionalProperties)
{ {
if (string.IsNullOrWhiteSpace(ComputerName)) if (string.IsNullOrWhiteSpace(ComputerName))
@@ -26,36 +37,36 @@ namespace Disco.BI.Interop.ActiveDirectory
using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultLdapRoot) using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultLdapRoot)
{ {
var loadProperties = new List<string> { "name", "distinguishedName", "sAMAccountName", "objectSid", "dNSHostName", "netbootGUID", "isCriticalSystemObject" }; var loadProperties = AdditionalProperties == null ? MachineLoadProperties : MachineLoadProperties.Concat(AdditionalProperties).ToArray();
loadProperties.AddRange(AdditionalProperties);
using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectClass=computer)(sAMAccountName={0}))", ActiveDirectoryHelpers.EscapeLdapQuery(sAMAccountName)), loadProperties.ToArray(), SearchScope.Subtree)) using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectCategory=computer)(sAMAccountName={0}))", ActiveDirectoryHelpers.EscapeLdapQuery(sAMAccountName)), loadProperties, SearchScope.Subtree))
{ {
SearchResult dResult = dSearcher.FindOne(); SearchResult dResult = dSearcher.FindOne();
if (dResult != null) if (dResult != null)
{ {
return ActiveDirectory.DirectorySearchResultToMachineAccount(dResult, AdditionalProperties); return ActiveDirectory.ActiveDirectoryMachineAccountFromSearchResult(dResult, AdditionalProperties);
} }
} }
if (UUIDNetbootGUID.HasValue) if (UUIDNetbootGUID.HasValue)
{ {
using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectClass=computer)(netbootGUID={0}))", ActiveDirectoryHelpers.FormatGuidForLdapQuery(UUIDNetbootGUID.Value)), loadProperties.ToArray(), SearchScope.Subtree)) using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectCategory=computer)(netbootGUID={0}))", ActiveDirectoryHelpers.FormatGuidForLdapQuery(UUIDNetbootGUID.Value)), loadProperties, SearchScope.Subtree))
{ {
SearchResult dResult = dSearcher.FindOne(); SearchResult dResult = dSearcher.FindOne();
if (dResult != null) if (dResult != null)
{ {
return ActiveDirectory.DirectorySearchResultToMachineAccount(dResult, AdditionalProperties); return ActiveDirectory.ActiveDirectoryMachineAccountFromSearchResult(dResult, AdditionalProperties);
} }
} }
} }
if (MacAddressNetbootGUID.HasValue) if (MacAddressNetbootGUID.HasValue)
{ {
using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectClass=computer)(netbootGUID={0}))", ActiveDirectoryHelpers.FormatGuidForLdapQuery(MacAddressNetbootGUID.Value)), loadProperties.ToArray(), SearchScope.Subtree)) using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectCategory=computer)(netbootGUID={0}))", ActiveDirectoryHelpers.FormatGuidForLdapQuery(MacAddressNetbootGUID.Value)), loadProperties, SearchScope.Subtree))
{ {
SearchResult dResult = dSearcher.FindOne(); SearchResult dResult = dSearcher.FindOne();
if (dResult != null) if (dResult != null)
{ {
return ActiveDirectory.DirectorySearchResultToMachineAccount(dResult, AdditionalProperties); return ActiveDirectory.ActiveDirectoryMachineAccountFromSearchResult(dResult, AdditionalProperties);
} }
} }
} }
@@ -64,7 +75,7 @@ namespace Disco.BI.Interop.ActiveDirectory
return null; return null;
} }
private static ActiveDirectoryMachineAccount DirectorySearchResultToMachineAccount(SearchResult result, params string[] AdditionalProperties) private static ActiveDirectoryMachineAccount ActiveDirectoryMachineAccountFromSearchResult(SearchResult result, params string[] AdditionalProperties)
{ {
string name = result.Properties["name"][0].ToString(); string name = result.Properties["name"][0].ToString();
string sAMAccountName = result.Properties["sAMAccountName"][0].ToString(); string sAMAccountName = result.Properties["sAMAccountName"][0].ToString();
@@ -89,6 +100,7 @@ namespace Disco.BI.Interop.ActiveDirectory
// Additional Properties // Additional Properties
Dictionary<string, object[]> additionalProperties = new Dictionary<string, object[]>(); Dictionary<string, object[]> additionalProperties = new Dictionary<string, object[]>();
if (AdditionalProperties != null)
foreach (string propertyName in AdditionalProperties) foreach (string propertyName in AdditionalProperties)
{ {
var property = result.Properties[propertyName]; var property = result.Properties[propertyName];
@@ -102,8 +114,8 @@ namespace Disco.BI.Interop.ActiveDirectory
{ {
Name = name, Name = name,
DistinguishedName = distinguishedName, DistinguishedName = distinguishedName,
sAMAccountName = sAMAccountName, SamAccountName = sAMAccountName,
ObjectSid = objectSid, SecurityIdentifier = objectSid,
NetbootGUID = netbootGUIDResult, NetbootGUID = netbootGUIDResult,
Path = result.Path, Path = result.Path,
Domain = ActiveDirectoryHelpers.DefaultDomainNetBiosName, Domain = ActiveDirectoryHelpers.DefaultDomainNetBiosName,
@@ -112,132 +124,9 @@ namespace Disco.BI.Interop.ActiveDirectory
LoadedProperties = additionalProperties LoadedProperties = additionalProperties
}; };
} }
private static ActiveDirectoryUserAccount SearchResultToActiveDirectoryUserAccount(SearchResult result, params string[] AdditionalProperties)
{
string name = result.Properties["name"][0].ToString();
string username = result.Properties["sAMAccountName"][0].ToString();
string distinguishedName = result.Properties["distinguishedName"][0].ToString();
byte[] objectSid = (byte[])result.Properties["objectSid"][0];
string objectSidSDDL = ActiveDirectoryHelpers.ConvertBytesToSDDLString(objectSid);
ResultPropertyValueCollection displayNameProp = result.Properties["displayName"]; #endregion
string displayName = username;
if (displayNameProp.Count > 0)
displayName = displayNameProp[0].ToString();
string surname = null;
ResultPropertyValueCollection surnameProp = result.Properties["sn"];
if (surnameProp.Count > 0)
surname = surnameProp[0].ToString();
string givenName = null;
ResultPropertyValueCollection givenNameProp = result.Properties["givenName"];
if (givenNameProp.Count > 0)
givenName = givenNameProp[0].ToString();
string email = null;
ResultPropertyValueCollection emailProp = result.Properties["mail"];
if (emailProp.Count > 0)
email = emailProp[0].ToString();
string phone = null;
ResultPropertyValueCollection phoneProp = result.Properties["telephoneNumber"];
if (phoneProp.Count > 0)
phone = phoneProp[0].ToString();
int primaryGroupID = (int)result.Properties["primaryGroupID"][0];
string primaryGroupSid = ActiveDirectoryHelpers.ConvertBytesToSDDLString(ActiveDirectoryHelpers.BuildPrimaryGroupSid(objectSid, primaryGroupID));
var groupCNs = result.Properties["memberOf"].Cast<string>().ToList();
groupCNs.Add(ActiveDirectoryCachedGroups.GetGroupsCnForSid(primaryGroupSid));
List<string> groups = ActiveDirectoryCachedGroups.GetGroups(groupCNs).Select(g => g.ToLower()).ToList();
//foreach (string groupCN in result.Properties["memberOf"])
//{
// Removed 2012-11-30 G# - Moved to Recursive Cache
//var groupCNlower = groupCN.ToLower();
//if (groupCNlower.StartsWith("cn="))
// groups.Add(groupCNlower.Substring(3, groupCNlower.IndexOf(",") - 3));
// End Removed 2012-11-30 G#
//}
string type = null;
if (groups.Contains("domain admins") || groups.Contains("disco admins"))
{
type = "Admin";
}
else
{
if (groups.Contains("staff"))
{
type = "Staff";
}
else
{
if (groups.Contains("students"))
{
type = "Student";
}
}
}
// Additional Properties
Dictionary<string, object[]> additionalProperties = new Dictionary<string, object[]>();
foreach (string propertyName in AdditionalProperties)
{
var property = result.Properties[propertyName];
var propertyValues = new List<object>();
for (int index = 0; index < property.Count; index++)
propertyValues.Add(property[index]);
additionalProperties.Add(propertyName, propertyValues.ToArray());
}
return new ActiveDirectoryUserAccount
{
Domain = ActiveDirectoryHelpers.DefaultDomainNetBiosName,
Name = name,
Surname = surname,
GivenName = givenName,
Email = email,
Phone = phone,
DistinguishedName = distinguishedName,
sAMAccountName = username,
DisplayName = displayName,
ObjectSid = objectSidSDDL,
Type = type,
Path = result.Path,
LoadedProperties = additionalProperties
};
}
public static ActiveDirectoryUserAccount GetUserAccount(string Username, params string[] AdditionalProperties)
{
if (string.IsNullOrWhiteSpace(Username))
throw new System.ArgumentException("Invalid User Account", "Username");
string sAMAccountName = Username;
if (sAMAccountName.Contains("\\"))
sAMAccountName = sAMAccountName.Substring(checked(sAMAccountName.IndexOf("\\") + 1));
using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultLdapRoot)
{
var loadProperties = new List<string> {
"name",
"distinguishedName",
"sAMAccountName",
"objectSid",
"displayName",
"sn",
"givenName",
"memberOf",
"primaryGroupID",
"mail",
"telephoneNumber"
};
loadProperties.AddRange(AdditionalProperties);
using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectClass=user)(sAMAccountName={0}))", ActiveDirectoryHelpers.EscapeLdapQuery(sAMAccountName)), loadProperties.ToArray(), SearchScope.Subtree))
{
SearchResult dResult = dSearcher.FindOne();
if (dResult != null)
return ActiveDirectory.SearchResultToActiveDirectoryUserAccount(dResult, AdditionalProperties);
else
return null;
}
}
}
public static string OfflineDomainJoinProvision(ref ActiveDirectoryMachineAccount ExistingAccount, string ComputerName, string OrganisationalUnit = null, string EnrolSessionId = null) public static string OfflineDomainJoinProvision(ref ActiveDirectoryMachineAccount ExistingAccount, string ComputerName, string OrganisationalUnit = null, string EnrolSessionId = null)
{ {
if (ExistingAccount != null && ExistingAccount.IsCriticalSystemObject) if (ExistingAccount != null && ExistingAccount.IsCriticalSystemObject)
@@ -323,16 +212,9 @@ namespace Disco.BI.Interop.ActiveDirectory
return DJoinResult; return DJoinResult;
} }
public static List<ActiveDirectoryUserAccount> SearchUsers(string term) #region Users
{
List<ActiveDirectoryUserAccount> users = new List<ActiveDirectoryUserAccount>(); private static readonly string[] UserLoadProperties = {
string defaultQualifiedDomainName = ActiveDirectoryHelpers.DefaultDomainQualifiedName;
string defaultNetBiosDomainName = ActiveDirectoryHelpers.DefaultDomainNetBiosName;
term = ActiveDirectoryHelpers.EscapeLdapQuery(term);
using (DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", defaultQualifiedDomainName)))
{
using (DirectorySearcher searcher = new DirectorySearcher(entry, string.Format("(&(objectClass=User)(objectCategory=Person)(|(sAMAccountName=*{0}*)(displayName=*{0}*)))", term), new string[]
{
"name", "name",
"distinguishedName", "distinguishedName",
"sAMAccountName", "sAMAccountName",
@@ -344,18 +226,127 @@ namespace Disco.BI.Interop.ActiveDirectory
"primaryGroupID", "primaryGroupID",
"mail", "mail",
"telephoneNumber" "telephoneNumber"
}, SearchScope.Subtree)) };
public static List<ActiveDirectoryUserAccount> SearchUsers(string term)
{
List<ActiveDirectoryUserAccount> users = new List<ActiveDirectoryUserAccount>();
string defaultQualifiedDomainName = ActiveDirectoryHelpers.DefaultDomainQualifiedName;
string defaultNetBiosDomainName = ActiveDirectoryHelpers.DefaultDomainNetBiosName;
term = ActiveDirectoryHelpers.EscapeLdapQuery(term);
using (DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", defaultQualifiedDomainName)))
{
using (DirectorySearcher searcher = new DirectorySearcher(entry, string.Format("(&(objectCategory=Person)(objectCategory=Person)(|(sAMAccountName=*{0}*)(displayName=*{0}*)))", term), UserLoadProperties, SearchScope.Subtree))
{ {
searcher.SizeLimit = 30; searcher.SizeLimit = 30;
SearchResultCollection results = searcher.FindAll(); SearchResultCollection results = searcher.FindAll();
foreach (SearchResult result in results) foreach (SearchResult result in results)
{ {
users.Add(ActiveDirectory.SearchResultToActiveDirectoryUserAccount(result)); users.Add(ActiveDirectory.ActiveDirectoryUserAccountFromSearchResult(result));
} }
} }
} }
return users; return users;
} }
private static ActiveDirectoryUserAccount ActiveDirectoryUserAccountFromSearchResult(SearchResult result, params string[] AdditionalProperties)
{
string name = result.Properties["name"][0].ToString();
string username = result.Properties["sAMAccountName"][0].ToString();
string distinguishedName = result.Properties["distinguishedName"][0].ToString();
byte[] objectSid = (byte[])result.Properties["objectSid"][0];
string objectSidSDDL = ActiveDirectoryHelpers.ConvertBytesToSDDLString(objectSid);
ResultPropertyValueCollection displayNameProp = result.Properties["displayName"];
string displayName = username;
if (displayNameProp.Count > 0)
displayName = displayNameProp[0].ToString();
string surname = null;
ResultPropertyValueCollection surnameProp = result.Properties["sn"];
if (surnameProp.Count > 0)
surname = surnameProp[0].ToString();
string givenName = null;
ResultPropertyValueCollection givenNameProp = result.Properties["givenName"];
if (givenNameProp.Count > 0)
givenName = givenNameProp[0].ToString();
string email = null;
ResultPropertyValueCollection emailProp = result.Properties["mail"];
if (emailProp.Count > 0)
email = emailProp[0].ToString();
string phone = null;
ResultPropertyValueCollection phoneProp = result.Properties["telephoneNumber"];
if (phoneProp.Count > 0)
phone = phoneProp[0].ToString();
int primaryGroupID = (int)result.Properties["primaryGroupID"][0];
string primaryGroupSid = ActiveDirectoryHelpers.ConvertBytesToSDDLString(ActiveDirectoryHelpers.BuildPrimaryGroupSid(objectSid, primaryGroupID));
var groupDistinguishedNames = result.Properties["memberOf"].Cast<string>().ToList();
groupDistinguishedNames.Add(ActiveDirectoryCachedGroups.GetGroupsDistinguishedNameForSecurityIdentifier(primaryGroupSid));
List<string> groups = ActiveDirectoryCachedGroups.GetGroups(groupDistinguishedNames).ToList();
//foreach (string groupCN in result.Properties["memberOf"])
//{
// Removed 2012-11-30 G# - Moved to Recursive Cache
//var groupCNlower = groupCN.ToLower();
//if (groupCNlower.StartsWith("cn="))
// groups.Add(groupCNlower.Substring(3, groupCNlower.IndexOf(",") - 3));
// End Removed 2012-11-30 G#
//}
// Additional Properties
Dictionary<string, object[]> additionalProperties = new Dictionary<string, object[]>();
if (AdditionalProperties != null)
foreach (string propertyName in AdditionalProperties)
{
var property = result.Properties[propertyName];
var propertyValues = new List<object>();
for (int index = 0; index < property.Count; index++)
propertyValues.Add(property[index]);
additionalProperties.Add(propertyName, propertyValues.ToArray());
}
return new ActiveDirectoryUserAccount
{
Domain = ActiveDirectoryHelpers.DefaultDomainNetBiosName,
Name = name,
Surname = surname,
GivenName = givenName,
Email = email,
Phone = phone,
DistinguishedName = distinguishedName,
SamAccountName = username,
DisplayName = displayName,
SecurityIdentifier = objectSidSDDL,
Groups = groups,
Path = result.Path,
LoadedProperties = additionalProperties
};
}
public static ActiveDirectoryUserAccount GetUserAccount(string Username, params string[] AdditionalProperties)
{
if (string.IsNullOrWhiteSpace(Username))
throw new System.ArgumentException("Invalid User Account", "Username");
string sAMAccountName = Username;
if (sAMAccountName.Contains("\\"))
sAMAccountName = sAMAccountName.Substring(checked(sAMAccountName.IndexOf("\\") + 1));
using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultLdapRoot)
{
var loadProperties = AdditionalProperties == null ? UserLoadProperties : UserLoadProperties.Concat(AdditionalProperties).ToArray();
using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectCategory=Person)(sAMAccountName={0}))", ActiveDirectoryHelpers.EscapeLdapQuery(sAMAccountName)), loadProperties, SearchScope.Subtree))
{
SearchResult dResult = dSearcher.FindOne();
if (dResult != null)
return ActiveDirectory.ActiveDirectoryUserAccountFromSearchResult(dResult, AdditionalProperties);
else
return null;
}
}
}
#endregion
#region Organisation Units
public static List<ActiveDirectoryOrganisationalUnit> GetOrganisationalUnitStructure() public static List<ActiveDirectoryOrganisationalUnit> GetOrganisationalUnitStructure()
{ {
ActiveDirectoryOrganisationalUnit DomainOUs = new ActiveDirectoryOrganisationalUnit ActiveDirectoryOrganisationalUnit DomainOUs = new ActiveDirectoryOrganisationalUnit
@@ -399,5 +390,173 @@ namespace Disco.BI.Interop.ActiveDirectory
} }
} }
#endregion
#region Groups
private static readonly string[] GroupLoadProperties = {
"name",
"distinguishedName",
"cn",
"sAMAccountName",
"objectSid",
"memberOf"
};
public static ActiveDirectoryGroup GetGroup(string SamAccountName)
{
if (string.IsNullOrWhiteSpace(SamAccountName))
throw new System.ArgumentException("Invalid Group Account", "SamAccountName");
string sAMAccountName = SamAccountName;
if (sAMAccountName.Contains("\\"))
sAMAccountName = sAMAccountName.Substring(checked(sAMAccountName.IndexOf("\\") + 1));
using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultLdapRoot)
{
using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectCategory=Group)(objectSid={0}))", ActiveDirectoryHelpers.EscapeLdapQuery(sAMAccountName)), GroupLoadProperties, SearchScope.Subtree))
{
SearchResult dResult = dSearcher.FindOne();
if (dResult != null)
{
return ActiveDirectoryGroupFromSearchResult(dResult);
}
else
return null;
}
}
}
public static ActiveDirectoryGroup GetGroupFromDistinguishedName(string DistinguishedName)
{
ActiveDirectoryGroup group = null;
using (DirectoryEntry groupDE = new DirectoryEntry(string.Concat(ActiveDirectoryHelpers.DefaultLdapPath, DistinguishedName)))
{
if (groupDE != null)
{
return ActiveDirectoryGroupFromDirectoryEntry(groupDE);
}
}
return group;
}
public static ActiveDirectoryGroup GetGroupFromSecurityIdentifier(string SecurityIdentifier)
{
using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultLdapRoot)
{
var sidBytes = ActiveDirectoryHelpers.ConvertSDDLStringToBytes(SecurityIdentifier);
var sidBinaryString = ActiveDirectoryHelpers.ConvertBytesToBinarySidString(sidBytes);
using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectCategory=Group)(objectSid={0}))", sidBinaryString), GroupLoadProperties, SearchScope.Subtree))
{
SearchResult dResult = dSearcher.FindOne();
if (dResult != null)
{
return ActiveDirectoryGroupFromSearchResult(dResult);
}
else
return null;
}
}
}
public static List<ActiveDirectoryGroup> SearchGroups(string term)
{
List<ActiveDirectoryGroup> results = new List<ActiveDirectoryGroup>();
string defaultQualifiedDomainName = ActiveDirectoryHelpers.DefaultDomainQualifiedName;
string defaultNetBiosDomainName = ActiveDirectoryHelpers.DefaultDomainNetBiosName;
term = ActiveDirectoryHelpers.EscapeLdapQuery(term);
using (DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", defaultQualifiedDomainName)))
{
using (DirectorySearcher searcher = new DirectorySearcher(entry, string.Format("(&(objectCategory=Group)(|(sAMAccountName=*{0}*)(name=*{0}*)(cn=*{0}*)))", term), GroupLoadProperties, SearchScope.Subtree))
{
searcher.SizeLimit = 30;
SearchResultCollection searchResults = searcher.FindAll();
foreach (SearchResult result in searchResults)
{
results.Add(ActiveDirectory.ActiveDirectoryGroupFromSearchResult(result));
}
}
}
return results;
}
private static ActiveDirectoryGroup ActiveDirectoryGroupFromDirectoryEntry(DirectoryEntry entry)
{
var name = (string)entry.Properties["name"].Value;
var distinguishedName = (string)entry.Properties["distinguishedName"].Value;
var cn = (string)entry.Properties["cn"].Value;
var sAMAccountName = (string)entry.Properties["sAMAccountName"].Value;
var objectSid = ActiveDirectoryHelpers.ConvertBytesToSDDLString((byte[])entry.Properties["objectSid"].Value);
var memberOf = entry.Properties["memberOf"].Cast<string>().ToList();
return new ActiveDirectoryGroup()
{
Name = name,
DistinguishedName = distinguishedName,
CommonName = cn,
SamAccountName = sAMAccountName,
SecurityIdentifier = objectSid,
MemberOf = memberOf
};
}
private static ActiveDirectoryGroup ActiveDirectoryGroupFromSearchResult(SearchResult result)
{
var name = (string)result.Properties["name"][0];
var distinguishedName = (string)result.Properties["distinguishedName"][0];
var cn = (string)result.Properties["cn"][0];
var sAMAccountName = (string)result.Properties["sAMAccountName"][0];
var objectSid = ActiveDirectoryHelpers.ConvertBytesToSDDLString((byte[])result.Properties["objectSid"][0]);
var memberOf = result.Properties["memberOf"].Cast<string>().ToList();
return new ActiveDirectoryGroup()
{
Name = name,
DistinguishedName = distinguishedName,
CommonName = cn,
SamAccountName = sAMAccountName,
SecurityIdentifier = objectSid,
MemberOf = memberOf
};
}
#endregion
private static readonly string[] ObjectLoadProperties = { "objectCategory" };
private static readonly string[] ObjectLoadPropertiesAll = ObjectLoadProperties.Concat(UserLoadProperties).Concat(MachineLoadProperties).Concat(GroupLoadProperties).Distinct().ToArray();
public static IActiveDirectoryObject GetObject(string SamAccountName)
{
if (string.IsNullOrWhiteSpace(SamAccountName))
throw new System.ArgumentException("Invalid Object Account Name", "SamAccountName");
string sAMAccountName = SamAccountName;
if (sAMAccountName.Contains("\\"))
sAMAccountName = sAMAccountName.Substring(checked(sAMAccountName.IndexOf("\\") + 1));
using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultLdapRoot)
{
using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(|(objectCategory=Person)(objectCategory=Computer)(objectCategory=Group))(sAMAccountName={0}))", ActiveDirectoryHelpers.EscapeLdapQuery(sAMAccountName)), ObjectLoadPropertiesAll, SearchScope.Subtree))
{
SearchResult dResult = dSearcher.FindOne();
if (dResult != null)
{
var objectCategory = (string)dResult.Properties["objectCategory"][0];
objectCategory = objectCategory.Substring(0, objectCategory.IndexOf(',')).ToLower();
switch (objectCategory)
{
case "cn=person":
return ActiveDirectoryUserAccountFromSearchResult(dResult);
case "cn=computer":
return ActiveDirectoryMachineAccountFromSearchResult(dResult);
case "cn=group":
return ActiveDirectoryGroupFromSearchResult(dResult);
default:
throw new InvalidOperationException("Unexpected objectCategory");
}
}
else
return null;
}
}
}
} }
} }
@@ -8,43 +8,44 @@ using System.Threading.Tasks;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Services.Tasks; using Disco.Services.Tasks;
using Quartz; using Quartz;
using Disco.Models.Interop.ActiveDirectory;
namespace Disco.BI.Interop.ActiveDirectory namespace Disco.BI.Interop.ActiveDirectory
{ {
public class ActiveDirectoryCachedGroups : ScheduledTask public class ActiveDirectoryCachedGroups : ScheduledTask
{ {
private static ConcurrentDictionary<string, Tuple<ADCachedGroup, DateTime>> _SidCache = new ConcurrentDictionary<string, Tuple<ADCachedGroup, DateTime>>(); private static ConcurrentDictionary<string, Tuple<ActiveDirectoryGroup, DateTime>> _SecurityIdentifierCache = new ConcurrentDictionary<string, Tuple<ActiveDirectoryGroup, DateTime>>();
private static ConcurrentDictionary<string, Tuple<ADCachedGroup, DateTime>> _Cache = new ConcurrentDictionary<string, Tuple<ADCachedGroup, DateTime>>(); private static ConcurrentDictionary<string, Tuple<ActiveDirectoryGroup, DateTime>> _DistinguishedNameCache = new ConcurrentDictionary<string, Tuple<ActiveDirectoryGroup, DateTime>>();
private const long CacheTimeoutTicks = 6000000000; // 10 Minutes private const long CacheTimeoutTicks = 6000000000; // 10 Minutes
public static IEnumerable<string> GetGroups(IEnumerable<string> GroupCNs) public static IEnumerable<string> GetGroups(IEnumerable<string> DistinguishedNames)
{ {
List<ADCachedGroup> groups = new List<ADCachedGroup>(); List<ActiveDirectoryGroup> groups = new List<ActiveDirectoryGroup>();
foreach (var groupCN in GroupCNs) foreach (var distinguishedName in DistinguishedNames)
foreach (var group in GetGroupsRecursive(groupCN, new Stack<ADCachedGroup>())) foreach (var group in GetGroupsRecursive(distinguishedName, new Stack<ActiveDirectoryGroup>()))
if (!groups.Contains(group)) if (!groups.Contains(group))
{ {
groups.Add(group); groups.Add(group);
yield return group.FriendlyName; yield return group.SamAccountName;
} }
} }
public static IEnumerable<string> GetGroups(string GroupCN) public static IEnumerable<string> GetGroups(string DistinguishedName)
{ {
foreach (var group in GetGroupsRecursive(GroupCN, new Stack<ADCachedGroup>())) foreach (var group in GetGroupsRecursive(DistinguishedName, new Stack<ActiveDirectoryGroup>()))
yield return group.FriendlyName; yield return group.SamAccountName;
} }
public static string GetGroupsCnForSid(string GroupSid) public static string GetGroupsDistinguishedNameForSecurityIdentifier(string SecurityIdentifier)
{ {
var sidGroup = GetGroupBySid(GroupSid); var group = GetGroupBySecurityIdentifier(SecurityIdentifier);
if (sidGroup == null) if (group == null)
return null; return null;
else else
return sidGroup.CN; return group.DistinguishedName;
} }
private static IEnumerable<ADCachedGroup> GetGroupsRecursive(string GroupCN, Stack<ADCachedGroup> RecursiveTree) private static IEnumerable<ActiveDirectoryGroup> GetGroupsRecursive(string DistinguishedName, Stack<ActiveDirectoryGroup> RecursiveTree)
{ {
var group = GetGroup(GroupCN); var group = GetGroup(DistinguishedName);
if (group != null && !RecursiveTree.Contains(group)) if (group != null && !RecursiveTree.Contains(group))
{ {
@@ -54,24 +55,24 @@ namespace Disco.BI.Interop.ActiveDirectory
{ {
RecursiveTree.Push(group); RecursiveTree.Push(group);
foreach (var memberOfGroupCN in group.MemberOf) foreach (var parentDistinguishedName in group.MemberOf)
foreach (var memberOfGroup in GetGroupsRecursive(memberOfGroupCN, RecursiveTree)) foreach (var parentGroup in GetGroupsRecursive(parentDistinguishedName, RecursiveTree))
yield return memberOfGroup; yield return parentGroup;
RecursiveTree.Pop(); RecursiveTree.Pop();
} }
} }
} }
private static ADCachedGroup GetGroup(string GroupCN) private static ActiveDirectoryGroup GetGroup(string DistinguishedName)
{ {
// Check Cache // Check Cache
Tuple<ADCachedGroup, DateTime> groupRecord = TryCache(GroupCN); Tuple<ActiveDirectoryGroup, DateTime> groupRecord = TryCache(DistinguishedName);
if (groupRecord == null) if (groupRecord == null)
{ {
// Load from AD // Load from AD
var group = ADCachedGroup.LoadWithCN(GroupCN); var group = ActiveDirectory.GetGroupFromDistinguishedName(DistinguishedName);
SetValue(group); SetValue(group);
return group; return group;
@@ -82,15 +83,15 @@ namespace Disco.BI.Interop.ActiveDirectory
return groupRecord.Item1; return groupRecord.Item1;
} }
} }
private static ADCachedGroup GetGroupBySid(string GroupSid) private static ActiveDirectoryGroup GetGroupBySecurityIdentifier(string SecurityIdentifier)
{ {
// Check Cache // Check Cache
Tuple<ADCachedGroup, DateTime> groupRecord = TrySidCache(GroupSid); Tuple<ActiveDirectoryGroup, DateTime> groupRecord = TrySecurityIdentifierCache(SecurityIdentifier);
if (groupRecord == null) if (groupRecord == null)
{ {
// Load from AD // Load from AD
var group = ADCachedGroup.LoadWithSid(GroupSid); var group = ActiveDirectory.GetGroupFromSecurityIdentifier(SecurityIdentifier);
SetValue(group); SetValue(group);
return group; return group;
@@ -102,177 +103,96 @@ namespace Disco.BI.Interop.ActiveDirectory
} }
} }
private static Tuple<ADCachedGroup, DateTime> TryCache(string GroupCN) private static Tuple<ActiveDirectoryGroup, DateTime> TryCache(string DistinguishedName)
{ {
string groupCN = GroupCN.ToLower(); string distinguishedName = DistinguishedName.ToLower();
Tuple<ADCachedGroup, DateTime> groupRecord; Tuple<ActiveDirectoryGroup, DateTime> groupRecord;
if (_Cache.TryGetValue(groupCN, out groupRecord)) if (_DistinguishedNameCache.TryGetValue(distinguishedName, out groupRecord))
{ {
if (groupRecord.Item2 > DateTime.Now) if (groupRecord.Item2 > DateTime.Now)
return groupRecord; return groupRecord;
else else
{ {
if (_Cache.TryRemove(groupCN, out groupRecord)) if (_DistinguishedNameCache.TryRemove(distinguishedName, out groupRecord))
_SidCache.TryRemove(groupRecord.Item1.ObjectSid, out groupRecord); _SecurityIdentifierCache.TryRemove(groupRecord.Item1.SecurityIdentifier, out groupRecord);
} }
} }
return null; return null;
} }
private static Tuple<ADCachedGroup, DateTime> TrySidCache(string GroupSid) private static Tuple<ActiveDirectoryGroup, DateTime> TrySecurityIdentifierCache(string SecurityIdentifier)
{ {
Tuple<ADCachedGroup, DateTime> groupRecord; Tuple<ActiveDirectoryGroup, DateTime> groupRecord;
if (_SidCache.TryGetValue(GroupSid, out groupRecord)) if (_SecurityIdentifierCache.TryGetValue(SecurityIdentifier, out groupRecord))
{ {
if (groupRecord.Item2 > DateTime.Now) if (groupRecord.Item2 > DateTime.Now)
return groupRecord; return groupRecord;
else else
{ {
if (_SidCache.TryRemove(GroupSid, out groupRecord)) if (_SecurityIdentifierCache.TryRemove(SecurityIdentifier, out groupRecord))
_Cache.TryRemove(groupRecord.Item1.CN.ToLower(), out groupRecord); _DistinguishedNameCache.TryRemove(groupRecord.Item1.DistinguishedName.ToLower(), out groupRecord);
} }
} }
return null; return null;
} }
private static bool SetValue(ADCachedGroup GroupRecord) private static bool SetValue(ActiveDirectoryGroup Group)
{ {
Tuple<ADCachedGroup, DateTime> groupRecord = new Tuple<ADCachedGroup, DateTime>(GroupRecord, DateTime.Now.AddTicks(CacheTimeoutTicks)); Tuple<ActiveDirectoryGroup, DateTime> groupRecord = new Tuple<ActiveDirectoryGroup, DateTime>(Group, DateTime.Now.AddTicks(CacheTimeoutTicks));
Tuple<ADCachedGroup, DateTime> oldGroupRecord; Tuple<ActiveDirectoryGroup, DateTime> oldGroupRecord;
string key = GroupRecord.CN.ToLower(); string key = Group.DistinguishedName.ToLower();
if (_Cache.ContainsKey(key)) if (_DistinguishedNameCache.ContainsKey(key))
{ {
if (_Cache.TryGetValue(key, out oldGroupRecord)) if (_DistinguishedNameCache.TryGetValue(key, out oldGroupRecord))
{ {
_Cache.TryUpdate(key, groupRecord, oldGroupRecord); _DistinguishedNameCache.TryUpdate(key, groupRecord, oldGroupRecord);
} }
} }
else else
{ {
_Cache.TryAdd(key, groupRecord); _DistinguishedNameCache.TryAdd(key, groupRecord);
} }
string sid = GroupRecord.ObjectSid; string securityIdentifier = Group.SecurityIdentifier;
if (_SidCache.ContainsKey(sid)) if (_SecurityIdentifierCache.ContainsKey(securityIdentifier))
{ {
if (_SidCache.TryGetValue(sid, out oldGroupRecord)) if (_SecurityIdentifierCache.TryGetValue(securityIdentifier, out oldGroupRecord))
{ {
_SidCache.TryUpdate(sid, groupRecord, oldGroupRecord); _SecurityIdentifierCache.TryUpdate(securityIdentifier, groupRecord, oldGroupRecord);
} }
} }
else else
{ {
_SidCache.TryAdd(sid, groupRecord); _SecurityIdentifierCache.TryAdd(securityIdentifier, groupRecord);
} }
return true; return true;
} }
private class ADCachedGroup
{
public string ObjectSid { get; set; }
public string CN { get; private set; }
public string FriendlyName { get; private set; }
public List<string> MemberOf { get; private set; }
public static ADCachedGroup LoadWithCN(string CN)
{
ADCachedGroup group = null;
using (DirectoryEntry groupDE = new DirectoryEntry(string.Concat(ActiveDirectoryHelpers.DefaultLdapPath, CN)))
{
if (groupDE != null)
{
group = new ADCachedGroup()
{
CN = CN
};
group.ObjectSid = ActiveDirectoryHelpers.ConvertBytesToSDDLString((byte[])groupDE.Properties["objectSid"].Value);
group.FriendlyName = (string)groupDE.Properties["sAMAccountName"].Value;
var groupMemberOf = groupDE.Properties["memberOf"];
if (groupMemberOf != null && groupMemberOf.Count > 0)
{
group.MemberOf = groupMemberOf.Cast<string>().ToList();
}
}
}
return group;
}
public static ADCachedGroup LoadWithSid(string Sid)
{
using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultLdapRoot)
{
var loadProperties = new List<string> {
"distinguishedName",
"objectSid",
"sAMAccountName",
"memberOf"
};
var sidBytes = ActiveDirectoryHelpers.ConvertSDDLStringToBytes(Sid);
var sidBinaryString = ActiveDirectoryHelpers.ConvertBytesToBinarySidString(sidBytes);
using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectClass=group)(objectSid={0}))", sidBinaryString), loadProperties.ToArray(), SearchScope.Subtree))
{
SearchResult dResult = dSearcher.FindOne();
if (dResult != null)
{
var group = new ADCachedGroup()
{
CN = (string)dResult.Properties["distinguishedName"][0],
ObjectSid = ActiveDirectoryHelpers.ConvertBytesToSDDLString((byte[])dResult.Properties["objectSid"][0]),
FriendlyName = (string)dResult.Properties["sAMAccountName"][0]
};
var groupMemberOf = dResult.Properties["memberOf"];
if (groupMemberOf != null && groupMemberOf.Count > 0)
{
group.MemberOf = groupMemberOf.Cast<string>().ToList();
}
return group;
}
else
return null;
}
}
}
private ADCachedGroup()
{
// Private Constructor
}
}
private static void CleanStaleCache() private static void CleanStaleCache()
{ {
// Clean Cache // Clean Cache
var groupKeys = _Cache.Keys.ToArray(); var groupKeys = _DistinguishedNameCache.Keys.ToArray();
foreach (string groupKey in groupKeys) foreach (string groupKey in groupKeys)
{ {
Tuple<ADCachedGroup, DateTime> groupRecord; Tuple<ActiveDirectoryGroup, DateTime> groupRecord;
if (_Cache.TryGetValue(groupKey, out groupRecord)) if (_DistinguishedNameCache.TryGetValue(groupKey, out groupRecord))
{ {
if (groupRecord.Item2 <= DateTime.Now) if (groupRecord.Item2 <= DateTime.Now)
{ {
_Cache.TryRemove(groupKey, out groupRecord); _DistinguishedNameCache.TryRemove(groupKey, out groupRecord);
} }
} }
} }
// Clean SID Cache // Clean SID Cache
groupKeys = _SidCache.Keys.ToArray(); groupKeys = _SecurityIdentifierCache.Keys.ToArray();
foreach (string groupKey in groupKeys) foreach (string groupKey in groupKeys)
{ {
Tuple<ADCachedGroup, DateTime> groupRecord; Tuple<ActiveDirectoryGroup, DateTime> groupRecord;
if (_SidCache.TryGetValue(groupKey, out groupRecord)) if (_SecurityIdentifierCache.TryGetValue(groupKey, out groupRecord))
{ {
if (groupRecord.Item2 <= DateTime.Now) if (groupRecord.Item2 <= DateTime.Now)
{ {
_SidCache.TryRemove(groupKey, out groupRecord); _SecurityIdentifierCache.TryRemove(groupKey, out groupRecord);
} }
} }
} }
@@ -284,7 +204,7 @@ namespace Disco.BI.Interop.ActiveDirectory
public override bool CancelInitiallySupported { get { return false; } } public override bool CancelInitiallySupported { get { return false; } }
public override bool LogExceptionsOnly { get { return true; } } public override bool LogExceptionsOnly { get { return true; } }
public override void InitalizeScheduledTask(DiscoDataContext dbContext) public override void InitalizeScheduledTask(DiscoDataContext Database)
{ {
// Run @ every 15mins // Run @ every 15mins
@@ -0,0 +1,19 @@
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();
}
}
}
@@ -191,11 +191,11 @@ namespace Disco.BI.Interop.ActiveDirectory
case "name": case "name":
return account.Name; return account.Name;
case "samaccountname": case "samaccountname":
return account.sAMAccountName; return account.SamAccountName;
case "distinguishedname": case "distinguishedname":
return account.DistinguishedName; return account.DistinguishedName;
case "objectsid": case "objectsid":
return account.ObjectSid; return account.SecurityIdentifier;
case "netbootguid": case "netbootguid":
return account.NetbootGUID; return account.NetbootGUID;
default: default:
@@ -268,7 +268,9 @@ namespace Disco.BI.Interop.ActiveDirectory
if (account.IsCriticalSystemObject) 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)); throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", account.DistinguishedName));
if (!account.ParentDistinguishedName.Equals(NewOrganisationUnit, StringComparison.InvariantCultureIgnoreCase)) var parentDistinguishedName = account.ParentDistinguishedName();
if (parentDistinguishedName != null && !parentDistinguishedName.Equals(NewOrganisationUnit, StringComparison.InvariantCultureIgnoreCase))
{ {
string ouPath; string ouPath;
if (string.IsNullOrWhiteSpace(NewOrganisationUnit)) if (string.IsNullOrWhiteSpace(NewOrganisationUnit))
@@ -286,5 +288,14 @@ namespace Disco.BI.Interop.ActiveDirectory
} }
} }
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;
}
} }
} }
@@ -21,7 +21,7 @@ namespace Disco.BI.Interop.ActiveDirectory
public override bool SingleInstanceTask { get { return true; } } public override bool SingleInstanceTask { get { return true; } }
public override bool CancelInitiallySupported { get { return false; } } public override bool CancelInitiallySupported { get { return false; } }
public override void InitalizeScheduledTask(DiscoDataContext dbContext) public override void InitalizeScheduledTask(DiscoDataContext Database)
{ {
// ActiveDirectoryUpdateLastNetworkLogonDateJob @ 11:30pm // ActiveDirectoryUpdateLastNetworkLogonDateJob @ 11:30pm
TriggerBuilder triggerBuilder = TriggerBuilder.Create(). TriggerBuilder triggerBuilder = TriggerBuilder.Create().
@@ -35,11 +35,11 @@ namespace Disco.BI.Interop.ActiveDirectory
int changeCount; int changeCount;
this.Status.UpdateStatus(1, "Starting", "Connecting to the Database and initializing the environment"); this.Status.UpdateStatus(1, "Starting", "Connecting to the Database and initializing the environment");
using (DiscoDataContext dbContext = new DiscoDataContext()) using (DiscoDataContext database = new DiscoDataContext())
{ {
UpdateLastNetworkLogonDates(dbContext, this.Status); UpdateLastNetworkLogonDates(database, this.Status);
this.Status.UpdateStatus(95, "Updating Database", "Writing last network logon dates to the Database"); this.Status.UpdateStatus(95, "Updating Database", "Writing last network logon dates to the Database");
changeCount = dbContext.SaveChanges(); changeCount = database.SaveChanges();
this.Status.Finished(string.Format("{0} Device last network logon dates updated", changeCount), "/Config/SystemConfig"); this.Status.Finished(string.Format("{0} Device last network logon dates updated", changeCount), "/Config/SystemConfig");
} }
@@ -86,7 +86,7 @@ namespace Disco.BI.Interop.ActiveDirectory
{ {
using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultDCLdapRoot(dcName)) using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultDCLdapRoot(dcName))
{ {
DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectClass=computer)(sAMAccountName={0}$))", ActiveDirectoryHelpers.EscapeLdapQuery(Device.ComputerName)), new string[] DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectCategory=Computer)(sAMAccountName={0}$))", ActiveDirectoryHelpers.EscapeLdapQuery(Device.ComputerName)), new string[]
{ {
"lastLogon" "lastLogon"
}, SearchScope.Subtree); }, SearchScope.Subtree);
@@ -150,7 +150,7 @@ namespace Disco.BI.Interop.ActiveDirectory
UpdateLastNetworkLogonDate = false; UpdateLastNetworkLogonDate = false;
return UpdateLastNetworkLogonDate; return UpdateLastNetworkLogonDate;
} }
private static void UpdateLastNetworkLogonDates(DiscoDataContext context, ScheduledTaskStatus status) private static void UpdateLastNetworkLogonDates(DiscoDataContext Database, ScheduledTaskStatus status)
{ {
System.Collections.Generic.Dictionary<string, System.DateTime> computerLastLogonDates = new System.Collections.Generic.Dictionary<string, System.DateTime>(); System.Collections.Generic.Dictionary<string, System.DateTime> computerLastLogonDates = new System.Collections.Generic.Dictionary<string, System.DateTime>();
@@ -176,7 +176,7 @@ namespace Disco.BI.Interop.ActiveDirectory
double progressDCStart = 5 + (progressDCCount * progressDCProgress); double progressDCStart = 5 + (progressDCCount * progressDCProgress);
status.UpdateStatus(progressDCStart, string.Format("Querying Domain Controller: {0}", dcName), "Searching..."); status.UpdateStatus(progressDCStart, string.Format("Querying Domain Controller: {0}", dcName), "Searching...");
using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, "(objectClass=computer)", new string[] { "sAMAccountName", "lastLogon" }, SearchScope.Subtree)) using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, "(objectCategory=Computer)", new string[] { "sAMAccountName", "lastLogon" }, SearchScope.Subtree))
{ {
using (SearchResultCollection dResults = dSearcher.FindAll()) using (SearchResultCollection dResults = dSearcher.FindAll())
{ {
@@ -238,7 +238,7 @@ namespace Disco.BI.Interop.ActiveDirectory
} }
foreach (Device d in context.Devices.Where(device => device.ComputerName != null)) foreach (Device d in Database.Devices.Where(device => device.ComputerName != null))
{ {
DateTime computerLastLogonDate; DateTime computerLastLogonDate;
if (computerLastLogonDates.TryGetValue(d.ComputerName.ToUpper(), out computerLastLogonDate)) if (computerLastLogonDates.TryGetValue(d.ComputerName.ToUpper(), out computerLastLogonDate))
@@ -5,11 +5,6 @@ namespace Disco.BI.Interop.ActiveDirectory
{ {
internal static class ActiveDirectoryUserAccountExtensions internal static class ActiveDirectoryUserAccountExtensions
{ {
public static bool HasRole(this ActiveDirectoryUserAccount account, string Role)
{
return account.Groups != null && account.Groups.Contains(Role.ToLower());
}
public static object GetPropertyValue(this ActiveDirectoryUserAccount account, string PropertyName, int Index = 0) public static object GetPropertyValue(this ActiveDirectoryUserAccount account, string PropertyName, int Index = 0)
{ {
switch (PropertyName.ToLower()) switch (PropertyName.ToLower())
@@ -17,11 +12,11 @@ namespace Disco.BI.Interop.ActiveDirectory
case "name": case "name":
return account.Name; return account.Name;
case "samaccountname": case "samaccountname":
return account.sAMAccountName; return account.SamAccountName;
case "distinguishedname": case "distinguishedname":
return account.DistinguishedName; return account.DistinguishedName;
case "objectsid": case "objectsid":
return account.ObjectSid; return account.SecurityIdentifier;
case "sn": case "sn":
return account.Surname; return account.Surname;
case "givenname": case "givenname":
+17 -12
View File
@@ -31,12 +31,12 @@ namespace Disco.BI.Interop.Community
return string.Format("{0}.{1}.{2:0000}.{3:0000}", v.Major, v.Minor, v.Build, v.Revision); return string.Format("{0}.{1}.{2:0000}.{3:0000}", v.Major, v.Minor, v.Build, v.Revision);
} }
public static UpdateResponse Check(DiscoDataContext db, bool UseProxy, ScheduledTaskStatus status = null) public static UpdateResponse Check(DiscoDataContext Database, bool UseProxy, ScheduledTaskStatus status = null)
{ {
if (status != null) if (status != null)
status.UpdateStatus(10, "Building Update Request"); status.UpdateStatus(10, "Building Update Request");
var request = BuildRequest(db); var request = BuildRequest(Database);
//var requestJson = JsonConvert.SerializeObject(request); //var requestJson = JsonConvert.SerializeObject(request);
if (status != null) if (status != null)
@@ -78,8 +78,8 @@ namespace Disco.BI.Interop.Community
result = (UpdateResponse)xml.Deserialize(wResStream); result = (UpdateResponse)xml.Deserialize(wResStream);
} }
//var result = JsonConvert.DeserializeObject<UpdateResponse>(responseContent); //var result = JsonConvert.DeserializeObject<UpdateResponse>(responseContent);
db.DiscoConfiguration.UpdateLastCheck = result; Database.DiscoConfiguration.UpdateLastCheck = result;
db.SaveChanges(); Database.SaveChanges();
status.SetFinishedMessage(string.Format("The update server reported Version {0} is the latest.", result.Version)); status.SetFinishedMessage(string.Format("The update server reported Version {0} is the latest.", result.Version));
@@ -94,23 +94,28 @@ namespace Disco.BI.Interop.Community
} }
} }
private static UpdateRequestV1 BuildRequest(DiscoDataContext db) private static UpdateRequestV1 BuildRequest(DiscoDataContext Database)
{ {
var m = new UpdateRequestV1(); var m = new UpdateRequestV1();
m.DeploymentId = db.DiscoConfiguration.DeploymentId; m.DeploymentId = Database.DiscoConfiguration.DeploymentId;
m.CurrentDiscoVersion = CurrentDiscoVersionFormatted(); m.CurrentDiscoVersion = CurrentDiscoVersionFormatted();
m.OrganisationName = db.DiscoConfiguration.OrganisationName; m.OrganisationName = Database.DiscoConfiguration.OrganisationName;
m.BroadbandDoeWanId = GetBroadbandDoeWanId(); m.BroadbandDoeWanId = GetBroadbandDoeWanId();
m.BetaDeployment = db.DiscoConfiguration.UpdateBetaDeployment; m.BetaDeployment = Database.DiscoConfiguration.UpdateBetaDeployment;
m.Stat_JobCounts = db.Jobs.GroupBy(j => j.JobTypeId).Select(g => new Disco.Models.BI.Interop.Community.UpdateRequestV1.Stat { Key = g.Key, Count = g.Count() }).ToList(); m.Stat_JobCounts = Database.Jobs.GroupBy(j => j.JobTypeId).Select(g => new Disco.Models.BI.Interop.Community.UpdateRequestV1.Stat { Key = g.Key, Count = g.Count() }).ToList();
m.Stat_OpenJobCounts = db.Jobs.Where(j => j.ClosedDate == null).GroupBy(j => j.JobTypeId).Select(g => new Disco.Models.BI.Interop.Community.UpdateRequestV1.Stat { Key = g.Key, Count = g.Count() }).ToList(); m.Stat_OpenJobCounts = Database.Jobs.Where(j => j.ClosedDate == null).GroupBy(j => j.JobTypeId).Select(g => new Disco.Models.BI.Interop.Community.UpdateRequestV1.Stat { Key = g.Key, Count = g.Count() }).ToList();
var activeThreshold = DateTime.Now.AddDays(-60); var activeThreshold = DateTime.Now.AddDays(-60);
m.Stat_ActiveDeviceModelCounts = db.DeviceModels.Select(dm => new Disco.Models.BI.Interop.Community.UpdateRequestV1.Stat { Key = dm.Manufacturer + ";" + dm.Model, Count = dm.Devices.Count(d => d.DecommissionedDate == null && (d.LastNetworkLogonDate == null || d.LastNetworkLogonDate > activeThreshold)) }).ToList(); m.Stat_ActiveDeviceModelCounts = Database.DeviceModels.Select(dm => new Disco.Models.BI.Interop.Community.UpdateRequestV1.Stat { Key = dm.Manufacturer + ";" + dm.Model, Count = dm.Devices.Count(d => d.DecommissionedDate == null && (d.LastNetworkLogonDate == null || d.LastNetworkLogonDate > activeThreshold)) }).ToList();
m.Stat_UserCounts = db.Users.GroupBy(u => u.Type).Select(g => new Disco.Models.BI.Interop.Community.UpdateRequestV1.Stat { Key = g.Key, Count = g.Count() }).ToList(); m.Stat_UserCounts = new List<UpdateRequestV1.Stat>() {
new UpdateRequestV1.Stat(){
Key = "All Users",
Count = Database.Users.Count()
}
};
m.InstalledPlugins = Disco.Services.Plugins.Plugins.GetPlugins().Select(manifest => new Disco.Models.BI.Interop.Community.UpdateRequestV1.PluginRef { Id = manifest.Id, Version = manifest.VersionFormatted }).ToList(); m.InstalledPlugins = Disco.Services.Plugins.Plugins.GetPlugins().Select(manifest => new Disco.Models.BI.Interop.Community.UpdateRequestV1.PluginRef { Id = manifest.Id, Version = manifest.VersionFormatted }).ToList();
@@ -53,7 +53,7 @@ namespace Disco.BI.Interop.Community
} }
} }
public override void InitalizeScheduledTask(Data.Repository.DiscoDataContext dbContext) public override void InitalizeScheduledTask(Data.Repository.DiscoDataContext Database)
{ {
// Random time between midday and midnight. // Random time between midday and midnight.
var rnd = new Random(); var rnd = new Random();
@@ -69,17 +69,17 @@ namespace Disco.BI.Interop.Community
protected override void ExecuteTask() protected override void ExecuteTask()
{ {
using (DiscoDataContext db = new DiscoDataContext()) using (DiscoDataContext database = new DiscoDataContext())
{ {
try try
{ {
UpdateCheck.Check(db, true, this.Status); UpdateCheck.Check(database, true, this.Status);
} }
catch (Exception ex) catch (Exception ex)
{ {
ScheduledTasksLog.LogScheduledTaskException(this.Status.TaskName, this.Status.SessionId, this.Status.TaskType, ex); ScheduledTasksLog.LogScheduledTaskException(this.Status.TaskName, this.Status.SessionId, this.Status.TaskType, ex);
// Could be proxy error - try again without proxy: // Could be proxy error - try again without proxy:
UpdateCheck.Check(db, false, this.Status); UpdateCheck.Check(database, false, this.Status);
} }
} }
} }
+14 -13
View File
@@ -12,13 +12,14 @@ using Disco.BI.Expressions;
using System.Collections; using System.Collections;
using Disco.BI.Extensions; using Disco.BI.Extensions;
using Disco.Models.BI.Expressions; using Disco.Models.BI.Expressions;
using Disco.Services.Users;
namespace Disco.BI.Interop.Pdf namespace Disco.BI.Interop.Pdf
{ {
public static class PdfGenerator public static class PdfGenerator
{ {
public static System.IO.Stream GenerateBulkFromTemplate(DocumentTemplate dt, DiscoDataContext dbContext, User CreatorUser, System.DateTime Timestamp, params object[] DataObjects) public static System.IO.Stream GenerateBulkFromTemplate(DocumentTemplate dt, DiscoDataContext Database, User CreatorUser, System.DateTime Timestamp, params object[] DataObjects)
{ {
if (DataObjects.Length > 0) if (DataObjects.Length > 0)
{ {
@@ -27,7 +28,7 @@ namespace Disco.BI.Interop.Pdf
{ {
foreach (object d in DataObjects) foreach (object d in DataObjects)
{ {
generatedPdfs.Add(dt.GeneratePdf(dbContext, d, CreatorUser, Timestamp, state, true)); generatedPdfs.Add(dt.GeneratePdf(Database, d, CreatorUser, Timestamp, state, true));
state.SequenceNumber++; state.SequenceNumber++;
state.FlushScopeCache(); state.FlushScopeCache();
} }
@@ -47,24 +48,24 @@ namespace Disco.BI.Interop.Pdf
return null; return null;
} }
public static System.IO.Stream GenerateBulkFromTemplate(DocumentTemplate dt, DiscoDataContext dbContext, User CreatorUser, System.DateTime Timestamp, params string[] DataObjectsIds) public static System.IO.Stream GenerateBulkFromTemplate(DocumentTemplate dt, DiscoDataContext Database, User CreatorUser, System.DateTime Timestamp, params string[] DataObjectsIds)
{ {
object[] DataObjects; object[] DataObjects;
switch (dt.Scope) switch (dt.Scope)
{ {
case DocumentTemplate.DocumentTemplateScopes.Device: case DocumentTemplate.DocumentTemplateScopes.Device:
DataObjects = dbContext.Devices.Where(d => DataObjectsIds.Contains(d.SerialNumber)).ToArray(); DataObjects = Database.Devices.Where(d => DataObjectsIds.Contains(d.SerialNumber)).ToArray();
break; break;
case DocumentTemplate.DocumentTemplateScopes.Job: case DocumentTemplate.DocumentTemplateScopes.Job:
int[] intDataObjectsIds = DataObjectsIds.Select(i => int.Parse(i)).ToArray(); int[] intDataObjectsIds = DataObjectsIds.Select(i => int.Parse(i)).ToArray();
DataObjects = dbContext.Jobs.Where(j => intDataObjectsIds.Contains(j.Id)).ToArray(); DataObjects = Database.Jobs.Where(j => intDataObjectsIds.Contains(j.Id)).ToArray();
break; break;
case DocumentTemplate.DocumentTemplateScopes.User: case DocumentTemplate.DocumentTemplateScopes.User:
DataObjects = new object[DataObjectsIds.Length]; DataObjects = new object[DataObjectsIds.Length];
for (int idIndex = 0; idIndex < DataObjectsIds.Length; idIndex++) for (int idIndex = 0; idIndex < DataObjectsIds.Length; idIndex++)
{ {
DataObjects[idIndex] = UserBI.UserCache.GetUser(DataObjectsIds[idIndex], dbContext, true); DataObjects[idIndex] = UserService.GetUser(DataObjectsIds[idIndex], Database, true);
if (DataObjects[idIndex] == null) if (DataObjects[idIndex] == null)
throw new Exception(string.Format("Unknown Username specified: {0}", DataObjectsIds[idIndex])); throw new Exception(string.Format("Unknown Username specified: {0}", DataObjectsIds[idIndex]));
} }
@@ -73,10 +74,10 @@ namespace Disco.BI.Interop.Pdf
throw new InvalidOperationException("Invalid DocumentType Scope"); throw new InvalidOperationException("Invalid DocumentType Scope");
} }
return GenerateBulkFromTemplate(dt, dbContext, CreatorUser, Timestamp, DataObjects); return GenerateBulkFromTemplate(dt, Database, CreatorUser, Timestamp, DataObjects);
} }
public static System.IO.Stream GenerateFromTemplate(DocumentTemplate dt, DiscoDataContext dbContext, object Data, User CreatorUser, System.DateTime TimeStamp, DocumentState State, bool FlattenFields = false) public static System.IO.Stream GenerateFromTemplate(DocumentTemplate dt, DiscoDataContext Database, object Data, User CreatorUser, System.DateTime TimeStamp, DocumentState State, bool FlattenFields = false)
{ {
// Validate Data // Validate Data
switch (dt.Scope) switch (dt.Scope)
@@ -97,15 +98,15 @@ namespace Disco.BI.Interop.Pdf
throw new InvalidOperationException("Invalid AttachmentType Scope"); throw new InvalidOperationException("Invalid AttachmentType Scope");
} }
dbContext.Configuration.LazyLoadingEnabled = true; Database.Configuration.LazyLoadingEnabled = true;
// Override FlattenFields if Document Template instructs. // Override FlattenFields if Document Template instructs.
if (dt.FlattenForm) if (dt.FlattenForm)
FlattenFields = true; FlattenFields = true;
ConcurrentDictionary<string, Expression> expressionCache = dt.PdfExpressionsFromCache(dbContext); ConcurrentDictionary<string, Expression> expressionCache = dt.PdfExpressionsFromCache(Database);
string templateFilename = dt.RepositoryFilename(dbContext); string templateFilename = dt.RepositoryFilename(Database);
PdfReader pdfReader = new PdfReader(templateFilename); PdfReader pdfReader = new PdfReader(templateFilename);
MemoryStream pdfGeneratedStream = new MemoryStream(); MemoryStream pdfGeneratedStream = new MemoryStream();
@@ -114,7 +115,7 @@ namespace Disco.BI.Interop.Pdf
pdfStamper.FormFlattening = FlattenFields; pdfStamper.FormFlattening = FlattenFields;
pdfStamper.Writer.CloseStream = false; pdfStamper.Writer.CloseStream = false;
IDictionary expressionVariables = Expression.StandardVariables(dt, dbContext, CreatorUser, TimeStamp, State); IDictionary expressionVariables = Expression.StandardVariables(dt, Database, CreatorUser, TimeStamp, State);
foreach (string pdfFieldKey in pdfStamper.AcroFields.Fields.Keys) foreach (string pdfFieldKey in pdfStamper.AcroFields.Fields.Keys)
{ {
@@ -240,7 +241,7 @@ namespace Disco.BI.Interop.Pdf
Timestamp = DateTime.Now Timestamp = DateTime.Now
}; };
jl.Comments = string.Format("Document Generated{0}{1} [{2}]", Environment.NewLine, dt.Description, dt.Id); jl.Comments = string.Format("Document Generated{0}{1} [{2}]", Environment.NewLine, dt.Description, dt.Id);
dbContext.JobLogs.Add(jl); Database.JobLogs.Add(jl);
} }
pdfGeneratedStream.Position = 0; pdfGeneratedStream.Position = 0;
+15 -15
View File
@@ -205,7 +205,7 @@ namespace Disco.BI.Interop.Pdf
return null; return null;
} }
private static DetectImageResult DetectImage(DiscoDataContext dbContext, Bitmap pageImageOriginal, string SessionId, IEnumerable<DocumentTemplate> detectDocumentTemplates, DetectStateHints StateHints) private static DetectImageResult DetectImage(DiscoDataContext Database, Bitmap pageImageOriginal, string SessionId, IEnumerable<DocumentTemplate> detectDocumentTemplates, DetectStateHints StateHints)
{ {
Bitmap pageImage = pageImageOriginal; Bitmap pageImage = pageImageOriginal;
double pageImageModifiedScale = 1; double pageImageModifiedScale = 1;
@@ -270,7 +270,7 @@ namespace Disco.BI.Interop.Pdf
{ {
foreach (DocumentTemplate dt in detectDocumentTemplates) foreach (DocumentTemplate dt in detectDocumentTemplates)
{ {
var locationBag = dt.QRCodeLocations(dbContext); var locationBag = dt.QRCodeLocations(Database);
foreach (var location in locationBag) foreach (var location in locationBag)
{ {
result = DetectImageFromSegment(pageImage, zxingMfr, zxingMfrHints, result = DetectImageFromSegment(pageImage, zxingMfr, zxingMfrHints,
@@ -303,7 +303,7 @@ namespace Disco.BI.Interop.Pdf
} }
} }
private static DetectPageResult DetectPage(DiscoDataContext dbContext, PdfReader pdfReader, int PageNumber, string SessionId, string DataStoreSessionCacheLocation, IEnumerable<DocumentTemplate> detectDocumentTemplates, DetectStateHints StateHints) private static DetectPageResult DetectPage(DiscoDataContext Database, PdfReader pdfReader, int PageNumber, string SessionId, string DataStoreSessionCacheLocation, IEnumerable<DocumentTemplate> detectDocumentTemplates, DetectStateHints StateHints)
{ {
DetectPageResult result = new DetectPageResult() { PageNumber = PageNumber }; DetectPageResult result = new DetectPageResult() { PageNumber = PageNumber };
@@ -325,7 +325,7 @@ namespace Disco.BI.Interop.Pdf
{ {
DocumentImporterLog.LogImportPageProgress(SessionId, PageNumber, (int)(10 + (pageProgressInterval * pageImages.IndexOf(pageImageOriginal))), String.Format("Processing Page Image {0} of {1}", pageImages.IndexOf(pageImageOriginal) + 1, pageImages.Count)); DocumentImporterLog.LogImportPageProgress(SessionId, PageNumber, (int)(10 + (pageProgressInterval * pageImages.IndexOf(pageImageOriginal))), String.Format("Processing Page Image {0} of {1}", pageImages.IndexOf(pageImageOriginal) + 1, pageImages.Count));
using (var zxingResult = DetectImage(dbContext, pageImageOriginal, SessionId, detectDocumentTemplates, StateHints)) using (var zxingResult = DetectImage(Database, pageImageOriginal, SessionId, detectDocumentTemplates, StateHints))
{ {
if (zxingResult != null) if (zxingResult != null)
{ {
@@ -377,9 +377,9 @@ namespace Disco.BI.Interop.Pdf
} }
} }
public static bool ProcessPdfAttachment(string Filename, DiscoDataContext dbContext, string SessionId, Cache HttpCache) public static bool ProcessPdfAttachment(string Filename, DiscoDataContext Database, string SessionId, Cache HttpCache)
{ {
var dataStoreUnassignedLocation = DataStore.CreateLocation(dbContext, "DocumentDropBox_Unassigned"); var dataStoreUnassignedLocation = DataStore.CreateLocation(Database, "DocumentDropBox_Unassigned");
DocumentImporterLog.LogImportProgress(SessionId, 0, "Reading File"); DocumentImporterLog.LogImportProgress(SessionId, 0, "Reading File");
@@ -389,8 +389,8 @@ namespace Disco.BI.Interop.Pdf
var pdfPagesAssigned = new Dictionary<int, Tuple<DocumentUniqueIdentifier, byte[]>>(); var pdfPagesAssigned = new Dictionary<int, Tuple<DocumentUniqueIdentifier, byte[]>>();
var dataStoreSessionPagesCacheLocation = DataStore.CreateLocation(dbContext, "Cache\\DocumentDropBox_SessionPages"); var dataStoreSessionPagesCacheLocation = DataStore.CreateLocation(Database, "Cache\\DocumentDropBox_SessionPages");
var detectDocumentTemplates = dbContext.DocumentTemplates.ToArray(); var detectDocumentTemplates = Database.DocumentTemplates.ToArray();
double progressInterval = 70 / pdfReader.NumberOfPages; double progressInterval = 70 / pdfReader.NumberOfPages;
@@ -401,14 +401,14 @@ namespace Disco.BI.Interop.Pdf
DocumentImporterLog.LogImportProgress(SessionId, (int)(PageNumber * progressInterval), string.Format("Processing Page {0} of {1}", PageNumber, pdfReader.NumberOfPages)); DocumentImporterLog.LogImportProgress(SessionId, (int)(PageNumber * progressInterval), string.Format("Processing Page {0} of {1}", PageNumber, pdfReader.NumberOfPages));
DocumentImporterLog.LogImportPageStarting(SessionId, PageNumber); DocumentImporterLog.LogImportPageStarting(SessionId, PageNumber);
using (var pageResult = DetectPage(dbContext, pdfReader, PageNumber, SessionId, dataStoreSessionPagesCacheLocation, detectDocumentTemplates, detectStateHints)) using (var pageResult = DetectPage(Database, pdfReader, PageNumber, SessionId, dataStoreSessionPagesCacheLocation, detectDocumentTemplates, detectStateHints))
{ {
if (pageResult.DetectedIdentifier != null) if (pageResult.DetectedIdentifier != null)
{ {
var docId = pageResult.DetectedIdentifier; var docId = pageResult.DetectedIdentifier;
pdfPagesAssigned.Add(PageNumber, new Tuple<DocumentUniqueIdentifier, byte[]>(docId, pageResult.AttachmentThumbnailImage.ToArray())); pdfPagesAssigned.Add(PageNumber, new Tuple<DocumentUniqueIdentifier, byte[]>(docId, pageResult.AttachmentThumbnailImage.ToArray()));
docId.LoadComponents(dbContext); docId.LoadComponents(Database);
DocumentImporterLog.LogImportPageDetected(SessionId, PageNumber, docId.DocumentUniqueId, docId.DocumentTemplate.Description, docId.DocumentTemplate.Scope, docId.DataId, docId.DataDescription); DocumentImporterLog.LogImportPageDetected(SessionId, PageNumber, docId.DocumentUniqueId, docId.DocumentTemplate.Description, docId.DocumentTemplate.Scope, docId.DataId, docId.DataDescription);
} }
else else
@@ -441,7 +441,7 @@ namespace Disco.BI.Interop.Pdf
var documentPortionIdentifier = documentPortionInfo.Item1; var documentPortionIdentifier = documentPortionInfo.Item1;
var documentPortionThumbnail = documentPortionInfo.Item2; var documentPortionThumbnail = documentPortionInfo.Item2;
if (!documentPortionIdentifier.LoadComponents(dbContext)) if (!documentPortionIdentifier.LoadComponents(Database))
{ {
// Unknown Document Unique Id // Unknown Document Unique Id
foreach (var dp in documentPortion) foreach (var dp in documentPortion)
@@ -477,7 +477,7 @@ namespace Disco.BI.Interop.Pdf
msBuilder.Position = 0; msBuilder.Position = 0;
var attachmentSuccess = documentPortionIdentifier.ImportPdfAttachment(dbContext, msBuilder, documentPortionThumbnail); var attachmentSuccess = documentPortionIdentifier.ImportPdfAttachment(Database, msBuilder, documentPortionThumbnail);
if (!attachmentSuccess) if (!attachmentSuccess)
{ // Unable to add Attachment { // Unable to add Attachment
@@ -538,13 +538,13 @@ namespace Disco.BI.Interop.Pdf
return true; return true;
} }
public static bool ProcessPdfAttachment(string Filename, DiscoDataContext dbContext, string DocumentTemplateId, string DataId, string UserId, DateTime Timestamp) public static bool ProcessPdfAttachment(string Filename, DiscoDataContext Database, string DocumentTemplateId, string DataId, string UserId, DateTime Timestamp)
{ {
using (FileStream fs = new FileStream(Filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) using (FileStream fs = new FileStream(Filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{ {
DocumentUniqueIdentifier identifier = new DocumentUniqueIdentifier(DocumentTemplateId, DataId, UserId, Timestamp); DocumentUniqueIdentifier identifier = new DocumentUniqueIdentifier(DocumentTemplateId, DataId, UserId, Timestamp);
identifier.LoadComponents(dbContext); identifier.LoadComponents(Database);
return identifier.ImportPdfAttachment(dbContext, fs, null); return identifier.ImportPdfAttachment(Database, fs, null);
} }
} }
@@ -1,14 +0,0 @@
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using Disco.Data.Repository;
//using Quartz;
//namespace Disco.BI.Interop.PluginServices
//{
// interface IDiscoScheduledTask
// {
// void InitalizeScheduledTask(DiscoDataContext dbContext, IScheduler Scheduler);
// }
//}
@@ -1,45 +0,0 @@
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using Disco.Data.Repository;
//using Quartz;
//namespace Disco.BI.Interop.PluginServices
//{
// public static class Utilities
// {
// public static void InitalizeScheduledTasks(DiscoDataContext dbContext, ISchedulerFactory SchedulerFactory)
// {
// var scheduler = SchedulerFactory.GetScheduler();
// // Discover IDiscoScheduledTasks (Only from Disco Assemblies)
// var appDomain = AppDomain.CurrentDomain;
// var scheduledTaskTypes = (from a in appDomain.GetAssemblies()
// where !a.GlobalAssemblyCache && !a.IsDynamic && a.FullName.StartsWith("Disco.", StringComparison.InvariantCultureIgnoreCase)
// from type in a.GetTypes()
// where typeof(IDiscoScheduledTask).IsAssignableFrom(type) && !type.IsAbstract
// select type);
// foreach (Type scheduledTaskType in scheduledTaskTypes)
// {
// IDiscoScheduledTask instance = (IDiscoScheduledTask)Activator.CreateInstance(scheduledTaskType);
// try
// {
// instance.InitalizeScheduledTask(dbContext, scheduler);
// }
// catch (Exception ex)
// {
// if (instance == null)
// Logging.SystemLog.LogException("Initializing Scheduled Task; Disco.BI.Interop.Plugins.Utilities.InitalizeScheduledTasks()", ex);
// else
// Logging.SystemLog.LogException(string.Format("Initializing Scheduled Task: '{0}'; Disco.BI.Interop.Plugins.Utilities.InitalizeScheduledTasks()", instance.GetType().Name), ex);
// }
// }
// }
// }
//}
@@ -1,16 +0,0 @@
using Disco.Models.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.BI.Interop.SignalRHandlers
{
public class AdminAuthorizedPersistentConnection : AuthorizedPersistentConnection
{
private string[] authorizedUserTypes = { User.Types.Admin };
protected override string[] AuthorizedUserTypes { get { return authorizedUserTypes; } }
}
}
@@ -1,4 +1,5 @@
using Microsoft.AspNet.SignalR; using Disco.Services.Users;
using Microsoft.AspNet.SignalR;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@@ -9,9 +10,9 @@ namespace Disco.BI.Interop.SignalRHandlers
{ {
public class AuthorizedPersistentConnection : PersistentConnection public class AuthorizedPersistentConnection : PersistentConnection
{ {
private string[] authorizedUserTypes = null; private string authorizedClaim = null;
protected virtual string[] AuthorizedUserTypes { get { return authorizedUserTypes; } } protected virtual string AuthorizedClaim { get { return authorizedClaim; } }
protected override bool AuthorizeRequest(IRequest request) protected override bool AuthorizeRequest(IRequest request)
{ {
@@ -19,17 +20,15 @@ namespace Disco.BI.Interop.SignalRHandlers
return false; return false;
else else
{ {
var user = UserBI.UserCache.CurrentUser; var authToken = UserService.CurrentAuthorization;
if (user == null)
return false;
if (AuthorizedUserTypes == null || AuthorizedUserTypes.Length == 0) if (authToken == null)
return true; return false; // No Current User
if (AuthorizedUserTypes.Contains(user.Type)) if (authorizedClaim == null)
return true; return true; // Just Authenticate - no Authorization
else
return false; return authToken.Has(authorizedClaim);
} }
} }
} }
@@ -61,7 +61,7 @@ namespace Disco.BI.Interop.SignalRHandlers
{ {
User u = (User)e.Entity; User u = (User)e.Entity;
var userDevices = e.dbContext.Devices.Where(d => d.AssignedUserId == u.Id); var userDevices = e.Database.Devices.Where(d => d.AssignedUserId == u.Id);
foreach (var userDevice in userDevices) foreach (var userDevice in userDevices)
{ {
@@ -1,4 +1,5 @@
using Disco.Services.Logging; using Disco.Services.Authorization;
using Disco.Services.Logging;
using Disco.Services.Logging.Models; using Disco.Services.Logging.Models;
using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR;
using System; using System;
@@ -9,10 +10,12 @@ using System.Threading.Tasks;
namespace Disco.BI.Interop.SignalRHandlers namespace Disco.BI.Interop.SignalRHandlers
{ {
public class LogNotifications : AdminAuthorizedPersistentConnection public class LogNotifications : AuthorizedPersistentConnection
{ {
public static bool initialized = false; public static bool initialized = false;
protected override string AuthorizedClaim { get { return Claims.DiscoAdminAccount; } }
public LogNotifications() public LogNotifications()
{ {
if (!initialized) if (!initialized)
@@ -1,4 +1,5 @@
using Disco.Data.Repository.Monitor; using Disco.Data.Repository.Monitor;
using Disco.Services.Authorization;
using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -8,8 +9,10 @@ using System.Threading.Tasks;
namespace Disco.BI.Interop.SignalRHandlers namespace Disco.BI.Interop.SignalRHandlers
{ {
public class RepositoryMonitorNotifications : AdminAuthorizedPersistentConnection public class RepositoryMonitorNotifications : AuthorizedPersistentConnection
{ {
protected override string AuthorizedClaim { get { return Claims.DiscoAdminAccount; } }
public static void Initialize() public static void Initialize()
{ {
RepositoryMonitor.StreamAfterCommit.Subscribe(AfterCommit); RepositoryMonitor.StreamAfterCommit.Subscribe(AfterCommit);
@@ -1,4 +1,5 @@
using Disco.Services.Tasks; using Disco.Services.Authorization;
using Disco.Services.Tasks;
using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -8,10 +9,12 @@ using System.Threading.Tasks;
namespace Disco.BI.Interop.SignalRHandlers namespace Disco.BI.Interop.SignalRHandlers
{ {
public class ScheduledTasksStatusNotifications : AdminAuthorizedPersistentConnection public class ScheduledTasksStatusNotifications : AuthorizedPersistentConnection
{ {
public static bool initialized = false; public static bool initialized = false;
protected override string AuthorizedClaim { get { return Claims.DiscoAdminAccount; } }
public ScheduledTasksStatusNotifications() public ScheduledTasksStatusNotifications()
{ {
if (!initialized) if (!initialized)
@@ -48,7 +48,7 @@ namespace Disco.BI.Interop.SignalRHandlers
if (j.DeviceSerialNumber != null) if (j.DeviceSerialNumber != null)
{ {
var jobDevice = e.dbContext.Devices.Where(d => d.SerialNumber == j.DeviceSerialNumber).FirstOrDefault(); var jobDevice = e.Database.Devices.Where(d => d.SerialNumber == j.DeviceSerialNumber).FirstOrDefault();
if (jobDevice.AssignedUserId != null) if (jobDevice.AssignedUserId != null)
notificationContext.Connection.Broadcast(jobDevice.AssignedUserId); notificationContext.Connection.Broadcast(jobDevice.AssignedUserId);
+24 -11
View File
@@ -9,6 +9,7 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Disco.BI.Extensions; using Disco.BI.Extensions;
using System.Reactive.Linq; using System.Reactive.Linq;
using Disco.Services.Users;
namespace Disco.BI.JobBI namespace Disco.BI.JobBI
{ {
@@ -20,10 +21,22 @@ namespace Disco.BI.JobBI
private IDisposable unsubscribeToken; private IDisposable unsubscribeToken;
private object updateLock = new object(); private object updateLock = new object();
public ManagedJobList Initialize(DiscoDataContext dbContext) public override List<JobTableItemModel> Items
{
get
{
return base.Items.PermissionsFiltered(UserService.CurrentAuthorization);
}
set
{
throw new InvalidOperationException("Items cannot be manually set in a Managed Job List");
}
}
public ManagedJobList Initialize(DiscoDataContext Database)
{ {
// Initially fill table // Initially fill table
this.Items = this.SortFunction(this.DetermineItems(dbContext, this.FilterFunction(dbContext.Jobs))).ToList(); base.Items = this.SortFunction(this.DetermineItems(Database, this.FilterFunction(Database.Jobs))).ToList();
// Subscribe for Changes // Subscribe for Changes
// - Job (or Job Meta) Changes // - Job (or Job Meta) Changes
@@ -65,19 +78,19 @@ namespace Disco.BI.JobBI
if (e.EntityType == typeof(DeviceProfile)) if (e.EntityType == typeof(DeviceProfile))
{ {
int deviceProfileId = ((DeviceProfile)e.Entity).Id; int deviceProfileId = ((DeviceProfile)e.Entity).Id;
existingItems = this.Items.Where(i => i.DeviceProfileId == deviceProfileId).ToArray(); existingItems = base.Items.Where(i => i.DeviceProfileId == deviceProfileId).ToArray();
} }
else else
if (e.EntityType == typeof(DeviceModel)) if (e.EntityType == typeof(DeviceModel))
{ {
int deviceModelId = ((DeviceModel)e.Entity).Id; int deviceModelId = ((DeviceModel)e.Entity).Id;
existingItems = this.Items.Where(i => i.DeviceModelId == deviceModelId).ToArray(); existingItems = base.Items.Where(i => i.DeviceModelId == deviceModelId).ToArray();
} }
else else
if (e.EntityType == typeof(Device)) if (e.EntityType == typeof(Device))
{ {
string deviceSerialNumber = ((Device)e.Entity).SerialNumber; string deviceSerialNumber = ((Device)e.Entity).SerialNumber;
existingItems = this.Items.Where(i => i.DeviceSerialNumber == deviceSerialNumber).ToArray(); existingItems = base.Items.Where(i => i.DeviceSerialNumber == deviceSerialNumber).ToArray();
} }
else else
return; // Subscription should never reach return; // Subscription should never reach
@@ -93,20 +106,20 @@ namespace Disco.BI.JobBI
if (jobIds.Count == 0) if (jobIds.Count == 0)
return; return;
else else
UpdateJobs(e.dbContext, jobIds, existingItems); UpdateJobs(e.Database, jobIds, existingItems);
} }
private void UpdateJobs(DiscoDataContext dbContext, List<int> jobIds, JobTableItemModel[] existingItems = null) private void UpdateJobs(DiscoDataContext Database, List<int> jobIds, JobTableItemModel[] existingItems = null)
{ {
lock (updateLock) lock (updateLock)
{ {
// Check for existing items, if not handed them // Check for existing items, if not handed them
if (existingItems == null) if (existingItems == null)
existingItems = this.Items.Where(i => jobIds.Contains(i.Id)).ToArray(); existingItems = base.Items.Where(i => jobIds.Contains(i.Id)).ToArray();
var updatedItems = this.DetermineItems(dbContext, this.FilterFunction(dbContext.Jobs.Where(j => jobIds.Contains(j.Id)))); var updatedItems = this.DetermineItems(Database, this.FilterFunction(Database.Jobs.Where(j => jobIds.Contains(j.Id))));
var refreshedList = this.Items.ToList(); var refreshedList = base.Items.ToList();
// Remove Existing // Remove Existing
if (existingItems.Length > 0) if (existingItems.Length > 0)
@@ -119,7 +132,7 @@ namespace Disco.BI.JobBI
refreshedList.Add(updatedItem); refreshedList.Add(updatedItem);
// Reorder // Reorder
this.Items = this.SortFunction(refreshedList).ToList(); base.Items = this.SortFunction(refreshedList).ToList();
} }
} }
+8 -8
View File
@@ -11,7 +11,7 @@ namespace Disco.BI.JobBI
{ {
public static class Searching public static class Searching
{ {
public static JobTableModel Search(DiscoDataContext dbContext, string Term, int? LimitCount = null, bool IncludeJobStatus = true, bool SearchDetails = false) public static JobTableModel Search(DiscoDataContext Database, string Term, int? LimitCount = null, bool IncludeJobStatus = true, bool SearchDetails = false)
{ {
int termInt = default(int); int termInt = default(int);
@@ -22,7 +22,7 @@ namespace Disco.BI.JobBI
// Term is a Number (int) // Term is a Number (int)
if (SearchDetails) if (SearchDetails)
{ {
query = BuildJobTableModel(dbContext).Where(j => query = BuildJobTableModel(Database).Where(j =>
j.Id == termInt || j.Id == termInt ||
j.DeviceHeldLocation.Contains(Term) || j.DeviceHeldLocation.Contains(Term) ||
j.Device.SerialNumber.Contains(Term) || j.Device.SerialNumber.Contains(Term) ||
@@ -36,7 +36,7 @@ namespace Disco.BI.JobBI
} }
else else
{ {
query = BuildJobTableModel(dbContext).Where(j => query = BuildJobTableModel(Database).Where(j =>
j.Id == termInt || j.Id == termInt ||
j.DeviceHeldLocation.Contains(Term) || j.DeviceHeldLocation.Contains(Term) ||
j.Device.SerialNumber.Contains(Term) || j.Device.SerialNumber.Contains(Term) ||
@@ -51,7 +51,7 @@ namespace Disco.BI.JobBI
{ {
if (SearchDetails) if (SearchDetails)
{ {
query = BuildJobTableModel(dbContext).Where(j => query = BuildJobTableModel(Database).Where(j =>
j.DeviceHeldLocation.Contains(Term) || j.DeviceHeldLocation.Contains(Term) ||
j.Device.SerialNumber.Contains(Term) || j.Device.SerialNumber.Contains(Term) ||
j.Device.AssetNumber.Contains(Term) || j.Device.AssetNumber.Contains(Term) ||
@@ -64,7 +64,7 @@ namespace Disco.BI.JobBI
} }
else else
{ {
query = BuildJobTableModel(dbContext).Where(j => query = BuildJobTableModel(Database).Where(j =>
j.DeviceHeldLocation.Contains(Term) || j.DeviceHeldLocation.Contains(Term) ||
j.Device.SerialNumber.Contains(Term) || j.Device.SerialNumber.Contains(Term) ||
j.Device.AssetNumber.Contains(Term) || j.Device.AssetNumber.Contains(Term) ||
@@ -79,14 +79,14 @@ namespace Disco.BI.JobBI
query = query.Take(LimitCount.Value); query = query.Take(LimitCount.Value);
JobTableModel model = new JobTableModel() { ShowStatus = IncludeJobStatus }; JobTableModel model = new JobTableModel() { ShowStatus = IncludeJobStatus };
model.Fill(dbContext, query); model.Fill(Database, query);
return model; return model;
} }
public static IQueryable<Job> BuildJobTableModel(DiscoDataContext dbContext) public static IQueryable<Job> BuildJobTableModel(DiscoDataContext Database)
{ {
return dbContext.Jobs.Include("JobType").Include("Device").Include("User").Include("OpenedTechUser"); return Database.Jobs.Include("JobType").Include("Device").Include("User").Include("OpenedTechUser");
} }
} }
@@ -25,7 +25,7 @@ namespace Disco.BI.JobBI.Statistics
public override bool SingleInstanceTask { get { return true; } } public override bool SingleInstanceTask { get { return true; } }
public override bool CancelInitiallySupported { get { return false; } } public override bool CancelInitiallySupported { get { return false; } }
public override void InitalizeScheduledTask(DiscoDataContext dbContext) public override void InitalizeScheduledTask(DiscoDataContext Database)
{ {
// Trigger Daily @ 12:29am // Trigger Daily @ 12:29am
TriggerBuilder triggerBuilder = TriggerBuilder.Create().WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(0, 29)); TriggerBuilder triggerBuilder = TriggerBuilder.Create().WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(0, 29));
@@ -34,40 +34,13 @@ namespace Disco.BI.JobBI.Statistics
} }
protected override void ExecuteTask() protected override void ExecuteTask()
{ {
using (var dbContext = new DiscoDataContext()) using (var database = new DiscoDataContext())
{ {
UpdateDataHistory(dbContext, true); UpdateDataHistory(database, true);
} }
} }
//public void InitalizeScheduledTask(DiscoDataContext dbContext, IScheduler Scheduler) private static void UpdateDataHistory(DiscoDataContext Database, bool Refresh = false)
//{
// // Run @ 12:29am
// IJobDetail jobDetail = new JobDetailImpl("JobStatisticsDailyOpenedClosed", typeof(DailyOpenedClosed));
// ITrigger trigger = TriggerBuilder.Create().
// WithIdentity("JobStatisticsDailyOpenedClosedTrigger").
// StartNow().
// WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(0, 29)).
// Build();
// Scheduler.ScheduleJob(jobDetail, trigger);
//}
//public void Execute(IJobExecutionContext context)
//{
// try
// {
// using (var dbContext = new DiscoDataContext())
// {
// UpdateDataHistory(dbContext, true);
// }
// }
// catch (Exception ex)
// {
// Logging.SystemLog.LogException("Disco.BI.JobBI.Statistics.DailyOpenedClosed", ex);
// }
//}
private static void UpdateDataHistory(DiscoDataContext dbContext, bool Refresh = false)
{ {
DateTime historyEnd = DateTime.Now.Date; DateTime historyEnd = DateTime.Now.Date;
@@ -98,7 +71,7 @@ namespace Disco.BI.JobBI.Statistics
// Cache Data // Cache Data
while (processDate <= historyEnd) while (processDate <= historyEnd)
{ {
resultData.Add(Data(dbContext, processDate)); resultData.Add(Data(Database, processDate));
processDate = processDate.AddDays(1); processDate = processDate.AddDays(1);
} }
_data = resultData; _data = resultData;
@@ -162,14 +135,14 @@ namespace Disco.BI.JobBI.Statistics
} }
} }
private static DailyOpenedClosedItem Data(DiscoDataContext dbContext, DateTime ProcessDate) private static DailyOpenedClosedItem Data(DiscoDataContext Database, DateTime ProcessDate)
{ {
DateTime processDateStart = ProcessDate; DateTime processDateStart = ProcessDate;
DateTime processDateEnd = ProcessDate.AddDays(1); DateTime processDateEnd = ProcessDate.AddDays(1);
int totalJobs = dbContext.Jobs.Where(j => j.OpenedDate < processDateEnd && (!j.ClosedDate.HasValue || j.ClosedDate > processDateEnd)).Count(); int totalJobs = Database.Jobs.Where(j => j.OpenedDate < processDateEnd && (!j.ClosedDate.HasValue || j.ClosedDate > processDateEnd)).Count();
int openedJobs = dbContext.Jobs.Where(j => j.OpenedDate > processDateStart && j.OpenedDate < processDateEnd).Count(); int openedJobs = Database.Jobs.Where(j => j.OpenedDate > processDateStart && j.OpenedDate < processDateEnd).Count();
int closedJobs = dbContext.Jobs.Where(j => j.ClosedDate > processDateStart && j.ClosedDate < processDateEnd).Count(); int closedJobs = Database.Jobs.Where(j => j.ClosedDate > processDateStart && j.ClosedDate < processDateEnd).Count();
return new DailyOpenedClosedItem() return new DailyOpenedClosedItem()
{ {
@@ -180,11 +153,11 @@ namespace Disco.BI.JobBI.Statistics
}; };
} }
public static List<DailyOpenedClosedItem> Data(DiscoDataContext dbContext, bool FilterUnimportantWeekends = false) public static List<DailyOpenedClosedItem> Data(DiscoDataContext Database, bool FilterUnimportantWeekends = false)
{ {
List<DailyOpenedClosedItem> resultData; List<DailyOpenedClosedItem> resultData;
UpdateDataHistory(dbContext); UpdateDataHistory(Database);
if (FilterUnimportantWeekends) if (FilterUnimportantWeekends)
resultData = _data.Where(i => (i.Timestamp.DayOfWeek != DayOfWeek.Saturday && i.Timestamp.DayOfWeek != DayOfWeek.Sunday) || resultData = _data.Where(i => (i.Timestamp.DayOfWeek != DayOfWeek.Saturday && i.Timestamp.DayOfWeek != DayOfWeek.Sunday) ||
@@ -192,9 +165,6 @@ namespace Disco.BI.JobBI.Statistics
else else
resultData = _data.ToList(); resultData = _data.ToList();
// Removed - Live Updated via Repository Monitor; See: RepositoryEvent_JobChange
//resultData.Add(Data(dbContext, DateTime.Today));
return resultData; return resultData;
} }
} }
+6 -6
View File
@@ -10,7 +10,7 @@ namespace Disco.BI.JobBI
{ {
public static class Utilities public static class Utilities
{ {
public static Job Create(DiscoDataContext dbContext, Device device, User user, JobType type, List<JobSubType> subTypes, User initialTech) public static Job Create(DiscoDataContext Database, Device device, User user, JobType type, List<JobSubType> subTypes, User initialTech)
{ {
Job j = new Job() Job j = new Job()
{ {
@@ -38,19 +38,19 @@ namespace Disco.BI.JobBI
List<JobSubType> jobSubTypes = subTypes.ToList(); List<JobSubType> jobSubTypes = subTypes.ToList();
j.JobSubTypes = jobSubTypes; j.JobSubTypes = jobSubTypes;
dbContext.Jobs.Add(j); Database.Jobs.Add(j);
switch (type.Id) switch (type.Id)
{ {
case JobType.JobTypeIds.HWar: case JobType.JobTypeIds.HWar:
dbContext.JobMetaWarranties.Add(new JobMetaWarranty() { Job = j }); Database.JobMetaWarranties.Add(new JobMetaWarranty() { Job = j });
break; break;
case JobType.JobTypeIds.HNWar: case JobType.JobTypeIds.HNWar:
dbContext.JobMetaNonWarranties.Add(new JobMetaNonWarranty() { Job = j }); Database.JobMetaNonWarranties.Add(new JobMetaNonWarranty() { Job = j });
if (device != null) if (device != null)
{ {
// Add Job Components // Add Job Components
var components = dbContext.DeviceComponents.Include("JobSubTypes").Where(c => !c.DeviceModelId.HasValue || c.DeviceModelId == j.Device.DeviceModelId); var components = Database.DeviceComponents.Include("JobSubTypes").Where(c => !c.DeviceModelId.HasValue || c.DeviceModelId == j.Device.DeviceModelId);
var addedComponents = new List<DeviceComponent>(); var addedComponents = new List<DeviceComponent>();
foreach (var c in components) foreach (var c in components)
{ {
@@ -76,7 +76,7 @@ namespace Disco.BI.JobBI
} }
} }
foreach (var c in addedComponents) foreach (var c in addedComponents)
dbContext.JobComponents.Add(new JobComponent() Database.JobComponents.Add(new JobComponent()
{ {
Job = j, Job = j,
TechUserId = initialTech.Id, TechUserId = initialTech.Id,
+7 -6
View File
@@ -5,6 +5,7 @@ using System.Text;
using Disco.Models.BI.Search; using Disco.Models.BI.Search;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Services.Users;
namespace Disco.BI.UserBI namespace Disco.BI.UserBI
{ {
@@ -32,7 +33,7 @@ namespace Disco.BI.UserBI
}).ToList(); }).ToList();
} }
public static List<UserSearchResultItem> Search(DiscoDataContext dbContext, string Term, int? LimitCount = null) public static List<UserSearchResultItem> Search(DiscoDataContext Database, string Term, int? LimitCount = null)
{ {
if (string.IsNullOrWhiteSpace(Term) || Term.Length < 2) if (string.IsNullOrWhiteSpace(Term) || Term.Length < 2)
throw new ArgumentException("Search Term must contain at least two characters", "Term"); throw new ArgumentException("Search Term must contain at least two characters", "Term");
@@ -41,16 +42,16 @@ namespace Disco.BI.UserBI
var adImportedUsers = Interop.ActiveDirectory.ActiveDirectory.SearchUsers(Term).Select(adU => adU.ToRepositoryUser()); var adImportedUsers = Interop.ActiveDirectory.ActiveDirectory.SearchUsers(Term).Select(adU => adU.ToRepositoryUser());
foreach (var adU in adImportedUsers) foreach (var adU in adImportedUsers)
{ {
var existingUser = dbContext.Users.Find(adU.Id); var existingUser = Database.Users.Find(adU.Id);
if (existingUser != null) if (existingUser != null)
existingUser.UpdateSelf(adU); existingUser.UpdateSelf(adU);
else else
dbContext.Users.Add(adU); Database.Users.Add(adU);
dbContext.SaveChanges(); Database.SaveChanges();
UserCache.InvalidateValue(adU.Id); UserService.InvalidateCachedUser(adU.Id);
} }
return Search_SelectUserSearchResultItems(dbContext.Users.Where(u => return Search_SelectUserSearchResultItems(Database.Users.Where(u =>
u.Id.Contains(Term) || u.Id.Contains(Term) ||
u.Surname.Contains(Term) || u.Surname.Contains(Term) ||
u.GivenName.Contains(Term) || u.GivenName.Contains(Term) ||
-146
View File
@@ -1,146 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using Disco.Models.Repository;
using Disco.Data.Repository;
using System.Web;
using Quartz;
using Quartz.Impl;
using Disco.Services.Tasks;
namespace Disco.BI.UserBI
{
public class UserCache
{
private static ConcurrentDictionary<string, Tuple<User, DateTime>> _Cache = new ConcurrentDictionary<string, Tuple<User, DateTime>>();
private const long CacheTimeoutTicks = 6000000000; // 10 Minutes
private const string CacheHttpRequestKey = "Disco_CurrentUser";
public static User CurrentUser
{
get
{
string username = null;
User user;
// Check for ASP.NET
if (HttpContext.Current != null)
{
if (HttpContext.Current.Request.IsAuthenticated)
{
user = (User)HttpContext.Current.Items[CacheHttpRequestKey];
if (user != null)
return user;
username = HttpContext.Current.User.Identity.Name;
}
else
{
return null;
//throw new PlatformNotSupportedException("ASP.NET Authentication is not correctly configured");
}
}
// User default User
if (username == null)
{
username = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
}
user = GetUser(username);
if (HttpContext.Current != null && HttpContext.Current.Request.IsAuthenticated)
{
// Cache in current request
HttpContext.Current.Items[CacheHttpRequestKey] = user;
}
return user;
}
}
public static User GetUser(string Username)
{
// Check Cache
User u = TryUserCache(Username);
if (u == null)
{
// Load from Repository
using (DiscoDataContext dbContext = new DiscoDataContext())
{
u = GetUser(Username, dbContext, true);
}
}
return u;
}
public static User GetUser(string Username, DiscoDataContext dbContext, bool ForceRefresh = false)
{
User u = null;
// Check Cache
if (!ForceRefresh)
u = TryUserCache(Username);
if (u == null)
{
string username = Username.ToLower();
u = UserBI.Utilities.LoadUser(dbContext, username);
SetValue(username, u);
}
return u;
}
private static User TryUserCache(string Username)
{
string username = Username.ToLower();
Tuple<User, DateTime> userRecord;
if (_Cache.TryGetValue(username, out userRecord))
{
if (userRecord.Item2 > DateTime.Now)
return userRecord.Item1;
else
_Cache.TryRemove(username, out userRecord);
}
return null;
}
public static bool InvalidateValue(string Key)
{
Tuple<User, DateTime> userRecord;
return _Cache.TryRemove(Key.ToLower(), out userRecord);
}
private static bool SetValue(string Key, User User)
{
string key = Key.ToLower();
Tuple<User, DateTime> userRecord = new Tuple<User, DateTime>(User, DateTime.Now.AddTicks(CacheTimeoutTicks));
if (_Cache.ContainsKey(key))
{
Tuple<User, DateTime> oldUser;
if (_Cache.TryGetValue(key, out oldUser))
{
return _Cache.TryUpdate(key, userRecord, oldUser);
}
}
return _Cache.TryAdd(key, userRecord);
}
internal static void CleanStaleCache()
{
var usernames = _Cache.Keys.ToArray();
foreach (string username in usernames)
{
Tuple<User, DateTime> userRecord;
if (_Cache.TryGetValue(username, out userRecord))
{
if (userRecord.Item2 <= DateTime.Now)
_Cache.TryRemove(username, out userRecord);
}
}
}
}
}
-76
View File
@@ -1,76 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Disco.Models.Repository;
using Disco.Data.Repository;
using Disco.Models.BI.Search;
using System.Runtime.InteropServices;
using System.DirectoryServices.ActiveDirectory;
using Disco.Services.Logging;
namespace Disco.BI.UserBI
{
public static class Utilities
{
public static User LoadUser(DiscoDataContext dbContext, string Username)
{
// Machine Account ?
if (Username.EndsWith("$"))
{
return Interop.ActiveDirectory.ActiveDirectory.GetMachineAccount(Username).ToRepositoryUser();
}
// User Account
User user = null;
try
{
var ADUser = Interop.ActiveDirectory.ActiveDirectory.GetUserAccount(Username);
if (ADUser == null)
throw new ArgumentException(string.Format("Invalid Username: '{0}'", Username), "Username");
user = ADUser.ToRepositoryUser();
}
catch (COMException ex)
{
// If "Server is not operational" then Try Cache
if (ex.ErrorCode != -2147016646)
{
throw ex;
}
SystemLog.LogException("Primary Domain Controller Down? Disco.BI.UserBI.Utilities.LoadUser", ex);
}
catch (ActiveDirectoryOperationException ex)
{
// Try From Cache...
SystemLog.LogException("Primary Domain Controller Down? Disco.BI.UserBI.Utilities.LoadUser", ex);
}
// Update Repository
User existingUser;
if (user == null)
{
string username = Username.Contains(@"\") ? Username.Substring(Username.IndexOf(@"\") + 1) : Username;
existingUser = dbContext.Users.Find(username);
if (existingUser == null)
throw new ArgumentException(string.Format("Invalid User - Not In Disco DB: '{0}'", Username), "Username");
else
return existingUser;
}
existingUser = dbContext.Users.Find(user.Id);
if (existingUser == null)
{
dbContext.Users.Add(user);
}
else
{
existingUser.UpdateSelf(user);
user = existingUser;
}
dbContext.SaveChanges();
return user;
}
}
}
+2 -6
View File
@@ -143,6 +143,7 @@
<Compile Include="BI\Expressions\Extensions\UserExt.cs" /> <Compile Include="BI\Expressions\Extensions\UserExt.cs" />
<Compile Include="BI\Extensions\AttachmentActionExtensions.cs" /> <Compile Include="BI\Extensions\AttachmentActionExtensions.cs" />
<Compile Include="BI\Extensions\AttachmentExtensions.cs" /> <Compile Include="BI\Extensions\AttachmentExtensions.cs" />
<Compile Include="BI\Extensions\AuthorizationRoleExtensions.cs" />
<Compile Include="BI\Extensions\ClientServicesExtensions.cs" /> <Compile Include="BI\Extensions\ClientServicesExtensions.cs" />
<Compile Include="BI\Extensions\DeviceActionExtensions.cs" /> <Compile Include="BI\Extensions\DeviceActionExtensions.cs" />
<Compile Include="BI\Extensions\DeviceBatchExtensions.cs" /> <Compile Include="BI\Extensions\DeviceBatchExtensions.cs" />
@@ -175,6 +176,7 @@
<Compile Include="BI\DocumentTemplateBI\Importer\DocumentImporterLog.cs" /> <Compile Include="BI\DocumentTemplateBI\Importer\DocumentImporterLog.cs" />
<Compile Include="BI\Interop\ActiveDirectory\ActiveDirectory.cs" /> <Compile Include="BI\Interop\ActiveDirectory\ActiveDirectory.cs" />
<Compile Include="BI\Interop\ActiveDirectory\ActiveDirectoryCachedGroups.cs" /> <Compile Include="BI\Interop\ActiveDirectory\ActiveDirectoryCachedGroups.cs" />
<Compile Include="BI\Interop\ActiveDirectory\ActiveDirectoryGroupExtensions.cs" />
<Compile Include="BI\Interop\ActiveDirectory\ActiveDirectoryHelpers.cs" /> <Compile Include="BI\Interop\ActiveDirectory\ActiveDirectoryHelpers.cs" />
<Compile Include="BI\Interop\ActiveDirectory\ActiveDirectoryMachineAccountExtensions.cs" /> <Compile Include="BI\Interop\ActiveDirectory\ActiveDirectoryMachineAccountExtensions.cs" />
<Compile Include="BI\Interop\ActiveDirectory\ActiveDirectoryOrganisationalUnit.cs" /> <Compile Include="BI\Interop\ActiveDirectory\ActiveDirectoryOrganisationalUnit.cs" />
@@ -186,9 +188,6 @@
<Compile Include="BI\Interop\MimeTypes.cs" /> <Compile Include="BI\Interop\MimeTypes.cs" />
<Compile Include="BI\Interop\Pdf\PdfGenerator.cs" /> <Compile Include="BI\Interop\Pdf\PdfGenerator.cs" />
<Compile Include="BI\Interop\Pdf\PdfImporter.cs" /> <Compile Include="BI\Interop\Pdf\PdfImporter.cs" />
<Compile Include="BI\Interop\PluginServices\IDiscoScheduledTask.cs" />
<Compile Include="BI\Interop\PluginServices\Utilities.cs" />
<Compile Include="BI\Interop\SignalRHandlers\AdminAuthorizedPersistentConnection.cs" />
<Compile Include="BI\Interop\SignalRHandlers\AuthorizedPersistentConnection.cs" /> <Compile Include="BI\Interop\SignalRHandlers\AuthorizedPersistentConnection.cs" />
<Compile Include="BI\Interop\SignalRHandlers\HeldDeviceNotifications.cs" /> <Compile Include="BI\Interop\SignalRHandlers\HeldDeviceNotifications.cs" />
<Compile Include="BI\Interop\SignalRHandlers\LogNotifications.cs" /> <Compile Include="BI\Interop\SignalRHandlers\LogNotifications.cs" />
@@ -201,9 +200,6 @@
<Compile Include="BI\JobBI\Statistics\DailyOpenedClosed.cs" /> <Compile Include="BI\JobBI\Statistics\DailyOpenedClosed.cs" />
<Compile Include="BI\JobBI\Utilities.cs" /> <Compile Include="BI\JobBI\Utilities.cs" />
<Compile Include="BI\UserBI\Searching.cs" /> <Compile Include="BI\UserBI\Searching.cs" />
<Compile Include="BI\UserBI\UserCache.cs" />
<Compile Include="BI\UserBI\UserCachePruneTask.cs" />
<Compile Include="BI\UserBI\Utilities.cs" />
<Compile Include="BI\Extensions\UtilityExtensions.cs" /> <Compile Include="BI\Extensions\UtilityExtensions.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Properties\Resources.Designer.cs"> <Compile Include="Properties\Resources.Designer.cs">
+2 -2
View File
@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers // You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below: // by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")] // [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.0725.2249")] [assembly: AssemblyVersion("1.2.1001.1541")]
[assembly: AssemblyFileVersion("1.2.0725.2249")] [assembly: AssemblyFileVersion("1.2.1001.1541")]
+1 -1
View File
@@ -44,7 +44,7 @@ namespace Disco.Client
// Ignore Local Proxies // Ignore Local Proxies
WebRequest.DefaultWebProxy = new WebProxy(); WebRequest.DefaultWebProxy = new WebProxy();
// Override Http 100 Continue Behavour // Override Http 100 Continue Behaviour
ServicePointManager.Expect100Continue = false; ServicePointManager.Expect100Continue = false;
// Assume success unless otherwise notified // Assume success unless otherwise notified
+2 -2
View File
@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers // You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below: // by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")] // [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.0725.2102")] [assembly: AssemblyVersion("1.2.1001.1300")]
[assembly: AssemblyFileVersion("1.2.0725.2102")] [assembly: AssemblyFileVersion("1.2.1001.1300")]
@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers // You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below: // by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")] // [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.0725.2102")] [assembly: AssemblyVersion("1.2.1001.1300")]
[assembly: AssemblyFileVersion("1.2.0725.2102")] [assembly: AssemblyFileVersion("1.2.1001.1300")]
@@ -11,30 +11,30 @@ namespace Disco.Data.Configuration
{ {
public abstract class ConfigurationBase public abstract class ConfigurationBase
{ {
private DiscoDataContext dbContext; private DiscoDataContext Database;
public abstract string Scope { get; } public abstract string Scope { get; }
public ConfigurationBase(DiscoDataContext dbContext) public ConfigurationBase(DiscoDataContext Database)
{ {
this.dbContext = dbContext; this.Database = Database;
} }
protected List<ConfigurationItem> Items protected List<ConfigurationItem> Items
{ {
get get
{ {
return ConfigurationCache.GetConfigurationItems(dbContext, this.Scope); return ConfigurationCache.GetConfigurationItems(Database, this.Scope);
} }
} }
private void SetValue<ValueType>(string Key, ValueType Value) private void SetValue<ValueType>(string Key, ValueType Value)
{ {
ConfigurationCache.SetConfigurationValue(dbContext, this.Scope, Key, Value); ConfigurationCache.SetConfigurationValue(Database, this.Scope, Key, Value);
} }
private ValueType GetValue<ValueType>(string Key, ValueType Default) private ValueType GetValue<ValueType>(string Key, ValueType Default)
{ {
return ConfigurationCache.GetConfigurationValue(dbContext, this.Scope, Key, Default); return ConfigurationCache.GetConfigurationValue(Database, this.Scope, Key, Default);
} }
protected void Set<ValueType>(ValueType Value, [CallerMemberName] string Key = null) protected void Set<ValueType>(ValueType Value, [CallerMemberName] string Key = null)
+24 -24
View File
@@ -16,7 +16,7 @@ namespace Disco.Data.Configuration
private static List<ConfigurationItem> configurationItems = new List<ConfigurationItem>(); private static List<ConfigurationItem> configurationItems = new List<ConfigurationItem>();
private static object configurationItemsLock = new object(); private static object configurationItemsLock = new object();
private static void LoadConfigurationItems(DiscoDataContext dbContext, string Scope, bool Reload) private static void LoadConfigurationItems(DiscoDataContext Database, string Scope, bool Reload)
{ {
if (Reload || !configDictionary.ContainsKey(Scope)) if (Reload || !configDictionary.ContainsKey(Scope))
{ {
@@ -24,10 +24,10 @@ namespace Disco.Data.Configuration
{ {
if (Reload || !configDictionary.ContainsKey(Scope)) if (Reload || !configDictionary.ContainsKey(Scope))
{ {
if (dbContext == null) if (Database == null)
throw new InvalidOperationException("Cache-miss where Configuration Item requested from Cache-Only Configuration Context"); throw new InvalidOperationException("Cache-miss where Configuration Item requested from Cache-Only Configuration Context");
var newItems = dbContext.ConfigurationItems.Where(ci => ci.Scope == Scope).ToArray(); var newItems = Database.ConfigurationItems.Where(ci => ci.Scope == Scope).ToArray();
if (configDictionary.ContainsKey(Scope)) if (configDictionary.ContainsKey(Scope))
{ {
@@ -43,15 +43,15 @@ namespace Disco.Data.Configuration
} }
} }
} }
private static Dictionary<string, Dictionary<string, ConfigurationItem>> ConfigurationDictionary(DiscoDataContext dbContext, string IncludingScope) private static Dictionary<string, Dictionary<string, ConfigurationItem>> ConfigurationDictionary(DiscoDataContext Database, string IncludingScope)
{ {
LoadConfigurationItems(dbContext, IncludingScope, false); LoadConfigurationItems(Database, IncludingScope, false);
return configDictionary; return configDictionary;
} }
private static ConfigurationItem ConfigurationItem(DiscoDataContext dbContext, string Scope, string Key) private static ConfigurationItem ConfigurationItem(DiscoDataContext Database, string Scope, string Key)
{ {
Dictionary<string, ConfigurationItem> scopeDict = default(Dictionary<string, ConfigurationItem>); Dictionary<string, ConfigurationItem> scopeDict = default(Dictionary<string, ConfigurationItem>);
if (ConfigurationDictionary(dbContext, Scope).TryGetValue(Scope, out scopeDict)) if (ConfigurationDictionary(Database, Scope).TryGetValue(Scope, out scopeDict))
{ {
ConfigurationItem item = default(ConfigurationItem); ConfigurationItem item = default(ConfigurationItem);
if (scopeDict.TryGetValue(Key, out item)) if (scopeDict.TryGetValue(Key, out item))
@@ -59,42 +59,42 @@ namespace Disco.Data.Configuration
} }
return null; return null;
} }
private static List<ConfigurationItem> ConfigurationItems(DiscoDataContext dbContext, string IncludingScope) private static List<ConfigurationItem> ConfigurationItems(DiscoDataContext Database, string IncludingScope)
{ {
LoadConfigurationItems(dbContext, IncludingScope, false); LoadConfigurationItems(Database, IncludingScope, false);
return configurationItems; return configurationItems;
} }
#endregion #endregion
#region Public Helpers #region Public Helpers
internal static ValueType GetConfigurationValue<ValueType>(DiscoDataContext dbContext, string Scope, string Key, ValueType Default) internal static ValueType GetConfigurationValue<ValueType>(DiscoDataContext Database, string Scope, string Key, ValueType Default)
{ {
var ci = ConfigurationItem(dbContext, Scope, Key); var ci = ConfigurationItem(Database, Scope, Key);
if (ci == null) if (ci == null)
return Default; return Default;
else else
return (ValueType)Convert.ChangeType(ci.Value, typeof(ValueType)); return (ValueType)Convert.ChangeType(ci.Value, typeof(ValueType));
} }
internal static void SetConfigurationValue<ValueType>(DiscoDataContext dbContext, string Scope, string Key, ValueType Value) internal static void SetConfigurationValue<ValueType>(DiscoDataContext Database, string Scope, string Key, ValueType Value)
{ {
if (dbContext == null) if (Database == null)
throw new InvalidOperationException("Cannot save changes with a CacheOnly Context"); throw new InvalidOperationException("Cannot save changes with a CacheOnly Context");
var ci = ConfigurationItem(dbContext, Scope, Key); var ci = ConfigurationItem(Database, Scope, Key);
if (ci == null && Value != null) if (ci == null && Value != null)
{ {
lock (configurationItemsLock) lock (configurationItemsLock)
{ {
ci = ConfigurationItem(dbContext, Scope, Key); ci = ConfigurationItem(Database, Scope, Key);
if (ci == null) if (ci == null)
{ {
// Create Configuration Item // Create Configuration Item
ci = new ConfigurationItem() { Scope = Scope, Key = Key, Value = Value.ToString() }; ci = new ConfigurationItem() { Scope = Scope, Key = Key, Value = Value.ToString() };
// Add Item to DB & Internal Collections // Add Item to DB & Internal Collections
dbContext.ConfigurationItems.Add(ci); Database.ConfigurationItems.Add(ci);
ConfigurationItems(dbContext, Scope).Add(ci); ConfigurationItems(Database, Scope).Add(ci);
ConfigurationDictionary(dbContext, Scope)[Scope].Add(Key, ci); ConfigurationDictionary(Database, Scope)[Scope].Add(Key, ci);
ci = null; ci = null;
} }
} }
@@ -103,17 +103,17 @@ namespace Disco.Data.Configuration
{ {
lock (configurationItemsLock) lock (configurationItemsLock)
{ {
var entityInfo = dbContext.Entry(ci); var entityInfo = Database.Entry(ci);
if (entityInfo.State == System.Data.EntityState.Detached) if (entityInfo.State == System.Data.EntityState.Detached)
{ {
// Reload Scope from DB // Reload Scope from DB
LoadConfigurationItems(dbContext, Scope, true); LoadConfigurationItems(Database, Scope, true);
ci = ConfigurationItem(dbContext, Scope, Key); ci = ConfigurationItem(Database, Scope, Key);
} }
if (Value == null) if (Value == null)
{ {
dbContext.ConfigurationItems.Remove(ci); Database.ConfigurationItems.Remove(ci);
configurationItems.Remove(ci); configurationItems.Remove(ci);
configDictionary[Scope].Remove(Key); configDictionary[Scope].Remove(Key);
} }
@@ -125,9 +125,9 @@ namespace Disco.Data.Configuration
} }
} }
internal static List<ConfigurationItem> GetConfigurationItems(DiscoDataContext dbContext, string Scope) internal static List<ConfigurationItem> GetConfigurationItems(DiscoDataContext Database, string Scope)
{ {
return ConfigurationDictionary(dbContext, Scope)[Scope].Values.ToList(); return ConfigurationDictionary(Database, Scope)[Scope].Values.ToList();
} }
internal static string ObsfucateValue(string Value) internal static string ObsfucateValue(string Value)
@@ -8,7 +8,7 @@ namespace Disco.Data.Configuration.Modules
{ {
public class BootstrapperConfiguration : ConfigurationBase public class BootstrapperConfiguration : ConfigurationBase
{ {
public BootstrapperConfiguration(DiscoDataContext dbContext) : base(dbContext) { } public BootstrapperConfiguration(DiscoDataContext Database) : base(Database) { }
public override string Scope public override string Scope
{ {
@@ -9,7 +9,7 @@ namespace Disco.Data.Configuration.Modules
{ {
public class DeviceProfilesConfiguration : ConfigurationBase public class DeviceProfilesConfiguration : ConfigurationBase
{ {
public DeviceProfilesConfiguration(DiscoDataContext dbContext) : base(dbContext) { } public DeviceProfilesConfiguration(DiscoDataContext Database) : base(Database) { }
public override string Scope { get { return "DeviceProfiles"; } } public override string Scope { get { return "DeviceProfiles"; } }
@@ -11,7 +11,7 @@ namespace Disco.Data.Configuration.Modules
{ {
public class OrganisationAddressesConfiguration : ConfigurationBase public class OrganisationAddressesConfiguration : ConfigurationBase
{ {
public OrganisationAddressesConfiguration(DiscoDataContext dbContext) : base(dbContext) { } public OrganisationAddressesConfiguration(DiscoDataContext Database) : base(Database) { }
public override string Scope { get { return "OrganisationAddresses"; } } public override string Scope { get { return "OrganisationAddresses"; } }
@@ -13,13 +13,13 @@ namespace Disco.Data.Configuration
{ {
public class SystemConfiguration : ConfigurationBase public class SystemConfiguration : ConfigurationBase
{ {
public SystemConfiguration(DiscoDataContext dbContext) public SystemConfiguration(DiscoDataContext Database)
: base(dbContext) : base(Database)
{ {
// Init Modules // Init Modules
this.moduleBootstrapperConfiguration = new Lazy<Modules.BootstrapperConfiguration>(() => new Modules.BootstrapperConfiguration(dbContext)); this.moduleBootstrapperConfiguration = new Lazy<Modules.BootstrapperConfiguration>(() => new Modules.BootstrapperConfiguration(Database));
this.moduleDeviceProfilesConfiguration = new Lazy<Modules.DeviceProfilesConfiguration>(() => new Modules.DeviceProfilesConfiguration(dbContext)); this.moduleDeviceProfilesConfiguration = new Lazy<Modules.DeviceProfilesConfiguration>(() => new Modules.DeviceProfilesConfiguration(Database));
this.moduleOrganisationAddressesConfiguration = new Lazy<Modules.OrganisationAddressesConfiguration>(() => new Modules.OrganisationAddressesConfiguration(dbContext)); this.moduleOrganisationAddressesConfiguration = new Lazy<Modules.OrganisationAddressesConfiguration>(() => new Modules.OrganisationAddressesConfiguration(Database));
} }
#region Configuration Modules #region Configuration Modules
+8 -2
View File
@@ -113,6 +113,10 @@
<Compile Include="Migrations\201309050648129_DBv8.Designer.cs"> <Compile Include="Migrations\201309050648129_DBv8.Designer.cs">
<DependentUpon>201309050648129_DBv8.cs</DependentUpon> <DependentUpon>201309050648129_DBv8.cs</DependentUpon>
</Compile> </Compile>
<Compile Include="Migrations\201310010352238_DBv9.cs" />
<Compile Include="Migrations\201310010352238_DBv9.Designer.cs">
<DependentUpon>201310010352238_DBv9.cs</DependentUpon>
</Compile>
<Compile Include="Migrations\Configuration.cs" /> <Compile Include="Migrations\Configuration.cs" />
<Compile Include="Migrations\DiscoDataMigrator.cs" /> <Compile Include="Migrations\DiscoDataMigrator.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
@@ -123,7 +127,6 @@
</Compile> </Compile>
<Compile Include="Repository\DiscoDatabaseConnectionFactory.cs" /> <Compile Include="Repository\DiscoDatabaseConnectionFactory.cs" />
<Compile Include="Repository\DiscoDataContext.cs" /> <Compile Include="Repository\DiscoDataContext.cs" />
<Compile Include="Repository\DiscoDataContextInitializer.cs" />
<Compile Include="Repository\DiscoDataSeeder.cs" /> <Compile Include="Repository\DiscoDataSeeder.cs" />
<Compile Include="Repository\Monitor\RepositoryMonitor.cs" /> <Compile Include="Repository\Monitor\RepositoryMonitor.cs" />
<Compile Include="Repository\Monitor\RepositoryMonitorEvent.cs" /> <Compile Include="Repository\Monitor\RepositoryMonitorEvent.cs" />
@@ -153,6 +156,9 @@
<EmbeddedResource Include="Migrations\201309050648129_DBv8.resx"> <EmbeddedResource Include="Migrations\201309050648129_DBv8.resx">
<DependentUpon>201309050648129_DBv8.cs</DependentUpon> <DependentUpon>201309050648129_DBv8.cs</DependentUpon>
</EmbeddedResource> </EmbeddedResource>
<EmbeddedResource Include="Migrations\201310010352238_DBv9.resx">
<DependentUpon>201310010352238_DBv9.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx"> <EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator> <Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput> <LastGenOutput>Resources.Designer.cs</LastGenOutput>
@@ -166,7 +172,7 @@
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<ProjectExtensions> <ProjectExtensions>
<VisualStudio> <VisualStudio>
<UserProperties BuildVersion_UpdateFileVersion="True" BuildVersion_UpdateAssemblyVersion="True" BuildVersion_BuildVersioningStyle="None.DeltaBaseYear.MonthAndDayStamp.TimeStamp" BuildVersion_StartDate="2011/7/1" BuildVersion_DetectChanges="False" BuildVersion_UseGlobalSettings="False" BuildVersion_BuildAction="Both" /> <UserProperties BuildVersion_BuildAction="Both" BuildVersion_UseGlobalSettings="False" BuildVersion_DetectChanges="False" BuildVersion_StartDate="2011/7/1" BuildVersion_BuildVersioningStyle="None.DeltaBaseYear.MonthAndDayStamp.TimeStamp" BuildVersion_UpdateAssemblyVersion="True" BuildVersion_UpdateFileVersion="True" />
</VisualStudio> </VisualStudio>
</ProjectExtensions> </ProjectExtensions>
<Import Project="$(SolutionDir)\.nuget\nuget.targets" /> <Import Project="$(SolutionDir)\.nuget\nuget.targets" />
+27
View File
@@ -0,0 +1,27 @@
// <auto-generated />
namespace Disco.Data.Migrations
{
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
public sealed partial class DBv9 : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(DBv9));
string IMigrationMetadata.Id
{
get { return "201310010352238_DBv9"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
@@ -0,0 +1,30 @@
namespace Disco.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class DBv9 : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.AuthorizationRoles",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 100),
SubjectIds = c.String(),
ClaimsJson = c.String(),
})
.PrimaryKey(t => t.Id);
DropColumn("dbo.Users", "Type");
}
public override void Down()
{
AddColumn("dbo.Users", "Type", c => c.String(maxLength: 8));
DropTable("dbo.AuthorizationRoles");
}
}
}
File diff suppressed because one or more lines are too long
+2 -2
View File
@@ -13,9 +13,9 @@ namespace Disco.Data.Migrations
AutomaticMigrationsEnabled = false; AutomaticMigrationsEnabled = false;
} }
protected override void Seed(DiscoDataContext context) protected override void Seed(DiscoDataContext Database)
{ {
context.SeedDatabase(); Database.SeedDatabase();
} }
} }
} }
+3 -3
View File
@@ -49,12 +49,12 @@ namespace Disco.Data.Migrations
public static void SeedDatabase() public static void SeedDatabase()
{ {
// Seed/Update Database // Seed/Update Database
using (DiscoDataContext dbContext = new DiscoDataContext()) using (DiscoDataContext database = new DiscoDataContext())
{ {
dbContext.SeedDatabase(); database.SeedDatabase();
try try
{ {
dbContext.SaveChanges(); database.SaveChanges();
} }
catch (Exception ex) catch (Exception ex)
{ {
+2 -2
View File
@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers // You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below: // by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")] // [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.0725.2249")] [assembly: AssemblyVersion("1.2.1001.1541")]
[assembly: AssemblyFileVersion("1.2.0725.2249")] [assembly: AssemblyFileVersion("1.2.1001.1541")]
@@ -23,6 +23,7 @@ namespace Disco.Data.Repository
public virtual DbSet<User> Users { get; set; } public virtual DbSet<User> Users { get; set; }
public virtual DbSet<UserAttachment> UserAttachments { get; set; } public virtual DbSet<UserAttachment> UserAttachments { get; set; }
public virtual DbSet<AuthorizationRole> AuthorizationRoles { get; set; }
public virtual DbSet<DeviceUserAssignment> DeviceUserAssignments { get; set; } public virtual DbSet<DeviceUserAssignment> DeviceUserAssignments { get; set; }
@@ -1,19 +0,0 @@
// Shouldn't Need this => Moved to Entity Migrations...
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Data.Entity;
//namespace Disco.Data.Repository
//{
// class DiscoDataContextInitializer : CreateDatabaseIfNotExists<DiscoDataContext>
// {
// protected override void Seed(DiscoDataContext context)
// {
// context.SeedDatabase();
// context.SaveChanges();
// }
// }
//}
+154 -182
View File
@@ -8,224 +8,224 @@ namespace Disco.Data.Repository
{ {
public static class DiscoDataSeeder public static class DiscoDataSeeder
{ {
public static void SeedDatabase(this DiscoDataContext context) public static void SeedDatabase(this DiscoDataContext Database)
{ {
context.SeedDeploymentId(); Database.SeedDeploymentId();
context.SeedDeviceModels(); Database.SeedDeviceModels();
context.SeedDeviceProfiles(); Database.SeedDeviceProfiles();
context.SeedJobTypes(); Database.SeedJobTypes();
context.SeedJobSubTypes(); Database.SeedJobSubTypes();
} }
public static void SeedDeploymentId(this DiscoDataContext context) public static void SeedDeploymentId(this DiscoDataContext Database)
{ {
if (context.ConfigurationItems.Count(ci => ci.Scope == "System" && ci.Key == "DeploymentId") == 0) if (Database.ConfigurationItems.Count(ci => ci.Scope == "System" && ci.Key == "DeploymentId") == 0)
{ {
var deploymentId = Guid.NewGuid().ToString("D"); var deploymentId = Guid.NewGuid().ToString("D");
context.ConfigurationItems.Add(new ConfigurationItem { Scope = "System", Key = "DeploymentId", Value = deploymentId }); Database.ConfigurationItems.Add(new ConfigurationItem { Scope = "System", Key = "DeploymentId", Value = deploymentId });
} }
} }
public static void SeedJobTypes(this DiscoDataContext context) public static void SeedJobTypes(this DiscoDataContext Database)
{ {
if (context.JobTypes.Count() == 0) if (Database.JobTypes.Count() == 0)
{ {
context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.HWar, Description = "Hardware - Warranty" }); Database.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.HWar, Description = "Hardware - Warranty" });
context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.HNWar, Description = "Hardware - Non-Warranty" }); Database.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.HNWar, Description = "Hardware - Non-Warranty" });
context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.HMisc, Description = "Hardware - Misc" }); Database.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.HMisc, Description = "Hardware - Misc" });
context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.SImg, Description = "Software - Reimage" }); Database.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.SImg, Description = "Software - Reimage" });
context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.SApp, Description = "Software - Application" }); Database.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.SApp, Description = "Software - Application" });
context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.SOS, Description = "Software - Operating System" }); Database.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.SOS, Description = "Software - Operating System" });
} }
// 2012-05-22 // 2012-05-22
#region "User Management" Added #region "User Management" Added
if (context.JobTypes.Count(jt => jt.Id == JobType.JobTypeIds.UMgmt) == 0) if (Database.JobTypes.Count(jt => jt.Id == JobType.JobTypeIds.UMgmt) == 0)
context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.UMgmt, Description = "User - Management" }); Database.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.UMgmt, Description = "User - Management" });
#endregion #endregion
// End // End
} }
public static void SeedDeviceModels(this DiscoDataContext context) public static void SeedDeviceModels(this DiscoDataContext Database)
{ {
if (context.DeviceModels.Count() == 0) if (Database.DeviceModels.Count() == 0)
{ {
context.DeviceModels.Add(new DeviceModel { Manufacturer = "Unknown", Model = "Unknown", Description = "Unknown Device Model" }); Database.DeviceModels.Add(new DeviceModel { Manufacturer = "Unknown", Model = "Unknown", Description = "Unknown Device Model" });
} }
UpdateDeviceModelConfiguration(context); UpdateDeviceModelConfiguration(Database);
// Removed: 2013-01-14 G# // Removed: 2013-01-14 G#
//UpdateDeviceModelImageStorage(context); //UpdateDeviceModelImageStorage(context);
// Added: 2013-02-07 G# // Added: 2013-02-07 G#
UpdateDeviceModelDuplicates(context); UpdateDeviceModelDuplicates(Database);
} }
public static void SeedDeviceProfiles(this DiscoDataContext context) public static void SeedDeviceProfiles(this DiscoDataContext Database)
{ {
if (context.DeviceProfiles.Count() == 0) if (Database.DeviceProfiles.Count() == 0)
{ {
context.DeviceProfiles.Add(new DeviceProfile { ShortName = "WS", Name = "Default", Description = "Initial Default Workstation Profile", ComputerNameTemplate = "DeviceProfile.ShortName + ''-'' + SerialNumber" }); Database.DeviceProfiles.Add(new DeviceProfile { ShortName = "WS", Name = "Default", Description = "Initial Default Workstation Profile", ComputerNameTemplate = "DeviceProfile.ShortName + ''-'' + SerialNumber" });
} }
} }
public static void SeedJobSubTypes(this DiscoDataContext context) public static void SeedJobSubTypes(this DiscoDataContext Database)
{ {
if (context.JobSubTypes.Count() == 0) if (Database.JobSubTypes.Count() == 0)
{ {
context.JobSubTypes.Add(new JobSubType { Id = "Bag", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bag" }); Database.JobSubTypes.Add(new JobSubType { Id = "Bag", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bag" });
context.JobSubTypes.Add(new JobSubType { Id = "Battery", JobTypeId = JobType.JobTypeIds.HWar, Description = "Battery" }); Database.JobSubTypes.Add(new JobSubType { Id = "Battery", JobTypeId = JobType.JobTypeIds.HWar, Description = "Battery" });
context.JobSubTypes.Add(new JobSubType { Id = "BezelCaseBottom", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Case Bottom" }); Database.JobSubTypes.Add(new JobSubType { Id = "BezelCaseBottom", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Case Bottom" });
context.JobSubTypes.Add(new JobSubType { Id = "BezelCaseTop", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Case Top" }); Database.JobSubTypes.Add(new JobSubType { Id = "BezelCaseTop", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Case Top" });
context.JobSubTypes.Add(new JobSubType { Id = "BezelScreenInner", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Screen Inner" }); Database.JobSubTypes.Add(new JobSubType { Id = "BezelScreenInner", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Screen Inner" });
context.JobSubTypes.Add(new JobSubType { Id = "BezelScreenTop", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Screen Top" }); Database.JobSubTypes.Add(new JobSubType { Id = "BezelScreenTop", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Screen Top" });
context.JobSubTypes.Add(new JobSubType { Id = "BluetoothAdapter", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bluetooth Adapter" }); Database.JobSubTypes.Add(new JobSubType { Id = "BluetoothAdapter", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bluetooth Adapter" });
context.JobSubTypes.Add(new JobSubType { Id = "CPU", JobTypeId = JobType.JobTypeIds.HWar, Description = "CPU" }); Database.JobSubTypes.Add(new JobSubType { Id = "CPU", JobTypeId = JobType.JobTypeIds.HWar, Description = "CPU" });
context.JobSubTypes.Add(new JobSubType { Id = "HardDrive", JobTypeId = JobType.JobTypeIds.HWar, Description = "Hard Drive" }); Database.JobSubTypes.Add(new JobSubType { Id = "HardDrive", JobTypeId = JobType.JobTypeIds.HWar, Description = "Hard Drive" });
context.JobSubTypes.Add(new JobSubType { Id = "Keyboard", JobTypeId = JobType.JobTypeIds.HWar, Description = "Keyboard" }); Database.JobSubTypes.Add(new JobSubType { Id = "Keyboard", JobTypeId = JobType.JobTypeIds.HWar, Description = "Keyboard" });
context.JobSubTypes.Add(new JobSubType { Id = "Motherboard", JobTypeId = JobType.JobTypeIds.HWar, Description = "Motherboard" }); Database.JobSubTypes.Add(new JobSubType { Id = "Motherboard", JobTypeId = JobType.JobTypeIds.HWar, Description = "Motherboard" });
context.JobSubTypes.Add(new JobSubType { Id = "Mouse", JobTypeId = JobType.JobTypeIds.HWar, Description = "Mouse/Track Pad" }); Database.JobSubTypes.Add(new JobSubType { Id = "Mouse", JobTypeId = JobType.JobTypeIds.HWar, Description = "Mouse/Track Pad" });
context.JobSubTypes.Add(new JobSubType { Id = "PowerAdapter", JobTypeId = JobType.JobTypeIds.HWar, Description = "Power Adapter" }); Database.JobSubTypes.Add(new JobSubType { Id = "PowerAdapter", JobTypeId = JobType.JobTypeIds.HWar, Description = "Power Adapter" });
context.JobSubTypes.Add(new JobSubType { Id = "PowerCord", JobTypeId = JobType.JobTypeIds.HWar, Description = "Power Cord/Socket" }); Database.JobSubTypes.Add(new JobSubType { Id = "PowerCord", JobTypeId = JobType.JobTypeIds.HWar, Description = "Power Cord/Socket" });
context.JobSubTypes.Add(new JobSubType { Id = "RAM", JobTypeId = JobType.JobTypeIds.HWar, Description = "RAM" }); Database.JobSubTypes.Add(new JobSubType { Id = "RAM", JobTypeId = JobType.JobTypeIds.HWar, Description = "RAM" });
context.JobSubTypes.Add(new JobSubType { Id = "ReplacementDevice", JobTypeId = JobType.JobTypeIds.HWar, Description = "Replacement Device" }); Database.JobSubTypes.Add(new JobSubType { Id = "ReplacementDevice", JobTypeId = JobType.JobTypeIds.HWar, Description = "Replacement Device" });
context.JobSubTypes.Add(new JobSubType { Id = "Screen", JobTypeId = JobType.JobTypeIds.HWar, Description = "Screen" }); Database.JobSubTypes.Add(new JobSubType { Id = "Screen", JobTypeId = JobType.JobTypeIds.HWar, Description = "Screen" });
context.JobSubTypes.Add(new JobSubType { Id = "Speakers", JobTypeId = JobType.JobTypeIds.HWar, Description = "Speakers" }); Database.JobSubTypes.Add(new JobSubType { Id = "Speakers", JobTypeId = JobType.JobTypeIds.HWar, Description = "Speakers" });
context.JobSubTypes.Add(new JobSubType { Id = "WebCamera", JobTypeId = JobType.JobTypeIds.HWar, Description = "Web Camera" }); Database.JobSubTypes.Add(new JobSubType { Id = "WebCamera", JobTypeId = JobType.JobTypeIds.HWar, Description = "Web Camera" });
context.JobSubTypes.Add(new JobSubType { Id = "WirelessAdapter", JobTypeId = JobType.JobTypeIds.HWar, Description = "Wireless Adapter" }); Database.JobSubTypes.Add(new JobSubType { Id = "WirelessAdapter", JobTypeId = JobType.JobTypeIds.HWar, Description = "Wireless Adapter" });
context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.HWar, Description = "Other" }); Database.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.HWar, Description = "Other" });
context.JobSubTypes.Add(new JobSubType { Id = "Bag", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bag" }); Database.JobSubTypes.Add(new JobSubType { Id = "Bag", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bag" });
context.JobSubTypes.Add(new JobSubType { Id = "Battery", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Battery" }); Database.JobSubTypes.Add(new JobSubType { Id = "Battery", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Battery" });
context.JobSubTypes.Add(new JobSubType { Id = "BezelCaseBottom", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Case Bottom" }); Database.JobSubTypes.Add(new JobSubType { Id = "BezelCaseBottom", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Case Bottom" });
context.JobSubTypes.Add(new JobSubType { Id = "BezelCaseTop", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Case Top" }); Database.JobSubTypes.Add(new JobSubType { Id = "BezelCaseTop", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Case Top" });
context.JobSubTypes.Add(new JobSubType { Id = "BezelScreenInner", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Screen Inner" }); Database.JobSubTypes.Add(new JobSubType { Id = "BezelScreenInner", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Screen Inner" });
context.JobSubTypes.Add(new JobSubType { Id = "BezelScreenTop", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Screen Top" }); Database.JobSubTypes.Add(new JobSubType { Id = "BezelScreenTop", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Screen Top" });
context.JobSubTypes.Add(new JobSubType { Id = "BluetoothAdapter", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bluetooth Adapter" }); Database.JobSubTypes.Add(new JobSubType { Id = "BluetoothAdapter", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bluetooth Adapter" });
context.JobSubTypes.Add(new JobSubType { Id = "CPU", JobTypeId = JobType.JobTypeIds.HNWar, Description = "CPU" }); Database.JobSubTypes.Add(new JobSubType { Id = "CPU", JobTypeId = JobType.JobTypeIds.HNWar, Description = "CPU" });
context.JobSubTypes.Add(new JobSubType { Id = "HardDrive", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Hard Drive" }); Database.JobSubTypes.Add(new JobSubType { Id = "HardDrive", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Hard Drive" });
context.JobSubTypes.Add(new JobSubType { Id = "Keyboard", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Keyboard" }); Database.JobSubTypes.Add(new JobSubType { Id = "Keyboard", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Keyboard" });
context.JobSubTypes.Add(new JobSubType { Id = "Motherboard", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Motherboard" }); Database.JobSubTypes.Add(new JobSubType { Id = "Motherboard", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Motherboard" });
context.JobSubTypes.Add(new JobSubType { Id = "Mouse", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Mouse/Track Pad" }); Database.JobSubTypes.Add(new JobSubType { Id = "Mouse", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Mouse/Track Pad" });
context.JobSubTypes.Add(new JobSubType { Id = "PowerAdapter", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Power Adapter" }); Database.JobSubTypes.Add(new JobSubType { Id = "PowerAdapter", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Power Adapter" });
context.JobSubTypes.Add(new JobSubType { Id = "PowerCord", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Power Cord/Socket" }); Database.JobSubTypes.Add(new JobSubType { Id = "PowerCord", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Power Cord/Socket" });
context.JobSubTypes.Add(new JobSubType { Id = "RAM", JobTypeId = JobType.JobTypeIds.HNWar, Description = "RAM" }); Database.JobSubTypes.Add(new JobSubType { Id = "RAM", JobTypeId = JobType.JobTypeIds.HNWar, Description = "RAM" });
context.JobSubTypes.Add(new JobSubType { Id = "ReplacementDevice", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Replacement Device" }); Database.JobSubTypes.Add(new JobSubType { Id = "ReplacementDevice", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Replacement Device" });
context.JobSubTypes.Add(new JobSubType { Id = "Screen", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Screen" }); Database.JobSubTypes.Add(new JobSubType { Id = "Screen", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Screen" });
context.JobSubTypes.Add(new JobSubType { Id = "Speakers", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Speakers" }); Database.JobSubTypes.Add(new JobSubType { Id = "Speakers", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Speakers" });
context.JobSubTypes.Add(new JobSubType { Id = "WebCamera", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Web Camera" }); Database.JobSubTypes.Add(new JobSubType { Id = "WebCamera", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Web Camera" });
context.JobSubTypes.Add(new JobSubType { Id = "WirelessAdapter", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Wireless Adapter" }); Database.JobSubTypes.Add(new JobSubType { Id = "WirelessAdapter", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Wireless Adapter" });
context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Other" }); Database.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Other" });
context.JobSubTypes.Add(new JobSubType { Id = "ExternalHardDrive", JobTypeId = JobType.JobTypeIds.HMisc, Description = "External Hard Drive" }); Database.JobSubTypes.Add(new JobSubType { Id = "ExternalHardDrive", JobTypeId = JobType.JobTypeIds.HMisc, Description = "External Hard Drive" });
context.JobSubTypes.Add(new JobSubType { Id = "IWB", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Interactive Whiteboard" }); Database.JobSubTypes.Add(new JobSubType { Id = "IWB", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Interactive Whiteboard" });
context.JobSubTypes.Add(new JobSubType { Id = "InternetDongle", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Internet Dongle" }); Database.JobSubTypes.Add(new JobSubType { Id = "InternetDongle", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Internet Dongle" });
context.JobSubTypes.Add(new JobSubType { Id = "Keyboard", JobTypeId = JobType.JobTypeIds.HMisc, Description = "External Keyboard" }); Database.JobSubTypes.Add(new JobSubType { Id = "Keyboard", JobTypeId = JobType.JobTypeIds.HMisc, Description = "External Keyboard" });
context.JobSubTypes.Add(new JobSubType { Id = "MobilePhone", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Mobile Phone" }); Database.JobSubTypes.Add(new JobSubType { Id = "MobilePhone", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Mobile Phone" });
context.JobSubTypes.Add(new JobSubType { Id = "Mouse", JobTypeId = JobType.JobTypeIds.HMisc, Description = "External Mouse" }); Database.JobSubTypes.Add(new JobSubType { Id = "Mouse", JobTypeId = JobType.JobTypeIds.HMisc, Description = "External Mouse" });
context.JobSubTypes.Add(new JobSubType { Id = "MP3Player", JobTypeId = JobType.JobTypeIds.HMisc, Description = "MP3 Player" }); Database.JobSubTypes.Add(new JobSubType { Id = "MP3Player", JobTypeId = JobType.JobTypeIds.HMisc, Description = "MP3 Player" });
context.JobSubTypes.Add(new JobSubType { Id = "PrinterScanner", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Printer/Scanner" }); Database.JobSubTypes.Add(new JobSubType { Id = "PrinterScanner", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Printer/Scanner" });
context.JobSubTypes.Add(new JobSubType { Id = "Projector", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Projector" }); Database.JobSubTypes.Add(new JobSubType { Id = "Projector", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Projector" });
context.JobSubTypes.Add(new JobSubType { Id = "USBFlashDrive", JobTypeId = JobType.JobTypeIds.HMisc, Description = "USB Flash Drive" }); Database.JobSubTypes.Add(new JobSubType { Id = "USBFlashDrive", JobTypeId = JobType.JobTypeIds.HMisc, Description = "USB Flash Drive" });
context.JobSubTypes.Add(new JobSubType { Id = "WebCamera", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Web Camera" }); Database.JobSubTypes.Add(new JobSubType { Id = "WebCamera", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Web Camera" });
context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Other" }); Database.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Other" });
context.JobSubTypes.Add(new JobSubType { Id = "ContentIllegal", JobTypeId = JobType.JobTypeIds.SImg, Description = "Content - Illegal" }); Database.JobSubTypes.Add(new JobSubType { Id = "ContentIllegal", JobTypeId = JobType.JobTypeIds.SImg, Description = "Content - Illegal" });
context.JobSubTypes.Add(new JobSubType { Id = "ContentInappropriate", JobTypeId = JobType.JobTypeIds.SImg, Description = "Content - Inappropriate" }); Database.JobSubTypes.Add(new JobSubType { Id = "ContentInappropriate", JobTypeId = JobType.JobTypeIds.SImg, Description = "Content - Inappropriate" });
context.JobSubTypes.Add(new JobSubType { Id = "CorruptOS", JobTypeId = JobType.JobTypeIds.SImg, Description = "Corrupt Operating System" }); Database.JobSubTypes.Add(new JobSubType { Id = "CorruptOS", JobTypeId = JobType.JobTypeIds.SImg, Description = "Corrupt Operating System" });
context.JobSubTypes.Add(new JobSubType { Id = "HardwareChanges", JobTypeId = JobType.JobTypeIds.SImg, Description = "Hardware Changes" }); Database.JobSubTypes.Add(new JobSubType { Id = "HardwareChanges", JobTypeId = JobType.JobTypeIds.SImg, Description = "Hardware Changes" });
context.JobSubTypes.Add(new JobSubType { Id = "Malware", JobTypeId = JobType.JobTypeIds.SImg, Description = "Malware" }); Database.JobSubTypes.Add(new JobSubType { Id = "Malware", JobTypeId = JobType.JobTypeIds.SImg, Description = "Malware" });
context.JobSubTypes.Add(new JobSubType { Id = "Performance", JobTypeId = JobType.JobTypeIds.SImg, Description = "Performance" }); Database.JobSubTypes.Add(new JobSubType { Id = "Performance", JobTypeId = JobType.JobTypeIds.SImg, Description = "Performance" });
context.JobSubTypes.Add(new JobSubType { Id = "UserRequest", JobTypeId = JobType.JobTypeIds.SImg, Description = "User Request" }); Database.JobSubTypes.Add(new JobSubType { Id = "UserRequest", JobTypeId = JobType.JobTypeIds.SImg, Description = "User Request" });
context.JobSubTypes.Add(new JobSubType { Id = "UpdatedImage", JobTypeId = JobType.JobTypeIds.SImg, Description = "Updated Image" }); Database.JobSubTypes.Add(new JobSubType { Id = "UpdatedImage", JobTypeId = JobType.JobTypeIds.SImg, Description = "Updated Image" });
context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.SImg, Description = "Other" }); Database.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.SImg, Description = "Other" });
context.JobSubTypes.Add(new JobSubType { Id = "CurriculumTool", JobTypeId = JobType.JobTypeIds.SApp, Description = "Curriculum Tool" }); Database.JobSubTypes.Add(new JobSubType { Id = "CurriculumTool", JobTypeId = JobType.JobTypeIds.SApp, Description = "Curriculum Tool" });
context.JobSubTypes.Add(new JobSubType { Id = "GamingEntertainment", JobTypeId = JobType.JobTypeIds.SApp, Description = "Gaming/Entertainment" }); Database.JobSubTypes.Add(new JobSubType { Id = "GamingEntertainment", JobTypeId = JobType.JobTypeIds.SApp, Description = "Gaming/Entertainment" });
context.JobSubTypes.Add(new JobSubType { Id = "ImageManipulation", JobTypeId = JobType.JobTypeIds.SApp, Description = "Image Manipulation" }); Database.JobSubTypes.Add(new JobSubType { Id = "ImageManipulation", JobTypeId = JobType.JobTypeIds.SApp, Description = "Image Manipulation" });
context.JobSubTypes.Add(new JobSubType { Id = "MultimediaPlayback", JobTypeId = JobType.JobTypeIds.SApp, Description = "Multimedia Playback" }); Database.JobSubTypes.Add(new JobSubType { Id = "MultimediaPlayback", JobTypeId = JobType.JobTypeIds.SApp, Description = "Multimedia Playback" });
context.JobSubTypes.Add(new JobSubType { Id = "Presentation", JobTypeId = JobType.JobTypeIds.SApp, Description = "Presentation" }); Database.JobSubTypes.Add(new JobSubType { Id = "Presentation", JobTypeId = JobType.JobTypeIds.SApp, Description = "Presentation" });
context.JobSubTypes.Add(new JobSubType { Id = "Spreadsheet", JobTypeId = JobType.JobTypeIds.SApp, Description = "Spreadsheet" }); Database.JobSubTypes.Add(new JobSubType { Id = "Spreadsheet", JobTypeId = JobType.JobTypeIds.SApp, Description = "Spreadsheet" });
context.JobSubTypes.Add(new JobSubType { Id = "StaffTool", JobTypeId = JobType.JobTypeIds.SApp, Description = "Staff Tool" }); Database.JobSubTypes.Add(new JobSubType { Id = "StaffTool", JobTypeId = JobType.JobTypeIds.SApp, Description = "Staff Tool" });
context.JobSubTypes.Add(new JobSubType { Id = "StudentReporting", JobTypeId = JobType.JobTypeIds.SApp, Description = "Student Reporting" }); Database.JobSubTypes.Add(new JobSubType { Id = "StudentReporting", JobTypeId = JobType.JobTypeIds.SApp, Description = "Student Reporting" });
context.JobSubTypes.Add(new JobSubType { Id = "VideoEditing", JobTypeId = JobType.JobTypeIds.SApp, Description = "Video Editing" }); Database.JobSubTypes.Add(new JobSubType { Id = "VideoEditing", JobTypeId = JobType.JobTypeIds.SApp, Description = "Video Editing" });
context.JobSubTypes.Add(new JobSubType { Id = "WebBrowser", JobTypeId = JobType.JobTypeIds.SApp, Description = "Web Browser" }); Database.JobSubTypes.Add(new JobSubType { Id = "WebBrowser", JobTypeId = JobType.JobTypeIds.SApp, Description = "Web Browser" });
context.JobSubTypes.Add(new JobSubType { Id = "WebBrowserPlugin", JobTypeId = JobType.JobTypeIds.SApp, Description = "Web Browser Plugin" }); Database.JobSubTypes.Add(new JobSubType { Id = "WebBrowserPlugin", JobTypeId = JobType.JobTypeIds.SApp, Description = "Web Browser Plugin" });
context.JobSubTypes.Add(new JobSubType { Id = "WordProcessing", JobTypeId = JobType.JobTypeIds.SApp, Description = "Word Processing" }); Database.JobSubTypes.Add(new JobSubType { Id = "WordProcessing", JobTypeId = JobType.JobTypeIds.SApp, Description = "Word Processing" });
context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.SApp, Description = "Other" }); Database.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.SApp, Description = "Other" });
context.JobSubTypes.Add(new JobSubType { Id = "Appearance", JobTypeId = JobType.JobTypeIds.SOS, Description = "Appearance & Personalisation" }); Database.JobSubTypes.Add(new JobSubType { Id = "Appearance", JobTypeId = JobType.JobTypeIds.SOS, Description = "Appearance & Personalisation" });
context.JobSubTypes.Add(new JobSubType { Id = "DisplaySettings", JobTypeId = JobType.JobTypeIds.SOS, Description = "Display Settings" }); Database.JobSubTypes.Add(new JobSubType { Id = "DisplaySettings", JobTypeId = JobType.JobTypeIds.SOS, Description = "Display Settings" });
context.JobSubTypes.Add(new JobSubType { Id = "DriversIWB", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - Interactive Whiteboard" }); Database.JobSubTypes.Add(new JobSubType { Id = "DriversIWB", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - Interactive Whiteboard" });
context.JobSubTypes.Add(new JobSubType { Id = "DriversPrintScan", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - Printers/Scanners" }); Database.JobSubTypes.Add(new JobSubType { Id = "DriversPrintScan", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - Printers/Scanners" });
context.JobSubTypes.Add(new JobSubType { Id = "DriversSystem", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - System" }); Database.JobSubTypes.Add(new JobSubType { Id = "DriversSystem", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - System" });
context.JobSubTypes.Add(new JobSubType { Id = "DriversOther", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - Other" }); Database.JobSubTypes.Add(new JobSubType { Id = "DriversOther", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - Other" });
context.JobSubTypes.Add(new JobSubType { Id = "Group Policy", JobTypeId = JobType.JobTypeIds.SOS, Description = "Group Policy" }); Database.JobSubTypes.Add(new JobSubType { Id = "Group Policy", JobTypeId = JobType.JobTypeIds.SOS, Description = "Group Policy" });
context.JobSubTypes.Add(new JobSubType { Id = "KeyboardMouseConfig", JobTypeId = JobType.JobTypeIds.SOS, Description = "Keyboard/Mouse Configuration" }); Database.JobSubTypes.Add(new JobSubType { Id = "KeyboardMouseConfig", JobTypeId = JobType.JobTypeIds.SOS, Description = "Keyboard/Mouse Configuration" });
context.JobSubTypes.Add(new JobSubType { Id = "MalwareProtection", JobTypeId = JobType.JobTypeIds.SOS, Description = "Malware Protection" }); Database.JobSubTypes.Add(new JobSubType { Id = "MalwareProtection", JobTypeId = JobType.JobTypeIds.SOS, Description = "Malware Protection" });
context.JobSubTypes.Add(new JobSubType { Id = "NetworkDrives", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network Drives" }); Database.JobSubTypes.Add(new JobSubType { Id = "NetworkDrives", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network Drives" });
context.JobSubTypes.Add(new JobSubType { Id = "NetworkWired", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network - Wired" }); Database.JobSubTypes.Add(new JobSubType { Id = "NetworkWired", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network - Wired" });
context.JobSubTypes.Add(new JobSubType { Id = "NetworkWireless", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network - Wireless" }); Database.JobSubTypes.Add(new JobSubType { Id = "NetworkWireless", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network - Wireless" });
context.JobSubTypes.Add(new JobSubType { Id = "NetworkOther", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network - Other" }); Database.JobSubTypes.Add(new JobSubType { Id = "NetworkOther", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network - Other" });
context.JobSubTypes.Add(new JobSubType { Id = "PatchUpdate", JobTypeId = JobType.JobTypeIds.SOS, Description = "Patches/Updates" }); Database.JobSubTypes.Add(new JobSubType { Id = "PatchUpdate", JobTypeId = JobType.JobTypeIds.SOS, Description = "Patches/Updates" });
context.JobSubTypes.Add(new JobSubType { Id = "PowerManagement", JobTypeId = JobType.JobTypeIds.SOS, Description = "Power Management" }); Database.JobSubTypes.Add(new JobSubType { Id = "PowerManagement", JobTypeId = JobType.JobTypeIds.SOS, Description = "Power Management" });
context.JobSubTypes.Add(new JobSubType { Id = "PrintersScanners", JobTypeId = JobType.JobTypeIds.SOS, Description = "Printers/Scanners" }); Database.JobSubTypes.Add(new JobSubType { Id = "PrintersScanners", JobTypeId = JobType.JobTypeIds.SOS, Description = "Printers/Scanners" });
context.JobSubTypes.Add(new JobSubType { Id = "SoundConfig", JobTypeId = JobType.JobTypeIds.SOS, Description = "Sound Configuration" }); Database.JobSubTypes.Add(new JobSubType { Id = "SoundConfig", JobTypeId = JobType.JobTypeIds.SOS, Description = "Sound Configuration" });
context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.SOS, Description = "Other" }); Database.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.SOS, Description = "Other" });
} }
// Feature Request 2012-04-27 by Elijah: https://disco.uservoice.com/forums/159707-feedback/suggestions/2803945-customisable-job-sub-types // Feature Request 2012-04-27 by Elijah: https://disco.uservoice.com/forums/159707-feedback/suggestions/2803945-customisable-job-sub-types
#region "Optical Drive" Added #region "Optical Drive" Added
if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "OpticalDrive") == 0) if (Database.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "OpticalDrive") == 0)
context.JobSubTypes.Add(new JobSubType { Id = "OpticalDrive", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Optical Drive" }); Database.JobSubTypes.Add(new JobSubType { Id = "OpticalDrive", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Optical Drive" });
if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HWar && jst.Id == "OpticalDrive") == 0) if (Database.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HWar && jst.Id == "OpticalDrive") == 0)
context.JobSubTypes.Add(new JobSubType { Id = "OpticalDrive", JobTypeId = JobType.JobTypeIds.HWar, Description = "Optical Drive" }); Database.JobSubTypes.Add(new JobSubType { Id = "OpticalDrive", JobTypeId = JobType.JobTypeIds.HWar, Description = "Optical Drive" });
#endregion #endregion
// End Feature Request // End Feature Request
// 2012-05-22 // 2012-05-22
#region "User Management" Added #region "User Management" Added
if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.UMgmt) == 0) if (Database.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.UMgmt) == 0)
{ {
context.JobSubTypes.Add(new JobSubType { Id = JobSubType.UserManagementJobSubTypes.Infringement, JobTypeId = JobType.JobTypeIds.UMgmt, Description = JobSubType.UserManagementJobSubTypes.Infringement }); Database.JobSubTypes.Add(new JobSubType { Id = JobSubType.UserManagementJobSubTypes.Infringement, JobTypeId = JobType.JobTypeIds.UMgmt, Description = JobSubType.UserManagementJobSubTypes.Infringement });
context.JobSubTypes.Add(new JobSubType { Id = JobSubType.UserManagementJobSubTypes.Contact, JobTypeId = JobType.JobTypeIds.UMgmt, Description = JobSubType.UserManagementJobSubTypes.Contact }); Database.JobSubTypes.Add(new JobSubType { Id = JobSubType.UserManagementJobSubTypes.Contact, JobTypeId = JobType.JobTypeIds.UMgmt, Description = JobSubType.UserManagementJobSubTypes.Contact });
} }
#endregion #endregion
// End // End
// 2012-05-29 - Audits // 2012-05-29 - Audits
#region "Audit" Added #region "Audit" Added
if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HMisc && jst.Id == "Audit") == 0) if (Database.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HMisc && jst.Id == "Audit") == 0)
context.JobSubTypes.Add(new JobSubType { Id = "Audit", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Audit" }); Database.JobSubTypes.Add(new JobSubType { Id = "Audit", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Audit" });
if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.SApp && jst.Id == "Audit") == 0) if (Database.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.SApp && jst.Id == "Audit") == 0)
context.JobSubTypes.Add(new JobSubType { Id = "Audit", JobTypeId = JobType.JobTypeIds.SApp, Description = "Audit" }); Database.JobSubTypes.Add(new JobSubType { Id = "Audit", JobTypeId = JobType.JobTypeIds.SApp, Description = "Audit" });
#endregion #endregion
// End // End
// Feature Request 2012-06-16 by James: https://disco.uservoice.com/forums/159707-feedback/suggestions/3002911-add-in-microphone-in-hardware-warranty-and-non-war // Feature Request 2012-06-16 by James: https://disco.uservoice.com/forums/159707-feedback/suggestions/3002911-add-in-microphone-in-hardware-warranty-and-non-war
#region "Microphone" Added #region "Microphone" Added
if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "Microphone") == 0) if (Database.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "Microphone") == 0)
context.JobSubTypes.Add(new JobSubType { Id = "Microphone", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Microphone" }); Database.JobSubTypes.Add(new JobSubType { Id = "Microphone", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Microphone" });
if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HWar && jst.Id == "Microphone") == 0) if (Database.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HWar && jst.Id == "Microphone") == 0)
context.JobSubTypes.Add(new JobSubType { Id = "Microphone", JobTypeId = JobType.JobTypeIds.HWar, Description = "Microphone" }); Database.JobSubTypes.Add(new JobSubType { Id = "Microphone", JobTypeId = JobType.JobTypeIds.HWar, Description = "Microphone" });
#endregion #endregion
// End Feature Request // End Feature Request
// Feature Request 2013-05-16 by Michael // Feature Request 2013-05-16 by Michael
#region "Bezel - Case Bottom Load Cover" Added #region "Bezel - Case Bottom Load Cover" Added
if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "BezelCaseBottomCover") == 0) if (Database.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "BezelCaseBottomCover") == 0)
context.JobSubTypes.Add(new JobSubType { Id = "BezelCaseBottomCover", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Case Bottom Load Cover" }); Database.JobSubTypes.Add(new JobSubType { Id = "BezelCaseBottomCover", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Case Bottom Load Cover" });
if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HWar && jst.Id == "BezelCaseBottomCover") == 0) if (Database.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HWar && jst.Id == "BezelCaseBottomCover") == 0)
context.JobSubTypes.Add(new JobSubType { Id = "BezelCaseBottomCover", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Case Bottom Load Cover" }); Database.JobSubTypes.Add(new JobSubType { Id = "BezelCaseBottomCover", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Case Bottom Load Cover" });
#endregion #endregion
// End Feature Request // End Feature Request
// Feature Request https://github.com/garysharp/Disco/issues/1 // Feature Request https://github.com/garysharp/Disco/issues/1
#region "Device Stolen/Lost" #region "Device Stolen/Lost"
if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "DeviceStolen") == 0) if (Database.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "DeviceStolen") == 0)
context.JobSubTypes.Add(new JobSubType { Id = "DeviceStolen", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Device Stolen" }); Database.JobSubTypes.Add(new JobSubType { Id = "DeviceStolen", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Device Stolen" });
if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "DeviceLost") == 0) if (Database.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "DeviceLost") == 0)
context.JobSubTypes.Add(new JobSubType { Id = "DeviceLost", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Device Lost" }); Database.JobSubTypes.Add(new JobSubType { Id = "DeviceLost", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Device Lost" });
#endregion #endregion
// End Feature Request // End Feature Request
} }
private static void UpdateDeviceModelConfiguration(this DiscoDataContext context) private static void UpdateDeviceModelConfiguration(this DiscoDataContext Database)
{ {
if (context.ConfigurationItems.Where(c => c.Scope.StartsWith("DeviceProfile:")).Count() > 0) if (Database.ConfigurationItems.Where(c => c.Scope.StartsWith("DeviceProfile:")).Count() > 0)
{ {
var configurationItems = context.ConfigurationItems.Where(c => c.Scope.StartsWith("DeviceProfile:")).ToList(); var configurationItems = Database.ConfigurationItems.Where(c => c.Scope.StartsWith("DeviceProfile:")).ToList();
var deviceProfiles = context.DeviceProfiles.ToDictionary(dp => dp.Id); var deviceProfiles = Database.DeviceProfiles.ToDictionary(dp => dp.Id);
foreach (var configurationItem in configurationItems) foreach (var configurationItem in configurationItems)
{ {
int profileId = int.Parse(configurationItem.Scope.Substring(configurationItem.Scope.IndexOf(":") + 1)); int profileId = int.Parse(configurationItem.Scope.Substring(configurationItem.Scope.IndexOf(":") + 1));
@@ -254,47 +254,19 @@ namespace Disco.Data.Repository
} }
} }
// Remove from DB // Remove from DB
context.ConfigurationItems.Remove(configurationItem); Database.ConfigurationItems.Remove(configurationItem);
} }
} }
} }
// Removed: 2013-01-14 G#
// private static void UpdateDeviceModelImageStorage(this DiscoDataContext dbContext)
// {
//#pragma warning disable 0618
// var updateModels = dbContext.DeviceModels.Where(dm => dm.Image != null);
// if (updateModels.Count() > 0)
// {
// var dataStoreLocation = dbContext.ConfigurationItems.Where(ci => ci.Scope == "System" && ci.Key == "DataStoreLocation").Select(ci => ci.Value).FirstOrDefault();
// if (!string.IsNullOrEmpty(dataStoreLocation) && System.IO.Directory.Exists(dataStoreLocation))
// {
// var deviceModelImagesLocation = System.IO.Path.Combine(dataStoreLocation, "DeviceModelImages");
// if (!System.IO.Directory.Exists(deviceModelImagesLocation))
// System.IO.Directory.CreateDirectory(deviceModelImagesLocation);
// foreach (var model in updateModels)
// {
// var modelpath = System.IO.Path.Combine(deviceModelImagesLocation, string.Format("{0}.png", model.Id));
// if (model.Image != null && model.Image.Length > 0)
// {
// System.IO.File.WriteAllBytes(modelpath, model.Image);
// }
// model.Image = null;
// }
// }
// }
//#pragma warning restore 0618
// }
// Added: 2013-02-07 G# // Added: 2013-02-07 G#
// Fix previous problem with duplicate device models being created if new devices enrol at the same time // Fix previous problem with duplicate device models being created if new devices enrol at the same time
// http://www.discoict.com.au/forum/support/2013/2/duplicate-device-models.aspx // http://www.discoict.com.au/forum/support/2013/2/duplicate-device-models.aspx
// Thanks to Michael Vorster for reporting this problem. // Thanks to Michael Vorster for reporting this problem.
private static void UpdateDeviceModelDuplicates(this DiscoDataContext dbContext) private static void UpdateDeviceModelDuplicates(this DiscoDataContext Database)
{ {
var deviceModels = dbContext.DeviceModels.ToList(); var deviceModels = Database.DeviceModels.ToList();
var duplicateModels = deviceModels.GroupBy(g => string.Format("{0}|{1}", g.Manufacturer, g.Model)).Where(g => g.Count() > 1); var duplicateModels = deviceModels.GroupBy(g => string.Format("{0}|{1}", g.Manufacturer, g.Model)).Where(g => g.Count() > 1);
foreach (var duplicateModel in duplicateModels) foreach (var duplicateModel in duplicateModels)
{ {
@@ -302,7 +274,7 @@ namespace Disco.Data.Repository
foreach (var redundantModel in duplicateModel.Where(m => m != primaryModel)) foreach (var redundantModel in duplicateModel.Where(m => m != primaryModel))
{ {
foreach (var affectedDevice in dbContext.Devices.Where(d => d.DeviceModelId == redundantModel.Id)) foreach (var affectedDevice in Database.Devices.Where(d => d.DeviceModelId == redundantModel.Id))
{ {
affectedDevice.DeviceModelId = primaryModel.Id; affectedDevice.DeviceModelId = primaryModel.Id;
} }
@@ -21,17 +21,17 @@ namespace Disco.Data.Repository.Monitor
public static Subject<RepositoryMonitorEvent> StreamBeforeCommit { get { return streamBefore; } } public static Subject<RepositoryMonitorEvent> StreamBeforeCommit { get { return streamBefore; } }
public static Subject<RepositoryMonitorEvent> StreamAfterCommit { get { return streamAfter; } } public static Subject<RepositoryMonitorEvent> StreamAfterCommit { get { return streamAfter; } }
internal static RepositoryMonitorEvent[] BeforeSaveChanges(DiscoDataContext dbContext) internal static RepositoryMonitorEvent[] BeforeSaveChanges(DiscoDataContext Database)
{ {
var contextStateManager = ((IObjectContextAdapter)dbContext).ObjectContext.ObjectStateManager; var contextStateManager = ((IObjectContextAdapter)Database).ObjectContext.ObjectStateManager;
dbContext.ChangeTracker.DetectChanges(); Database.ChangeTracker.DetectChanges();
var changes = dbContext.ChangeTracker.Entries().Where(entry => entry.State == System.Data.EntityState.Added || entry.State == System.Data.EntityState.Deleted || entry.State == System.Data.EntityState.Modified); var changes = Database.ChangeTracker.Entries().Where(entry => entry.State == System.Data.EntityState.Added || entry.State == System.Data.EntityState.Deleted || entry.State == System.Data.EntityState.Modified);
var events = changes.Select(entryState => var events = changes.Select(entryState =>
{ {
ObjectStateEntry stateEntry = contextStateManager.GetObjectStateEntry(entryState.Entity); ObjectStateEntry stateEntry = contextStateManager.GetObjectStateEntry(entryState.Entity);
var monitorEvent = EventFromEntryState(dbContext, entryState, stateEntry); var monitorEvent = EventFromEntryState(Database, entryState, stateEntry);
// Push to Stream // Push to Stream
streamBefore.OnNext(monitorEvent); streamBefore.OnNext(monitorEvent);
@@ -41,7 +41,7 @@ namespace Disco.Data.Repository.Monitor
return events; return events;
} }
internal static void AfterSaveChanges(DiscoDataContext dbContext, IEnumerable<RepositoryMonitorEvent> changes) internal static void AfterSaveChanges(DiscoDataContext Database, IEnumerable<RepositoryMonitorEvent> changes)
{ {
foreach (var change in changes) foreach (var change in changes)
{ {
@@ -88,7 +88,7 @@ namespace Disco.Data.Repository.Monitor
deferredAction.Invoke(monitorEvent); deferredAction.Invoke(monitorEvent);
} }
internal static RepositoryMonitorEvent EventFromEntryState(DiscoDataContext dbContext, DbEntityEntry entityEntry, ObjectStateEntry entryState) internal static RepositoryMonitorEvent EventFromEntryState(DiscoDataContext Database, DbEntityEntry entityEntry, ObjectStateEntry entryState)
{ {
RepositoryMonitorEventType eventType; RepositoryMonitorEventType eventType;
string[] modifiedProperties = null; string[] modifiedProperties = null;
@@ -135,7 +135,7 @@ namespace Disco.Data.Repository.Monitor
EntityKey = entityKey, EntityKey = entityKey,
EntityType = entityType, EntityType = entityType,
ModifiedProperties = modifiedProperties, ModifiedProperties = modifiedProperties,
dbContext = dbContext, Database = Database,
dbEntityState = entityEntry, dbEntityState = entityEntry,
objectEntryState = entryState objectEntryState = entryState
}; };
@@ -21,7 +21,7 @@ namespace Disco.Data.Repository.Monitor
internal List<Action<RepositoryMonitorEvent>> executeAfterCommit; internal List<Action<RepositoryMonitorEvent>> executeAfterCommit;
[JsonIgnore] [JsonIgnore]
public DiscoDataContext dbContext { get; set; } public DiscoDataContext Database { get; set; }
public RepositoryMonitorEventType EventType { get; set; } public RepositoryMonitorEventType EventType { get; set; }
@@ -0,0 +1,26 @@
using Disco.Models.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.Models.Authorization
{
public interface IAuthorizationToken
{
User User { get; set; }
List<string> GroupMembership { get; set; }
List<IRoleToken> RoleTokens { get; set; }
bool HasAny(params string[] ClaimKeys);
bool HasAny(IEnumerable<string> ClaimKeys);
bool HasAll(params string[] ClaimKeys);
bool HasAll(IEnumerable<string> ClaimKeys);
bool Has(string ClaimKey);
void Require(string ClaimKey);
void RequireAll(params string[] ClaimKeys);
void RequireAny(params string[] ClaimKeys);
}
}
@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.Models.Authorization
{
public interface IClaimNavigatorItem
{
string Key { get; }
string Name { get; }
string Description { get; }
bool Hidden { get; }
List<IClaimNavigatorItem> Children { get; }
bool IsGroup { get; }
bool? Value { get; }
}
}
+15
View File
@@ -0,0 +1,15 @@
using Disco.Models.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.Models.Authorization
{
public interface IRoleToken
{
AuthorizationRole Role { get; set; }
List<string> SubjectIds { get; set; }
}
}
@@ -70,5 +70,9 @@ namespace Disco.Models.BI.Config
throw new ArgumentException("Invalid Configuration Address Entry", "entry"); throw new ArgumentException("Invalid Configuration Address Entry", "entry");
} }
public override string ToString()
{
return string.Format("{0} ({1})", this.Name, this.ShortName);
}
} }
} }
+9
View File
@@ -45,6 +45,9 @@
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="Authorization\IAuthorizationToken.cs" />
<Compile Include="Authorization\IClaimNavigatorItem.cs" />
<Compile Include="Authorization\IRoleToken.cs" />
<Compile Include="BI\Config\OrganisationAddress.cs" /> <Compile Include="BI\Config\OrganisationAddress.cs" />
<Compile Include="BI\Device\ImportDevice.cs" /> <Compile Include="BI\Device\ImportDevice.cs" />
<Compile Include="BI\Device\ImportDeviceSession.cs" /> <Compile Include="BI\Device\ImportDeviceSession.cs" />
@@ -72,7 +75,9 @@
<Compile Include="ClientServices\WhoAmI.cs" /> <Compile Include="ClientServices\WhoAmI.cs" />
<Compile Include="ClientServices\WhoAmIResponse.cs" /> <Compile Include="ClientServices\WhoAmIResponse.cs" />
<Compile Include="Interop\ActiveDirectory\ActiveDirectoryMachineAccount.cs" /> <Compile Include="Interop\ActiveDirectory\ActiveDirectoryMachineAccount.cs" />
<Compile Include="Interop\ActiveDirectory\ActiveDirectoryGroup.cs" />
<Compile Include="Interop\ActiveDirectory\ActiveDirectoryUserAccount.cs" /> <Compile Include="Interop\ActiveDirectory\ActiveDirectoryUserAccount.cs" />
<Compile Include="Interop\ActiveDirectory\IActiveDirectoryObject.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Repository\ConfigurationItem.cs" /> <Compile Include="Repository\ConfigurationItem.cs" />
<Compile Include="Repository\Device\Device.cs" /> <Compile Include="Repository\Device\Device.cs" />
@@ -98,7 +103,11 @@
<Compile Include="Repository\User\User.cs" /> <Compile Include="Repository\User\User.cs" />
<Compile Include="Repository\User\UserAttachment.cs" /> <Compile Include="Repository\User\UserAttachment.cs" />
<Compile Include="Repository\User\UserDetail.cs" /> <Compile Include="Repository\User\UserDetail.cs" />
<Compile Include="Repository\User\AuthorizationRole.cs" />
<Compile Include="UI\BaseUIModel.cs" /> <Compile Include="UI\BaseUIModel.cs" />
<Compile Include="UI\Config\AuthorizationRole\ConfigAuthorizationRoleCreateModel.cs" />
<Compile Include="UI\Config\AuthorizationRole\ConfigAuthorizationRoleIndexModel.cs" />
<Compile Include="UI\Config\AuthorizationRole\ConfigAuthorizationRoleShowModel.cs" />
<Compile Include="UI\Config\DeviceBatch\ConfigDeviceBatchCreateModel.cs" /> <Compile Include="UI\Config\DeviceBatch\ConfigDeviceBatchCreateModel.cs" />
<Compile Include="UI\Config\DeviceBatch\ConfigDeviceBatchIndexModel.cs" /> <Compile Include="UI\Config\DeviceBatch\ConfigDeviceBatchIndexModel.cs" />
<Compile Include="UI\Config\DeviceBatch\ConfigDeviceBatchIndexModelItem.cs" /> <Compile Include="UI\Config\DeviceBatch\ConfigDeviceBatchIndexModelItem.cs" />
@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.Models.Interop.ActiveDirectory
{
public class ActiveDirectoryGroup : IActiveDirectoryObject
{
public string Name { get; set; }
public string DistinguishedName { get; set; }
public string SamAccountName { get; set; }
public string SecurityIdentifier { get; set; }
public string CommonName { get; set; }
public List<string> MemberOf { get; set; }
}
}
@@ -6,37 +6,24 @@ using Disco.Models.Repository;
namespace Disco.Models.Interop.ActiveDirectory namespace Disco.Models.Interop.ActiveDirectory
{ {
public class ActiveDirectoryMachineAccount public class ActiveDirectoryMachineAccount : IActiveDirectoryObject
{ {
public string DistinguishedName { get; set; } public string DistinguishedName { get; set; }
public string DnsName { get; set; } public string DnsName { get; set; }
public string Domain { get; set; } public string Domain { get; set; }
public string Name { get; set; } public string Name { get; set; }
public Guid NetbootGUID { get; set; } public Guid NetbootGUID { get; set; }
public string ObjectSid { get; set; } public string SecurityIdentifier { get; set; }
public string Path { get; set; } public string Path { get; set; }
public string sAMAccountName { get; set; } public string SamAccountName { get; set; }
public bool IsCriticalSystemObject { get; set; } public bool IsCriticalSystemObject { get; set; }
public Dictionary<string, object[]> LoadedProperties { get; set; } public Dictionary<string, object[]> LoadedProperties { get; set; }
public string ParentDistinguishedName
{
get
{
// Determine Parent
if (!string.IsNullOrWhiteSpace(DistinguishedName))
return DistinguishedName.Substring(0, DistinguishedName.IndexOf(",DC=")).Substring(DistinguishedName.IndexOf(",") + 1);
else
return null;
}
}
public User ToRepositoryUser() public User ToRepositoryUser()
{ {
return new User return new User
{ {
Id = this.sAMAccountName, Id = this.SamAccountName,
Type = "Computer",
DisplayName = this.Name DisplayName = this.Name
}; };
} }
@@ -6,7 +6,7 @@ using Disco.Models.Repository;
namespace Disco.Models.Interop.ActiveDirectory namespace Disco.Models.Interop.ActiveDirectory
{ {
public class ActiveDirectoryUserAccount public class ActiveDirectoryUserAccount : IActiveDirectoryObject
{ {
public string DisplayName { get; set; } public string DisplayName { get; set; }
public string DistinguishedName { get; set; } public string DistinguishedName { get; set; }
@@ -15,25 +15,23 @@ namespace Disco.Models.Interop.ActiveDirectory
public string GivenName { get; set; } public string GivenName { get; set; }
public List<string> Groups { get; set; } public List<string> Groups { get; set; }
public string Name { get; set; } public string Name { get; set; }
public string ObjectSid { get; set; } public string SecurityIdentifier { get; set; }
public string Path { get; set; } public string Path { get; set; }
public string Phone { get; set; } public string Phone { get; set; }
public string sAMAccountName { get; set; } public string SamAccountName { get; set; }
public string Surname { get; set; } public string Surname { get; set; }
public string Type { get; set; }
public Dictionary<string, object[]> LoadedProperties { get; set; } public Dictionary<string, object[]> LoadedProperties { get; set; }
public User ToRepositoryUser() public User ToRepositoryUser()
{ {
return new User return new User
{ {
Id = this.sAMAccountName, Id = this.SamAccountName,
DisplayName = this.DisplayName, DisplayName = this.DisplayName,
Surname = this.Surname, Surname = this.Surname,
GivenName = this.GivenName, GivenName = this.GivenName,
EmailAddress = this.Email, EmailAddress = this.Email,
PhoneNumber = this.Phone, PhoneNumber = this.Phone,
Type = this.Type
}; };
} }
@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.Models.Interop.ActiveDirectory
{
public interface IActiveDirectoryObject
{
string DistinguishedName { get; set; }
string SecurityIdentifier { get; set; }
string SamAccountName { get; set; }
string Name { get; set; }
}
}
+2 -2
View File
@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers // You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below: // by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")] // [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.0725.2249")] [assembly: AssemblyVersion("1.2.1001.1541")]
[assembly: AssemblyFileVersion("1.2.0725.2249")] [assembly: AssemblyFileVersion("1.2.1001.1541")]
@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.Models.Repository
{
public class AuthorizationRole
{
[Key]
public int Id { get; set; }
[Required, StringLength(100)]
public string Name { get; set; }
public string SubjectIds { get; set; }
public string ClaimsJson { get; set; }
}
}
+1 -25
View File
@@ -19,8 +19,6 @@ namespace Disco.Models.Repository
[StringLength(200)] [StringLength(200)]
public string GivenName { get; set; } public string GivenName { get; set; }
[StringLength(8)]
public string Type { get; set; }
[StringLength(100)] [StringLength(100)]
public string PhoneNumber { get; set; } public string PhoneNumber { get; set; }
[StringLength(150)] [StringLength(150)]
@@ -32,17 +30,6 @@ namespace Disco.Models.Repository
[InverseProperty("UserId")] [InverseProperty("UserId")]
public virtual IList<Job> Jobs { get; set; } public virtual IList<Job> Jobs { get; set; }
//#region Helper Members
//[NotMapped, XmlIgnore, ScriptIgnore]
//public List<DeviceUserAssignment> CurrentDeviceUserAssignments
//{
// get
// {
// return this.DeviceUserAssignments.Where(dua => !dua.UnassignedDate.HasValue).ToList();
// }
//}
//#endregion
public override string ToString() public override string ToString()
{ {
return string.Format("{0} ({1})", this.DisplayName, this.Id); return string.Format("{0} ({1})", this.DisplayName, this.Id);
@@ -63,17 +50,6 @@ namespace Disco.Models.Repository
this.EmailAddress = u.EmailAddress; this.EmailAddress = u.EmailAddress;
if (this.PhoneNumber != u.PhoneNumber) if (this.PhoneNumber != u.PhoneNumber)
this.PhoneNumber = u.PhoneNumber; this.PhoneNumber = u.PhoneNumber;
if (this.Type != u.Type) }
this.Type = u.Type;
}
public static class Types
{
public const string Admin = "Admin";
public const string Computer = "Computer";
public const string Staff = "Staff";
public const string Student = "Student";
}
} }
} }
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.Models.UI.Config.AuthorizationRole
{
public interface ConfigAuthorizationRoleCreateModel : BaseUIModel
{
Models.Repository.AuthorizationRole AuthorizationRole { get; set; }
}
}
@@ -0,0 +1,14 @@
using Disco.Models.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.Models.UI.Config.AuthorizationRole
{
public interface ConfigAuthorizationRoleIndexModel : BaseUIModel
{
List<IRoleToken> Tokens { get; set; }
}
}
@@ -0,0 +1,14 @@
using Disco.Models.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.Models.UI.Config.AuthorizationRole
{
public interface ConfigAuthorizationRoleShowModel : BaseUIModel
{
IRoleToken Token { get; set; }
}
}
@@ -9,6 +9,9 @@ namespace Disco.Models.UI.Config.DeviceBatch
public interface ConfigDeviceBatchShowModel : BaseUIModel public interface ConfigDeviceBatchShowModel : BaseUIModel
{ {
Disco.Models.Repository.DeviceBatch DeviceBatch { get; set; } Disco.Models.Repository.DeviceBatch DeviceBatch { get; set; }
Disco.Models.Repository.DeviceModel DefaultDeviceModel { get; set; }
List<Disco.Models.Repository.DeviceModel> DeviceModels { get; set; } List<Disco.Models.Repository.DeviceModel> DeviceModels { get; set; }
List<ConfigDeviceBatchShowModelMembership> DeviceModelMembers { get; set; } List<ConfigDeviceBatchShowModelMembership> DeviceModelMembers { get; set; }
@@ -9,6 +9,8 @@ namespace Disco.Models.UI.Config.DeviceProfile
public interface ConfigDeviceProfileShowModel : BaseUIModel public interface ConfigDeviceProfileShowModel : BaseUIModel
{ {
Disco.Models.Repository.DeviceProfile DeviceProfile { get; set; } Disco.Models.Repository.DeviceProfile DeviceProfile { get; set; }
Disco.Models.BI.Config.OrganisationAddress DefaultOrganisationAddress { get; set; }
List<Disco.Models.BI.Config.OrganisationAddress> OrganisationAddresses { get; set; } List<Disco.Models.BI.Config.OrganisationAddress> OrganisationAddresses { get; set; }
int DeviceCount { get; set; } int DeviceCount { get; set; }
+3 -1
View File
@@ -1,4 +1,5 @@
using System; using Disco.Models.Authorization;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@@ -11,5 +12,6 @@ namespace Disco.Models.UI.User
Disco.Models.Repository.User User { get; set; } Disco.Models.Repository.User User { get; set; }
Disco.Models.BI.Job.JobTableModel Jobs { get; set; } Disco.Models.BI.Job.JobTableModel Jobs { get; set; }
List<Disco.Models.Repository.DocumentTemplate> DocumentTemplates { get; set; } List<Disco.Models.Repository.DocumentTemplate> DocumentTemplates { get; set; }
IClaimNavigatorItem ClaimNavigator { get; set; }
} }
} }
@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.Services.Authorization
{
public class AccessDeniedException : Exception
{
private string _message { get; set; }
public AccessDeniedException(string Message)
{
this._message = Message;
}
public override string Message
{
get
{
if (this._message == null)
{
return "Your account does not have the required permission to access this Disco feature.";
}
else
{
return this._message;
}
}
}
}
}

Some files were not shown because too many files have changed in this diff Show More