Certificate/wireless plugins; major refactoring

Migrate much of BI to Services.
Added Wireless Profile Provider plugin feature.
Added Certificate Authority Provider plugin feature.
Modified Certificate Provider plugin feature.
Database migration v17, for Device Profiles.
Enrolment Client Updated to support CA Certificates, Wireless Profiles
and Hardware Info.
New Client Enrolment Protocol to support new features.
Plugin Manifest Generator added to main solution.
Improved AD search performance.
This commit is contained in:
Gary Sharp
2016-09-28 20:16:25 +10:00
parent 489a5df7cc
commit 27c21175d7
210 changed files with 9822 additions and 6675 deletions
@@ -1,14 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
namespace Disco.BI
{
public class EnrolSafeException : System.Exception
{
public EnrolSafeException(string Message) : base(Message)
{
}
}
}
-486
View File
@@ -1,486 +0,0 @@
using Disco.Services.Logging;
using Disco.Services.Logging.Models;
using Disco.Models.ClientServices;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Disco.BI.DeviceBI
{
public class EnrolmentLog : LogBase
{
public enum EventTypeIds
{
SessionStarting = 10,
SessionProgress,
SessionDevice,
SessionDeviceInfo,
SessionFinished = 20,
SessionDiagnosticInformation,
SessionWarning,
SessionError,
SessionErrorWithInner,
SessionClientError,
SessionTaskAddedDevice = 50,
SessionTaskUpdatingDevice,
SessionTaskCreatedDeviceModel = 56,
SessionTaskProvisioningADAccount = 58,
SessionTaskAssigningUser = 60,
SessionTaskProvisioningWirelessCertificate = 62,
SessionTaskRenamingDevice = 64,
SessionTaskMovingDeviceOrganisationUnit = 66,
ClientError = 400
}
private const int _ModuleId = 50;
public static EnrolmentLog Current
{
get
{
return (EnrolmentLog)LogContext.LogModules[50];
}
}
public override string ModuleDescription
{
get
{
return "Device Enrolment";
}
}
public override int ModuleId
{
get
{
return 50;
}
}
public override string ModuleName
{
get
{
return "DeviceEnrolment";
}
}
[System.Diagnostics.DebuggerNonUserCode]
public EnrolmentLog()
{
}
private static void Log(EnrolmentLog.EventTypeIds EventTypeId, params object[] Args)
{
EnrolmentLog.Current.Log((int)EventTypeId, Args);
}
public static void LogSessionStarting(string SessionId, string HostId, DeviceEnrol.EnrolmentTypes EnrolmentType)
{
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionStarting, new object[]
{
SessionId,
HostId,
System.Enum.GetName(EnrolmentType.GetType(), EnrolmentType)
});
}
public static void LogSessionDevice(string SessionId, string DeviceSerialNumber, int? DeviceModelId)
{
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionDevice, new object[]
{
SessionId,
DeviceSerialNumber,
DeviceModelId
});
}
public static void LogSessionDeviceInfo(string SessionId, string SerialNumber, string UUID, string ComputerName, string LanMacAddress, string WlanMacAddress, string Manufacturer, string Model, string ModelType)
{
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionDeviceInfo, new object[]
{
SessionId,
SerialNumber,
UUID,
ComputerName,
LanMacAddress,
WlanMacAddress,
Manufacturer,
Model,
ModelType
});
}
public static void LogSessionDeviceInfo(string SessionId, MacEnrol Request)
{
EnrolmentLog.LogSessionDeviceInfo(SessionId, Request.DeviceSerialNumber, Request.DeviceUUID, Request.DeviceComputerName, Request.DeviceLanMacAddress, Request.DeviceWlanMacAddress, Request.DeviceManufacturer, Request.DeviceModel, Request.DeviceModelType);
}
public static void LogSessionDeviceInfo(string SessionId, Models.ClientServices.Enrol Request)
{
EnrolmentLog.LogSessionDeviceInfo(SessionId, Request.DeviceSerialNumber, Request.DeviceUUID, Request.DeviceComputerName, Request.DeviceLanMacAddress, Request.DeviceWlanMacAddress, Request.DeviceManufacturer, Request.DeviceModel, Request.DeviceModelType);
}
public static void LogSessionDeviceInfo(string SessionId, Models.ClientServices.Register Request)
{
EnrolmentLog.LogSessionDeviceInfo(SessionId, Request.DeviceSerialNumber, Request.DeviceUUID, Request.DeviceComputerName, null, null, Request.DeviceManufacturer, Request.DeviceModel, Request.DeviceModelType);
}
public static void LogSessionProgress(string SessionId, int Progress, string Status)
{
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionProgress, new object[]
{
SessionId,
Progress,
Status
});
}
public static void LogSessionFinished(string SessionId)
{
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionFinished, new object[]
{
SessionId
});
}
public static void LogSessionDiagnosticInformation(string SessionId, string Message)
{
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionDiagnosticInformation, new object[]
{
SessionId,
Message
});
}
public static void LogSessionWarning(string SessionId, string Message)
{
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionWarning, new object[]
{
SessionId,
Message
});
}
public static void LogSessionError(string SessionId, System.Exception Ex)
{
if (Ex.InnerException == null)
{
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionError, new object[]
{
SessionId,
Ex.GetType().Name,
Ex.Message,
Ex.StackTrace
});
}
else
{
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionErrorWithInner, new object[]
{
SessionId,
Ex.GetType().Name,
Ex.Message,
Ex.InnerException.GetType().Name,
Ex.InnerException.Message,
Ex.StackTrace,
Ex.InnerException.StackTrace
});
}
}
public static void LogSessionClientError(string SessionId, string ClientIP, string ClientIdentifier, string ClientVersion, string Error, string RawError)
{
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionClientError, new object[]
{
SessionId,
ClientIP,
ClientIdentifier,
ClientVersion,
Error,
RawError
});
}
public static void LogSessionTaskAddedDevice(string SessionId, string DeviceSerialNumber)
{
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskAddedDevice, new object[]
{
SessionId,
DeviceSerialNumber
});
}
public static void LogSessionTaskUpdatingDevice(string SessionId, string DeviceSerialNumber)
{
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskUpdatingDevice, new object[]
{
SessionId,
DeviceSerialNumber
});
}
public static void LogSessionTaskCreatedDeviceModel(string SessionId, string DeviceSerialNumber, string Manufacturer, string Model)
{
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskCreatedDeviceModel, new object[]
{
SessionId,
DeviceSerialNumber,
Manufacturer,
Model
});
}
public static void LogSessionTaskProvisioningADAccount(string SessionId, string DeviceSerialNumber, string ADAccountName)
{
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskProvisioningADAccount, new object[]
{
SessionId,
DeviceSerialNumber,
ADAccountName
});
}
public static void LogSessionTaskAssigningUser(string SessionId, string DeviceSerialNumber, string UserDisplayName, string UserUsername, string UserDomain, string UserSID)
{
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskAssigningUser, new object[]
{
SessionId,
DeviceSerialNumber,
UserDisplayName,
UserUsername,
UserDomain,
UserSID
});
}
public static void LogSessionTaskProvisioningWirelessCertificate(string SessionId, string DeviceSerialNumber, string CertificateName)
{
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskProvisioningWirelessCertificate, new object[]
{
SessionId,
DeviceSerialNumber,
CertificateName
});
}
public static void LogSessionTaskRenamingDevice(string SessionId, string OldComputerName, string NewComputerName)
{
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskRenamingDevice, new object[]
{
SessionId,
OldComputerName,
NewComputerName
});
}
public static void LogSessionTaskMovingDeviceOrganisationUnit(string SessionId, string OldOrganisationUnit, string NewOrganisationUnit)
{
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskMovingDeviceOrganisationUnit, new object[]
{
SessionId,
OldOrganisationUnit,
NewOrganisationUnit
});
}
public static void LogClientError(string ClientIP, string ClientIdentifier, string ClientVersion, string Error, string RawError)
{
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.ClientError, new object[]
{
ClientIP,
ClientIdentifier,
ClientVersion,
Error,
RawError
});
}
protected override System.Collections.Generic.List<LogEventType> LoadEventTypes()
{
return new System.Collections.Generic.List<LogEventType>
{
new LogEventType
{
Id = 10,
ModuleId = 50,
Name = "Session Starting",
Format = "Starting '{2}' Enrolment for {1} (Session# {0})",
Severity = 0,
UseLive = true,
UsePersist = true,
UseDisplay = true
},
new LogEventType
{
Id = 12,
ModuleId = 50,
Name = "Session Device",
Format = null,
Severity = 0,
UseLive = true,
UsePersist = true,
UseDisplay = false
},
new LogEventType
{
Id = 11,
ModuleId = 50,
Name = "Session Progress",
Format = "Processing Session# {0}; {1}% Complete; Status: {2}",
Severity = 0,
UseLive = true,
UsePersist = false,
UseDisplay = false
},
new LogEventType
{
Id = 13,
ModuleId = 50,
Name = "Session Device Info",
Format = null,
Severity = 0,
UseLive = true,
UsePersist = true,
UseDisplay = true
},
new LogEventType
{
Id = 20,
ModuleId = 50,
Name = "Session Finished",
Format = "Finished Session# {0}",
Severity = 0,
UseLive = true,
UsePersist = true,
UseDisplay = true
},
new LogEventType
{
Id = 21,
ModuleId = 50,
Name = "Session Diagnostic Information",
Format = null,
Severity = 0,
UseLive = true,
UsePersist = false,
UseDisplay = false
},
new LogEventType
{
Id = 22,
ModuleId = 50,
Name = "Session Warning",
Format = null,
Severity = 1,
UseLive = true,
UsePersist = true,
UseDisplay = true
},
new LogEventType
{
Id = 23,
ModuleId = 50,
Name = "Session Error",
Format = "An Error Occurred: [{1}] {2}",
Severity = 2,
UseLive = true,
UsePersist = true,
UseDisplay = true
},
new LogEventType
{
Id = 24,
ModuleId = 50,
Name = "Session Error with Internal",
Format = "An Error Occurred: [{1}] {2}; Internal Error: [{3}] {4}",
Severity = 2,
UseLive = true,
UsePersist = true,
UseDisplay = true
},
new LogEventType
{
Id = (int)EventTypeIds.SessionClientError,
ModuleId = _ModuleId,
Name = "Client Error",
Format = "IP: {1}; Device ID: {2}; Version: {3} Error: {4}; Session# {0}",
Severity = (int)LogEventType.Severities.Error,
UseLive = true,
UsePersist = true,
UseDisplay = true
},
new LogEventType
{
Id = 50,
ModuleId = 50,
Name = "Task - Added Device",
Format = "Creating Disco Device {1}",
Severity = 0,
UseLive = true,
UsePersist = true,
UseDisplay = true
},
new LogEventType
{
Id = 51,
ModuleId = 50,
Name = "Task - Updating Device",
Format = "Updating Disco Device {1}",
Severity = 0,
UseLive = true,
UsePersist = true,
UseDisplay = true
},
new LogEventType
{
Id = 56,
ModuleId = 50,
Name = "Task - Creating Device Model",
Format = "Creating Device Model '{2} {3}' for Device {1}",
Severity = 0,
UseLive = true,
UsePersist = true,
UseDisplay = true
},
new LogEventType
{
Id = 58,
ModuleId = 50,
Name = "Task - Provisioning Active Directory Account",
Format = "Provisioning Active Directory Account '{2}' for Device {1}",
Severity = 0,
UseLive = true,
UsePersist = true,
UseDisplay = true
},
new LogEventType
{
Id = 60,
ModuleId = 50,
Name = "Task - Assigning User",
Format = "Assigning User '{2}' ({4}\\{3} {{{5}}}) for Device {1}",
Severity = 0,
UseLive = true,
UsePersist = true,
UseDisplay = true
},
new LogEventType
{
Id = 62,
ModuleId = 50,
Name = "Task - Provisioning Wireless Certificate",
Format = "Provisioning Wireless Certificate '{2}' for Device {1}",
Severity = 0,
UseLive = true,
UsePersist = true,
UseDisplay = true
},
new LogEventType
{
Id = 64,
ModuleId = 50,
Name = "Task - Renaming Device",
Format = "Renaming Device '{1}' to '{2}'",
Severity = 0,
UseLive = true,
UsePersist = true,
UseDisplay = true
},
new LogEventType
{
Id = 66,
ModuleId = 50,
Name = "Task - Moving Device Organisation Unit",
Format = "Moving Device Organisation Unit '{1}' to '{2}'",
Severity = 0,
UseLive = true,
UsePersist = true,
UseDisplay = true
},
new LogEventType
{
Id = (int)EventTypeIds.ClientError,
ModuleId = _ModuleId,
Name = "Client Error",
Format = "IP: {0}; Device ID: {1}; Version: {2} Error: {3}",
Severity = (int)LogEventType.Severities.Error,
UseLive = true,
UsePersist = true,
UseDisplay = true
}
};
}
}
}
-21
View File
@@ -1,21 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace Disco.BI
{
public class DisposableImageCollection : List<Bitmap>, IDisposable
{
public void Dispose()
{
foreach (Image i in this)
{
if (i != null)
i.Dispose();
}
}
}
}
@@ -1,96 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Disco.Models.Repository;
using Disco.Data.Repository;
using Disco.Services.Users;
using Disco.Services.Authorization;
using Disco.BI.DocumentTemplateBI.ManagedGroups;
using Disco.Services;
namespace Disco.BI.Extensions
{
public static class AttachmentActionExtensions
{
#region Delete
public static bool CanDelete(this DeviceAttachment da)
{
if (UserService.CurrentAuthorization.Has(Claims.Device.Actions.RemoveAnyAttachments))
return true;
if (UserService.CurrentAuthorization.Has(Claims.Device.Actions.RemoveOwnAttachments)
&& da.TechUserId.Equals(UserService.CurrentUserId, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
public static void OnDelete(this DeviceAttachment da, DiscoDataContext Database)
{
if (!da.CanDelete())
throw new InvalidOperationException("Deletion of Attachment is Denied");
var attachmentId = da.Id;
var documentTemplateId = da.DocumentTemplateId;
var deviceSerialNumber = da.DeviceSerialNumber;
da.RepositoryDelete(Database);
Database.DeviceAttachments.Remove(da);
DocumentTemplateManagedGroups.TriggerDeviceAttachmentDeleted(Database, attachmentId, documentTemplateId, deviceSerialNumber);
}
public static bool CanDelete(this JobAttachment ja)
{
if (UserService.CurrentAuthorization.Has(Claims.Job.Actions.RemoveAnyAttachments))
return true;
if (UserService.CurrentAuthorization.Has(Claims.Job.Actions.RemoveOwnAttachments)
&& ja.TechUserId.Equals(UserService.CurrentUserId, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
public static void OnDelete(this JobAttachment ja, DiscoDataContext Database)
{
if (!ja.CanDelete())
throw new InvalidOperationException("Deletion of Attachment is Denied");
var attachmentId = ja.Id;
var documentTemplateId = ja.DocumentTemplateId;
var jobId = ja.JobId;
ja.RepositoryDelete(Database);
Database.JobAttachments.Remove(ja);
DocumentTemplateManagedGroups.TriggerJobAttachmentDeleted(Database, attachmentId, documentTemplateId, jobId);
}
public static bool CanDelete(this UserAttachment ua)
{
if (UserService.CurrentAuthorization.Has(Claims.User.Actions.RemoveAnyAttachments))
return true;
if (UserService.CurrentAuthorization.Has(Claims.User.Actions.RemoveOwnAttachments)
&& ua.TechUserId.Equals(UserService.CurrentUserId, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
public static void OnDelete(this UserAttachment ua, DiscoDataContext Database)
{
if (!ua.CanDelete())
throw new InvalidOperationException("Deletion of Attachment is Denied");
var attachmentId = ua.Id;
var documentTemplateId = ua.DocumentTemplateId;
var userId = ua.UserId;
ua.RepositoryDelete(Database);
Database.UserAttachments.Remove(ua);
DocumentTemplateManagedGroups.TriggerUserAttachmentDeleted(Database, attachmentId, documentTemplateId, userId);
}
#endregion
}
}
@@ -1,38 +0,0 @@
using System.Linq;
using Disco.Data.Repository;
using Disco.Models.Repository;
using Disco.Services.Plugins;
using Disco.Services.Plugins.Features.CertificateProvider;
using System;
using System.Collections.Generic;
namespace Disco.BI.Extensions
{
public static class DeviceCertificateExtensions
{
public static Tuple<DeviceCertificate, List<string>> AllocateCertificate(this Device device, DiscoDataContext Database)
{
if (!string.IsNullOrEmpty(device.DeviceProfile.CertificateProviderId))
{
// Load Plugin
PluginFeatureManifest featureManifest = Plugins.GetPluginFeature(device.DeviceProfile.CertificateProviderId, typeof(CertificateProviderFeature));
using (CertificateProviderFeature providerFeature = featureManifest.CreateInstance<CertificateProviderFeature>())
{
// REMOVED 2012-07-18 G# - Plugin is responsible for checking
// Already Allocated Certificate
//if (deviceCertificates.Count > 0)
// return new Tuple<DeviceCertificate, List<string>>(deviceCertificates[0], providerPlugin.RemoveExistingCertificateNames());
//else
return providerFeature.AllocateCertificate(Database, device);
}
}
// Device Profile does not allow certificate allocation
return null;
}
}
}
@@ -1,53 +0,0 @@
using Disco.Data.Repository;
using Disco.Models.Repository;
using Disco.Services;
using Disco.Services.Authorization;
using Disco.Services.Users;
using System;
using System.IO;
using System.Linq;
namespace Disco.BI.Extensions
{
public static class DeviceModelExtensions
{
#region Actions
public static bool CanDelete(this DeviceModel dm, DiscoDataContext Database)
{
if (!UserService.CurrentAuthorization.Has(Claims.Config.DeviceModel.Delete))
return false;
// Can't Delete Default Model (Id: 1)
if (dm.Id == 1)
return false;
// Can't Delete if Contains Devices
if (Database.Devices.Count(d => d.DeviceModelId == dm.Id) > 0)
return false;
return true;
}
public static void Delete(this DeviceModel dm, DiscoDataContext Database)
{
if (!dm.CanDelete(Database))
throw new InvalidOperationException("The state of this Device Model doesn't allow it to be deleted");
// Delete Image
var deviceModelImagePath = dm.ImageFilePath();
if (File.Exists(deviceModelImagePath))
File.Delete(deviceModelImagePath);
// Delete any Device Model Components
foreach (var deviceModelComponent in Database.DeviceComponents.Where(dc => dc.DeviceModelId == dm.Id).ToList())
{
Database.DeviceComponents.Remove(deviceModelComponent);
}
// Delete Model
Database.DeviceModels.Remove(dm);
}
// End Added 2012-11-26 G#
#endregion
}
}
@@ -1,9 +1,9 @@
using Disco.BI.DocumentTemplateBI.ManagedGroups;
using Disco.Data.Repository;
using Disco.Models.Repository;
using Disco.Models.Services.Documents;
using Disco.Services;
using Disco.Services.Documents;
using Disco.Services.Documents.ManagedGroups;
using Disco.Services.Expressions;
using Disco.Services.Interop.ActiveDirectory;
using iTextSharp.text.pdf;
-200
View File
@@ -1,200 +0,0 @@
using Disco.Data.Repository;
using Disco.Models.Repository;
using Disco.Models.Services.Documents;
using Disco.Services;
using Disco.Services.Authorization;
using Disco.Services.Plugins;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Disco.BI.Extensions
{
public static class JobExtensions
{
public static List<DocumentTemplate> AvailableDocumentTemplates(this Job j, DiscoDataContext Database, User User, DateTime TimeStamp)
{
var dts = Database.DocumentTemplates.Include("JobSubTypes")
.Where(dt => dt.Scope == DocumentTemplate.DocumentTemplateScopes.Job)
.ToList();
foreach (var dt in dts.ToArray())
{
if (dt.JobSubTypes.Count != 0)
{ // Filter Applied
bool match = false;
foreach (var st in j.JobSubTypes)
{
if (dt.JobSubTypes.Contains(st))
{
match = true;
break;
}
}
if (!match)
dts.Remove(dt);
}
}
// Evaluate Filters
dts = dts.Where(dt => dt.FilterExpressionMatches(j, Database, User, TimeStamp, DocumentState.DefaultState())).ToList();
return dts;
}
public static DateTime ValidateDateAfterOpened(this Job j, DateTime d)
{
if (d < j.OpenedDate)
{
if (d > j.OpenedDate.AddMinutes(-1))
return j.OpenedDate;
else
throw new ArgumentException("The Date must be >= the Open Date.", "d");
}
return d;
}
public static string GenerateFaultDescription(this Job j, DiscoDataContext Database)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("Faulty Components:");
foreach (var jst in j.JobSubTypes)
sb.Append("- ").AppendLine(jst.Description).AppendLine(" - ");
return sb.ToString();
}
public static string GenerateFaultDescriptionFooter(this Job j, DiscoDataContext Database, PluginFeatureManifest WarrantyProviderDefinition)
{
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})",
versionDisco.Major, versionDisco.Minor, versionDisco.Build, versionDisco.Revision, WarrantyProviderDefinition.Id, WarrantyProviderDefinition.PluginManifest.Version.ToString(4));
}
public static void UpdateSubTypes(this Job j, DiscoDataContext Database, List<JobSubType> SubTypes, bool AddComponents, User TechUser)
{
if (SubTypes == null || SubTypes.Count == 0)
throw new ArgumentException("The Job must contain at least one Sub Type");
List<JobSubType> addedSubTypes = new List<JobSubType>();
List<JobSubType> removedSubTypes = new List<JobSubType>();
// Removed Sub Types
foreach (var t in j.JobSubTypes.ToArray())
if (!SubTypes.Contains(t))
{
removedSubTypes.Add(t);
j.JobSubTypes.Remove(t);
}
// Added Sub Types
foreach (var t in SubTypes)
if (!j.JobSubTypes.Contains(t))
{
addedSubTypes.Add(t);
j.JobSubTypes.Add(t);
}
// Write Log
if (addedSubTypes.Count > 0 || removedSubTypes.Count > 0)
{
StringBuilder logBuilder = new StringBuilder();
logBuilder.AppendLine("# Updated Job Sub Types");
if (removedSubTypes.Count > 0)
{
logBuilder.AppendLine().AppendLine("Removed:");
foreach (var t in removedSubTypes)
logBuilder.Append("- **").Append(t.ToString()).AppendLine("**");
}
if (addedSubTypes.Count > 0)
{
logBuilder.AppendLine().AppendLine("Added:");
foreach (var t in addedSubTypes)
logBuilder.Append("- **").Append(t.ToString()).AppendLine("**");
}
Database.JobLogs.Add(new JobLog()
{
JobId = j.Id,
TechUserId = TechUser.UserId,
Timestamp = DateTime.Now,
Comments = logBuilder.ToString()
});
}
// Add Components
if (AddComponents && addedSubTypes.Count > 0 && j.DeviceSerialNumber != null)
{
var components = Database.DeviceComponents.Include("JobSubTypes").Where(c => !c.DeviceModelId.HasValue || c.DeviceModelId == j.Device.DeviceModelId);
var addedComponents = new List<DeviceComponent>();
foreach (var c in components)
{
foreach (var st in c.JobSubTypes)
{
foreach (var jst in addedSubTypes)
{
if (st.JobTypeId == jst.JobTypeId && st.Id == jst.Id)
{
addedComponents.Add(c);
break;
}
}
if (addedComponents.Contains(c))
break;
}
}
foreach (var c in addedComponents)
{
if (!j.JobComponents.Any(jc => jc.Description.Equals(c.Description, StringComparison.OrdinalIgnoreCase)))
{ // Job Component with matching Description doesn't exist.
Database.JobComponents.Add(new JobComponent()
{
Job = j,
TechUserId = TechUser.UserId,
Cost = c.Cost,
Description = c.Description
});
}
}
}
}
private static List<string> FilterCreatableTypePermissions(AuthorizationToken Authorization)
{
if (!Authorization.HasAll(Claims.Job.Types.CreateHMisc, Claims.Job.Types.CreateHNWar, Claims.Job.Types.CreateHWar, Claims.Job.Types.CreateSApp, Claims.Job.Types.CreateSImg, Claims.Job.Types.CreateSOS, Claims.Job.Types.CreateUMgmt))
{
// Must Filter
List<string> allowedTypes = new List<string>(6);
if (Authorization.Has(Claims.Job.Types.CreateHMisc))
allowedTypes.Add(JobType.JobTypeIds.HMisc);
if (Authorization.Has(Claims.Job.Types.CreateHNWar))
allowedTypes.Add(JobType.JobTypeIds.HNWar);
if (Authorization.Has(Claims.Job.Types.CreateHWar))
allowedTypes.Add(JobType.JobTypeIds.HWar);
if (Authorization.Has(Claims.Job.Types.CreateSApp))
allowedTypes.Add(JobType.JobTypeIds.SApp);
if (Authorization.Has(Claims.Job.Types.CreateSImg))
allowedTypes.Add(JobType.JobTypeIds.SImg);
if (Authorization.Has(Claims.Job.Types.CreateSOS))
allowedTypes.Add(JobType.JobTypeIds.SOS);
if (Authorization.Has(Claims.Job.Types.CreateUMgmt))
allowedTypes.Add(JobType.JobTypeIds.UMgmt);
return allowedTypes;
}
return null;
}
public static IQueryable<JobType> FilterCreatableTypePermissions(this IQueryable<JobType> JobTypes, AuthorizationToken Authorization)
{
var allowedTypes = FilterCreatableTypePermissions(Authorization);
if (allowedTypes != null)
{
return JobTypes.Where(jt => allowedTypes.Contains(jt.Id));
}
return JobTypes;
}
}
}
-36
View File
@@ -1,36 +0,0 @@
using Disco.Data.Repository;
using Disco.Models.Repository;
using Disco.Models.Services.Documents;
using Disco.Services;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Disco.BI.Extensions
{
public static class UserExtensions
{
public static List<DocumentTemplate> AvailableDocumentTemplates(this User u, DiscoDataContext Database, User User, DateTime TimeStamp)
{
var dts = Database.DocumentTemplates.Include("JobSubTypes")
.Where(dt => dt.Scope == DocumentTemplate.DocumentTemplateScopes.User)
.ToArray()
.Where(dt => dt.FilterExpressionMatches(u, Database, User, TimeStamp, DocumentState.DefaultState())).ToList();
return dts;
}
public static List<DeviceUserAssignment> CurrentDeviceUserAssignments(this User u)
{
return u.DeviceUserAssignments.Where(dua => !dua.UnassignedDate.HasValue).ToList();
}
public static bool CanCreateJob(this User u)
{
if (!JobActionExtensions.CanCreate())
return false;
return true;
}
}
}
@@ -1,27 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging;
namespace Disco.BI.Extensions
{
public static class UtilityExtensions
{
public static string StreamToString(this System.IO.Stream stream)
{
if (stream.Position != 0 && stream.CanSeek)
{
stream.Position = 0;
}
using (System.IO.StreamReader sr = new System.IO.StreamReader(stream))
{
return sr.ReadToEnd();
}
}
}
}
@@ -1,18 +0,0 @@
using Disco.Models.Repository;
using System;
using System.Security.Cryptography.X509Certificates;
namespace Disco.BI.Extensions
{
public static class WirelessCertificateExtensions
{
public static System.DateTime? CertificateExpirationDate(this DeviceCertificate wc)
{
if (wc.Content == null || wc.Content.Length == 0)
{
return null;
}
X509Certificate2 c = new X509Certificate2(wc.Content, "password");
return c.NotAfter;
}
}
}
+1 -1
View File
@@ -42,7 +42,7 @@ namespace Disco.BI.Interop.Pdf
}
else
{
Stream bulkPdf = DocumentTemplateBI.Utilities.JoinPdfs(generatedPdfs.ToArray());
Stream bulkPdf = Utilities.JoinPdfs(generatedPdfs.ToArray());
foreach (Stream singlePdf in generatedPdfs)
singlePdf.Dispose();
return bulkPdf;
@@ -1,7 +1,7 @@
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace Disco.BI.DocumentTemplateBI
namespace Disco.BI.Interop.Pdf
{
public static class Utilities
{
+6 -85
View File
@@ -15,6 +15,7 @@
<TargetFrameworkProfile />
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
<RestorePackages>true</RestorePackages>
<AssemblyVersion>2.2.16272.1003</AssemblyVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@@ -37,33 +38,15 @@
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="BitMiracle.LibTiff.NET">
<HintPath>..\Resources\Libraries\LibTiff.NET\BitMiracle.LibTiff.NET.dll</HintPath>
</Reference>
<Reference Include="EntityFramework">
<HintPath>..\packages\EntityFramework.5.0.0\lib\net45\EntityFramework.dll</HintPath>
</Reference>
<Reference Include="Exceptionless, Version=1.5.2092.0, Culture=neutral, PublicKeyToken=fc181f0a46f65747, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Exceptionless.1.5.2092\lib\net45\Exceptionless.dll</HintPath>
</Reference>
<Reference Include="Exceptionless.Models, Version=1.5.2092.0, Culture=neutral, PublicKeyToken=fc181f0a46f65747, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Exceptionless.1.5.2092\lib\net45\Exceptionless.Models.dll</HintPath>
</Reference>
<Reference Include="itextsharp">
<HintPath>..\Resources\Libraries\iTextSharp\itextsharp.dll</HintPath>
</Reference>
<Reference Include="PList, Version=0.1.4109.38751, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\plist.net.1.0\lib\Net35\PList.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Quartz">
<HintPath>..\Resources\Libraries\Quartz\Quartz.dll</HintPath>
</Reference>
<Reference Include="Renci.SshNet">
<HintPath>..\..\..\Resources\Libraries\SshNet\Renci.SshNet.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Core" />
@@ -72,29 +55,15 @@
<Reference Include="System.Drawing" />
<Reference Include="System.Management" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Net.Http.Extensions">
<Reference Include="System.Net.Http.Extensions, Version=2.2.22.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Net.Http.2.2.22\lib\net45\System.Net.Http.Extensions.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Net.Http.Primitives">
<Reference Include="System.Net.Http.Primitives, Version=4.2.22.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Net.Http.2.2.22\lib\net45\System.Net.Http.Primitives.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Net.Http.WebRequest" />
<Reference Include="System.Reactive.Core, Version=2.2.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Rx-Core.2.2.5\lib\net45\System.Reactive.Core.dll</HintPath>
</Reference>
<Reference Include="System.Reactive.Interfaces, Version=2.2.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Rx-Interfaces.2.2.5\lib\net45\System.Reactive.Interfaces.dll</HintPath>
</Reference>
<Reference Include="System.Reactive.Linq, Version=2.2.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Rx-Linq.2.2.5\lib\net45\System.Reactive.Linq.dll</HintPath>
</Reference>
<Reference Include="System.Reactive.PlatformServices, Version=2.2.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Rx-PlatformServices.2.2.5\lib\net45\System.Reactive.PlatformServices.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.Web" />
@@ -105,39 +74,9 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="BI\DeviceBI\BatchUtilities.cs" />
<Compile Include="BI\DeviceBI\DeviceModelBI.cs" />
<Compile Include="BI\DeviceBI\Migration\LogMacAddressImporting.cs" />
<Compile Include="BI\DisposableImageCollection.cs" />
<Compile Include="BI\DocumentTemplateBI\ManagedGroups\DocumentTemplateUsersManagedGroup.cs" />
<Compile Include="BI\DocumentTemplateBI\ManagedGroups\DocumentTemplateDevicesManagedGroup.cs" />
<Compile Include="BI\DocumentTemplateBI\ManagedGroups\DocumentTemplateManagedGroups.cs" />
<Compile Include="BI\Extensions\AttachmentActionExtensions.cs" />
<Compile Include="BI\Extensions\AuthorizationRoleExtensions.cs" />
<Compile Include="BI\Extensions\ClientServicesExtensions.cs" />
<Compile Include="BI\Extensions\UserFlagActionExtensions.cs" />
<Compile Include="BI\Extensions\DeviceActionExtensions.cs" />
<Compile Include="BI\Extensions\DeviceBatchExtensions.cs" />
<Compile Include="BI\Extensions\DeviceCertificateExtensions.cs" />
<Compile Include="BI\Extensions\DeviceDetailExtensions.cs" />
<Compile Include="BI\Extensions\DeviceModelExtensions.cs" />
<Compile Include="BI\Extensions\DeviceProfileExtensions.cs" />
<Compile Include="BI\Extensions\JobActionExtensions.cs" />
<Compile Include="BI\Extensions\JobExtensions.cs" />
<Compile Include="BI\Extensions\JobFlagExtensions.cs" />
<Compile Include="BI\Extensions\JobQueueActionExtensions.cs" />
<Compile Include="BI\Extensions\UserExtensions.cs" />
<Compile Include="BI\Extensions\WirelessCertificateExtensions.cs" />
<Compile Include="BI\Extensions\DeviceExtensions.cs" />
<Compile Include="BI\DeviceBI\EnrolSafeException.cs" />
<Compile Include="BI\DeviceBI\Enrol.cs" />
<Compile Include="BI\DeviceBI\EnrolmentLog.cs" />
<Compile Include="BI\Extensions\DocumentTemplateExtensions.cs" />
<Compile Include="BI\DocumentTemplateBI\Utilities.cs" />
<Compile Include="BI\Interop\Pdf\Utilities.cs" />
<Compile Include="BI\Interop\Pdf\PdfGenerator.cs" />
<Compile Include="BI\JobBI\Statistics\DailyOpenedClosed.cs" />
<Compile Include="BI\JobBI\Utilities.cs" />
<Compile Include="BI\Extensions\UtilityExtensions.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
@@ -170,24 +109,6 @@
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="Resources\MimeType-img16.png" />
</ItemGroup>
<ItemGroup>
<None Include="Resources\MimeType-pdf16.png" />
</ItemGroup>
<ItemGroup>
<None Include="Resources\EmptyLogo.png" />
</ItemGroup>
<ItemGroup>
<None Include="Resources\MimeType-doc48.png" />
</ItemGroup>
<ItemGroup>
<None Include="Resources\MimeType-pdf48.png" />
</ItemGroup>
<ItemGroup>
<None Include="Resources\MimeType-unknown48.png" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets" Condition="Exists('..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" />
+2 -2
View File
@@ -31,5 +31,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
[assembly: AssemblyVersion("2.2.16272.1003")]
[assembly: AssemblyFileVersion("2.2.16272.1003")]
+1 -51
View File
@@ -1,7 +1,7 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.17929
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@@ -59,55 +59,5 @@ namespace Disco.Properties {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap MimeType_doc48 {
get {
object obj = ResourceManager.GetObject("MimeType_doc48", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap MimeType_img16 {
get {
object obj = ResourceManager.GetObject("MimeType_img16", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap MimeType_pdf16 {
get {
object obj = ResourceManager.GetObject("MimeType_pdf16", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap MimeType_pdf48 {
get {
object obj = ResourceManager.GetObject("MimeType_pdf48", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap MimeType_unknown48 {
get {
object obj = ResourceManager.GetObject("MimeType_unknown48", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
-16
View File
@@ -117,20 +117,4 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="MimeType_doc48" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\MimeType-doc48.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="MimeType_img16" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\MimeType-img16.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="MimeType_pdf16" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\MimeType-pdf16.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="MimeType_pdf48" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\MimeType-pdf48.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="MimeType_unknown48" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\MimeType-unknown48.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

-7
View File
@@ -1,14 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="5.0.0" targetFramework="net45" />
<package id="Exceptionless" version="1.5.2092" targetFramework="net45" />
<package id="Microsoft.Bcl" version="1.1.9" targetFramework="net45" />
<package id="Microsoft.Bcl.Build" version="1.0.14" targetFramework="net45" />
<package id="Microsoft.Net.Http" version="2.2.22" targetFramework="net45" />
<package id="plist.net" version="1.0" targetFramework="net45" />
<package id="Rx-Core" version="2.2.5" targetFramework="net45" />
<package id="Rx-Interfaces" version="2.2.5" targetFramework="net45" />
<package id="Rx-Linq" version="2.2.5" targetFramework="net45" />
<package id="Rx-Main" version="2.2.5" targetFramework="net45" />
<package id="Rx-PlatformServices" version="2.2.5" targetFramework="net45" />
</packages>
+47 -1
View File
@@ -14,6 +14,7 @@
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
<RestorePackages>true</RestorePackages>
<AssemblyVersion>2.2.16272.1003</AssemblyVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
@@ -65,6 +66,42 @@
<Compile Include="..\Disco.Models\ClientServices\Enrol.cs">
<Link>Models\ClientServices\Enrol.cs</Link>
</Compile>
<Compile Include="..\Disco.Models\ClientServices\EnrolmentInformation\Certificate.cs">
<Link>Models\ClientServices\EnrolmentInformation\Certificate.cs</Link>
</Compile>
<Compile Include="..\Disco.Models\ClientServices\EnrolmentInformation\CertificateStore.cs">
<Link>Models\ClientServices\EnrolmentInformation\CertificateStore.cs</Link>
</Compile>
<Compile Include="..\Disco.Models\ClientServices\EnrolmentInformation\DeviceHardware.cs">
<Link>Models\ClientServices\EnrolmentInformation\DeviceHardware.cs</Link>
</Compile>
<Compile Include="..\Disco.Models\ClientServices\EnrolmentInformation\DiskDrive.cs">
<Link>Models\ClientServices\EnrolmentInformation\DiskDrive.cs</Link>
</Compile>
<Compile Include="..\Disco.Models\ClientServices\EnrolmentInformation\DiskDrivePartition.cs">
<Link>Models\ClientServices\EnrolmentInformation\DiskDrivePartition.cs</Link>
</Compile>
<Compile Include="..\Disco.Models\ClientServices\EnrolmentInformation\DiskLogical.cs">
<Link>Models\ClientServices\EnrolmentInformation\DiskLogical.cs</Link>
</Compile>
<Compile Include="..\Disco.Models\ClientServices\EnrolmentInformation\NetworkAdapter.cs">
<Link>Models\ClientServices\EnrolmentInformation\NetworkAdapter.cs</Link>
</Compile>
<Compile Include="..\Disco.Models\ClientServices\EnrolmentInformation\PhysicalMemory.cs">
<Link>Models\ClientServices\EnrolmentInformation\PhysicalMemory.cs</Link>
</Compile>
<Compile Include="..\Disco.Models\ClientServices\EnrolmentInformation\Processor.cs">
<Link>Models\ClientServices\EnrolmentInformation\Processor.cs</Link>
</Compile>
<Compile Include="..\Disco.Models\ClientServices\EnrolmentInformation\WirelessProfile.cs">
<Link>Models\ClientServices\EnrolmentInformation\WirelessProfile.cs</Link>
</Compile>
<Compile Include="..\Disco.Models\ClientServices\EnrolmentInformation\WirelessProfileStore.cs">
<Link>Models\ClientServices\EnrolmentInformation\WirelessProfileStore.cs</Link>
</Compile>
<Compile Include="..\Disco.Models\ClientServices\EnrolmentInformation\WirelessProfileTransformation.cs">
<Link>Models\ClientServices\EnrolmentInformation\WirelessProfileTransformation.cs</Link>
</Compile>
<Compile Include="..\Disco.Models\ClientServices\EnrolResponse.cs">
<Link>Models\ClientServices\EnrolResponse.cs</Link>
</Compile>
@@ -92,10 +129,19 @@
<Compile Include="Extensions\EnrolExtensions.cs" />
<Compile Include="Extensions\WhoAmIExtensions.cs" />
<Compile Include="Interop\Certificates.cs" />
<Compile Include="Interop\Hardware.cs" />
<Compile Include="Interop\LocalAuthentication.cs" />
<Compile Include="Interop\Native\NetworkConnectionStatuses.cs" />
<Compile Include="Interop\Native\ProfileInfoFlags.cs" />
<Compile Include="Interop\Native\WlanApi.cs" />
<Compile Include="Interop\Native\WLAN_INTERFACE_INFO.cs" />
<Compile Include="Interop\Native\WLAN_INTERFACE_INFO_LIST.cs" />
<Compile Include="Interop\Native\WLAN_INTERFACE_STATE.cs" />
<Compile Include="Interop\Native\WLAN_PROFILE_INFO.cs" />
<Compile Include="Interop\Native\WLAN_PROFILE_INFO_LIST.cs" />
<Compile Include="Interop\Network.cs" />
<Compile Include="Interop\WirelessNetwork.cs" />
<Compile Include="Presentation.cs" />
<Compile Include="Interop\SystemAudit.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
+1 -1
View File
@@ -89,7 +89,7 @@ namespace Disco.Client
string reportResponse;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ServicePathTemplate);
request.UserAgent = string.Format("Disco-Client/{0}", Assembly.GetExecutingAssembly().GetName().Version.ToString(3));
request.UserAgent = $"Disco-Client/{Assembly.GetExecutingAssembly().GetName().Version.ToString(3)}";
request.ContentType = "application/json";
request.Method = WebRequestMethods.Http.Post;
request.UseDefaultCredentials = true;
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.Client.Extensions
{
@@ -1,55 +1,60 @@
using System;
using System.Collections.Generic;
using Disco.Models.ClientServices;
using Newtonsoft.Json;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Disco.Models.ClientServices;
using Newtonsoft.Json;
namespace Disco.Client.Extensions
{
public static class ClientServicesExtensions
{
#if DEBUG
public const string ServicePathAuthenticatedTemplate = "http://WS-GSHARP:57252/Services/Client/Authenticated/{0}";
public const string ServicePathUnauthenticatedTemplate = "http://WS-GSHARP:57252/Services/Client/Unauthenticated/{0}";
#else
public const string ServicePathAuthenticatedTemplate = "http://DISCO:9292/Services/Client/Authenticated/{0}";
public const string ServicePathUnauthenticatedTemplate = "http://DISCO:9292/Services/Client/Unauthenticated/{0}";
#endif
public static ResponseType Post<ResponseType>(this ServiceBase<ResponseType> Service, bool Authenticated)
{
string jsonResponse;
ResponseType serviceResponse;
string serviceUrl;
if (Authenticated)
serviceUrl = string.Format(ServicePathAuthenticatedTemplate, Service.Feature);
else
serviceUrl = string.Format(ServicePathUnauthenticatedTemplate, Service.Feature);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serviceUrl);
request.UserAgent = string.Format("Disco-Client/{0}", Assembly.GetExecutingAssembly().GetName().Version.ToString(3));
request.UserAgent = $"Disco-Client/{Assembly.GetExecutingAssembly().GetName().Version.ToString(3)}";
request.ContentType = "application/json";
request.Method = WebRequestMethods.Http.Post;
request.UseDefaultCredentials = true;
request.Timeout = 300000; // 5 Minutes
string jsonRequest = JsonConvert.SerializeObject(Service);
using (StreamWriter requestWriter = new StreamWriter(request.GetRequestStream()))
var jsonSerializer = new JsonSerializer();
using (var requestWriter = new StreamWriter(request.GetRequestStream()))
{
requestWriter.Write(jsonRequest);
using (var jsonWriter = new JsonTextWriter(requestWriter))
{
jsonSerializer.Serialize(jsonWriter, Service);
}
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader responseReader = new StreamReader(response.GetResponseStream()))
using (var responseReader = new StreamReader(response.GetResponseStream()))
{
jsonResponse = responseReader.ReadToEnd();
using (var jsonReader = new JsonTextReader(responseReader))
{
serviceResponse = jsonSerializer.Deserialize<ResponseType>(jsonReader);
}
}
}
if (string.IsNullOrEmpty(jsonResponse))
return default(ResponseType);
else
return JsonConvert.DeserializeObject<ResponseType>(jsonResponse);
return serviceResponse;
}
}
+48 -71
View File
@@ -1,13 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Disco.Client.Interop;
using Disco.Models.ClientServices;
using System.Security.Cryptography.X509Certificates;
using System.IO;
using System.Diagnostics;
using Microsoft.Win32;
using System.Text.RegularExpressions;
using System;
using System.Diagnostics;
using System.IO;
namespace Disco.Client.Extensions
{
@@ -16,26 +12,23 @@ namespace Disco.Client.Extensions
public static void Build(this Enrol enrol)
{
enrol.DeviceUUID = Interop.SystemAudit.DeviceUUID;
enrol.DeviceSerialNumber = Interop.SystemAudit.DeviceSerialNumber;
enrol.ComputerName = Environment.MachineName;
enrol.RunningUserDomain = Environment.UserDomainName;
enrol.RunningUserName = Environment.UserName;
enrol.RunningInteractively = Environment.UserInteractive;
enrol.DeviceComputerName = Interop.LocalAuthentication.ComputerName;
// Hardware Audit
enrol.Hardware = Hardware.Information;
enrol.SerialNumber = enrol.Hardware.SerialNumber;
enrol.DeviceManufacturer = Interop.SystemAudit.DeviceManufacturer;
enrol.DeviceModel = Interop.SystemAudit.DeviceModel;
enrol.DeviceModelType = Interop.SystemAudit.DeviceType;
enrol.DeviceIsPartOfDomain = Interop.SystemAudit.DeviceIsPartOfDomain;
enrol.DeviceDNSDomainName = Interop.SystemAudit.DeviceDNSDomainName;
// LAN
enrol.DeviceLanMacAddress = Interop.Network.PrimaryLanMacAddress;
// WAN
enrol.DeviceWlanMacAddress = Interop.Network.PrimaryWlanMacAddress;
// Apply System Information
enrol.ApplySystemInformation();
// Certificates
enrol.DeviceCertificates = Interop.Certificates.GetCertificateSubjects(StoreName.My, StoreLocation.LocalMachine);
enrol.Certificates = Certificates.GetAllCertificates();
// Wireless Profiles
enrol.WirelessProfiles = WirelessNetwork.GetWirelessProfiles();
}
public static void Process(this EnrolResponse enrolResponse)
@@ -51,12 +44,14 @@ namespace Disco.Client.Extensions
// Offline Domain Join
bool requireReboot = enrolResponse.ApplyOfflineDomainJoin();
// Certificates
enrolResponse.ApplyDeviceCertificates();
// Device Owner
enrolResponse.ApplyDeviceAssignedUser();
// Certificates
enrolResponse.ApplyDeviceCertificates();
// Wireless Profiles
enrolResponse.ApplyWirelessProfiles();
Presentation.UpdateStatus("Enrolling Device", "Device Enrolment Successfully Completed", false, 0, 1500);
@@ -71,15 +66,15 @@ namespace Disco.Client.Extensions
/// <returns>Boolean indicating whether a reboot is required.</returns>
private static bool ApplyOfflineDomainJoin(this EnrolResponse enrolResponse)
{
if (!string.IsNullOrWhiteSpace(enrolResponse.OfflineDomainJoin))
if (!string.IsNullOrWhiteSpace(enrolResponse.OfflineDomainJoinManifest))
{
Presentation.UpdateStatus("Enrolling Device", string.Format("Performing Offline Domain Join:{0}Renaming Computer: {1} -> {2}", Environment.NewLine, Interop.LocalAuthentication.ComputerName, enrolResponse.DeviceComputerName), true, -1, 1500);
Presentation.UpdateStatus("Enrolling Device", $"Performing Offline Domain Join:\r\nRenaming Computer: {Environment.MachineName} -> {enrolResponse.ComputerName}", true, -1, 1500);
string odjFile = Path.GetTempFileName();
File.WriteAllBytes(odjFile, Convert.FromBase64String(enrolResponse.OfflineDomainJoin));
File.WriteAllBytes(odjFile, Convert.FromBase64String(enrolResponse.OfflineDomainJoinManifest));
string odjWindowsPath = Environment.GetEnvironmentVariable("SystemRoot");
string odjProcessArguments = string.Format("/REQUESTODJ /LOADFILE \"{0}\" /WINDOWSPATH \"{1}\" /LOCALOS", odjFile, odjWindowsPath);
string odjProcessArguments = $"/REQUESTODJ /LOADFILE \"{odjFile}\" /WINDOWSPATH \"{odjWindowsPath}\" /LOCALOS";
ProcessStartInfo odjProcessStartInfo = new ProcessStartInfo("DJOIN.EXE", odjProcessArguments)
{
@@ -95,17 +90,17 @@ namespace Disco.Client.Extensions
odjResult = odjProcess.StandardOutput.ReadToEnd();
odjProcess.WaitForExit(20000); // 20 Seconds
}
Presentation.UpdateStatus("Enrolling Device", string.Format("Offline Domain Join Result:{0}{1}", Environment.NewLine, odjResult), true, -1, 3000);
Presentation.UpdateStatus("Enrolling Device", $"Offline Domain Join Result:\r\n{odjResult}", true, -1, 3000);
if (File.Exists(odjFile))
File.Delete(odjFile);
// Flush Logged-On History
if (!string.IsNullOrEmpty(enrolResponse.DeviceDomainName))
if (!string.IsNullOrEmpty(enrolResponse.DomainName))
{
using (RegistryKey regWinlogon = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", true))
{
regWinlogon.SetValue("DefaultDomainName", enrolResponse.DeviceDomainName, RegistryValueKind.String);
regWinlogon.SetValue("DefaultDomainName", enrolResponse.DomainName, RegistryValueKind.String);
regWinlogon.SetValue("DefaultUserName", String.Empty, RegistryValueKind.String);
}
using (RegistryKey regLogonUI = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI", true))
@@ -130,62 +125,44 @@ namespace Disco.Client.Extensions
private static void ApplyDeviceAssignedUser(this EnrolResponse enrolResponse)
{
// Only run task if Assigned User was specified
if (!string.IsNullOrWhiteSpace(enrolResponse.DeviceAssignedUserSID))
if (!string.IsNullOrWhiteSpace(enrolResponse.AssignedUserSID))
{
Presentation.UpdateStatus("Enrolling Device", string.Format(@"Configuring the device owner:{0}{1} ({2}\{3})", Environment.NewLine, enrolResponse.DeviceAssignedUserName, enrolResponse.DeviceAssignedUserDomain, enrolResponse.DeviceAssignedUserUsername), true, -1, 3000);
Presentation.UpdateStatus("Enrolling Device", $"Configuring the device owner:\r\n{enrolResponse.AssignedUserDescription} ({enrolResponse.AssignedUserDomain}\\{enrolResponse.AssignedUserUsername})", true, -1, 3000);
if (enrolResponse.DeviceAssignedUserIsLocalAdmin)
Interop.LocalAuthentication.AddLocalGroupMembership("Administrators", enrolResponse.DeviceAssignedUserSID, enrolResponse.DeviceAssignedUserUsername, enrolResponse.DeviceAssignedUserDomain);
if (enrolResponse.AssignedUserIsLocalAdmin)
Interop.LocalAuthentication.AddLocalGroupMembership("Administrators", enrolResponse.AssignedUserSID, enrolResponse.AssignedUserUsername, enrolResponse.AssignedUserDomain);
// Make Windows think this user was the last to logon
using (RegistryKey regWinlogon = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", true))
{
regWinlogon.SetValue("DefaultDomainName", enrolResponse.DeviceAssignedUserDomain, RegistryValueKind.String);
regWinlogon.SetValue("DefaultUserName", enrolResponse.DeviceAssignedUserUsername, RegistryValueKind.String);
regWinlogon.SetValue("DefaultDomainName", enrolResponse.AssignedUserDomain, RegistryValueKind.String);
regWinlogon.SetValue("DefaultUserName", enrolResponse.AssignedUserUsername, RegistryValueKind.String);
}
using (RegistryKey regLogonUI = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI", true))
{
regLogonUI.SetValue("LastLoggedOnUser", string.Format(@"{0}\{1}", enrolResponse.DeviceAssignedUserDomain, enrolResponse.DeviceAssignedUserUsername), RegistryValueKind.String);
regLogonUI.SetValue("LastLoggedOnUser", $@"{enrolResponse.AssignedUserDomain}\{enrolResponse.AssignedUserUsername}", RegistryValueKind.String);
}
}
}
/// <summary>
/// Processes a Client Service Enrol Response for Device Certificate Actions
/// </summary>
/// <param name="enrolResponse"></param>
private static void ApplyDeviceCertificates(this EnrolResponse enrolResponse)
{
// Only run if a Certificate was supplied
if (!string.IsNullOrEmpty(enrolResponse.DeviceCertificate))
if (enrolResponse.Certificates != null)
{
Presentation.UpdateStatus("Enrolling Device", "Configuring Wireless Certificates", true, -1, 1000);
Presentation.UpdateStatus("Enrolling Device", "Configuring Certificates", true, -1, 1000);
var certPersonalBytes = Convert.FromBase64String(enrolResponse.DeviceCertificate);
var certPersonal = new X509Certificate2(certPersonalBytes, "password", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
if (certPersonal == null)
throw new ClientServiceException("Enrolment > Device Certificate", "Unable to Import Device Certificate Provided, possibly check password.");
// Certificate Removal
if (enrolResponse.DeviceCertificateRemoveExisting != null && enrolResponse.DeviceCertificateRemoveExisting.Count > 0)
{
List<Regex> regExMatchesSubject = new List<Regex>();
foreach (var subjectRegEx in enrolResponse.DeviceCertificateRemoveExisting)
regExMatchesSubject.Add(new Regex(subjectRegEx, RegexOptions.IgnoreCase));
// Remove from 'My' Store
Interop.Certificates.RemoveCertificates(StoreName.My, StoreLocation.LocalMachine, regExMatchesSubject, certPersonal);
// Remove from 'Root' Store
Interop.Certificates.RemoveCertificates(StoreName.Root, StoreLocation.LocalMachine, regExMatchesSubject, certPersonal);
// Remove from 'CertificateAuthority' Store
Interop.Certificates.RemoveCertificates(StoreName.CertificateAuthority, StoreLocation.LocalMachine, regExMatchesSubject, certPersonal);
}
// Add Certificate
Presentation.UpdateStatus("Enrolling Device", string.Format("Configuring Wireless Certificates{0}Installing Certificate: {1}", Environment.NewLine, Interop.Certificates.GetCertificateFriendlyName(certPersonal)), true, -1);
Interop.Certificates.AddCertificate(StoreName.My, StoreLocation.LocalMachine, certPersonal);
enrolResponse.Certificates.Apply();
}
}
private static void ApplyWirelessProfiles(this EnrolResponse enrolResponse)
{
if (enrolResponse.WirelessProfiles != null)
{
Presentation.UpdateStatus("Enrolling Device", "Configuring Wireless Profiles", true, -1, 1000);
enrolResponse.WirelessProfiles.Apply();
}
}
}
}
+89 -62
View File
@@ -1,103 +1,130 @@
using System;
using Disco.Models.ClientServices.EnrolmentInformation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
namespace Disco.Client.Interop
{
public static class Certificates
{
public static string GetCertificateFriendlyName(X509Certificate2 Certificate)
public static List<Certificate> GetAllCertificates()
{
string subject = Certificate.Subject;
return subject.Substring(subject.IndexOf("=") + 1, subject.IndexOf(",") - subject.IndexOf("=") - 1);
var certificates = new List<Certificate>();
// Trusted Root Certificates
certificates.AddRange(GetCertificates(StoreName.Root, "TrustedRoot"));
// Intermediate Certificates
certificates.AddRange(GetCertificates(StoreName.CertificateAuthority, "Intermediate"));
// Personal Certificates
certificates.AddRange(GetCertificates(StoreName.My, "Personal"));
return certificates;
}
public static List<string> GetCertificateSubjects(StoreName StoreName, StoreLocation StoreLocation)
private static IEnumerable<Certificate> GetCertificates(StoreName StoreName, string StoreDescription)
{
X509Store certStore = new X509Store(StoreName, StoreLocation);
certStore.Open(OpenFlags.ReadOnly);
var certSubjects = certStore.Certificates.Cast<X509Certificate2>().Select(c => c.Subject).ToList();
certStore.Close();
return certSubjects;
}
public static bool AddCertificate(StoreName StoreName, StoreLocation StoreLocation, X509Certificate2 Certificate)
{
X509Store certStore = new X509Store(StoreName, StoreLocation);
bool certAlreadyAdded = false;
certStore.Open(OpenFlags.ReadWrite);
var store = new X509Store(StoreName, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
try
{
foreach (X509Certificate2 cert in certStore.Certificates)
foreach (var certificate in store.Certificates)
{
if (cert.SerialNumber.Equals(Certificate.SerialNumber))
yield return new Certificate()
{
certAlreadyAdded = true;
break;
}
}
if (!certAlreadyAdded)
{
Presentation.UpdateStatus("Enrolling Device", string.Format("Configuring Wireless Certificates{0}Adding Certificate: '{1}' from {2}@{3}", Environment.NewLine, GetCertificateFriendlyName(Certificate), StoreName.ToString(), StoreLocation.ToString()), true, -1, 3000);
certStore.Add(Certificate);
Store = StoreDescription,
SubjectName = certificate.SubjectName.Name,
Thumbprint = certificate.Thumbprint,
FriendlyName = certificate.FriendlyName,
DnsName = certificate.GetNameInfo(X509NameType.DnsName, false),
Version = certificate.Version,
SignatureAlgorithm = certificate.SignatureAlgorithm.FriendlyName,
Issuer = certificate.IssuerName.Name,
NotAfter = certificate.NotAfter,
NotBefore = certificate.NotBefore,
HasPrivateKey = certificate.HasPrivateKey
};
}
}
catch (Exception) { throw; }
finally
{
certStore.Close();
store.Close();
}
return !certAlreadyAdded;
}
public static List<string> RemoveCertificates(StoreName StoreName, StoreLocation StoreLocation, List<Regex> RegExMatchesSubject, X509Certificate2 CertificateException)
public static void Apply(this CertificateStore EnrolStore)
{
X509Store certStore = new X509Store(StoreName, StoreLocation);
List<string> results = new List<string>();
List<X509Certificate2> certStoreRemove = new List<X509Certificate2>();
certStore.Open(OpenFlags.ReadWrite);
try
if (EnrolStore != null)
{
foreach (X509Certificate2 cert in certStore.Certificates)
// Apply Trusted Root
ApplyToStore(StoreName.Root, EnrolStore.TrustedRootCertificates, EnrolStore.TrustedRootRemoveThumbprints);
// Apply Intermediate
ApplyToStore(StoreName.CertificateAuthority, EnrolStore.IntermediateCertificates, EnrolStore.IntermediateRemoveThumbprints);
// Apply Personal
ApplyToStore(StoreName.My, EnrolStore.PersonalCertificates, EnrolStore.PersonalRemoveThumbprints);
}
}
private static void ApplyToStore(StoreName StoreName, List<byte[]> Certificates, List<string> RemoveThumbprints)
{
if ((Certificates != null && Certificates.Count > 0) ||
(RemoveThumbprints != null && RemoveThumbprints.Count > 0))
{
var store = new X509Store(StoreName, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadWrite);
try
{
if (!cert.SerialNumber.Equals(CertificateException.SerialNumber))
var addedThumbprints = new List<string>();
var existingThumbprints = store.Certificates.Cast<X509Certificate2>().GroupBy(c => c.Thumbprint).ToDictionary(c => c.Key, c => c.ToList(), StringComparer.OrdinalIgnoreCase);
// Add
if (Certificates != null && Certificates.Count > 0)
{
foreach (var subjectRegEx in RegExMatchesSubject)
foreach (var certificateBytes in Certificates)
{
if (subjectRegEx.IsMatch(cert.Subject))
var certificate = new X509Certificate2(certificateBytes, "password", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
// check if it already exists
if (!existingThumbprints.ContainsKey(certificate.Thumbprint) && !addedThumbprints.Contains(certificate.Thumbprint))
{
certStoreRemove.Add(cert);
break;
Presentation.UpdateStatus("Enrolling Device", $"Configuring Certificates\r\nAdding Certificate: '{certificate.GetNameInfo(X509NameType.DnsName, false)}' from {store.Name}@{store.Location}", true, -1, 1000);
store.Add(certificate);
addedThumbprints.Add(certificate.Thumbprint);
}
}
}
// Remove
if (RemoveThumbprints != null && RemoveThumbprints.Count > 0)
{
foreach (var thumbprint in RemoveThumbprints)
{
List<X509Certificate2> certificates;
if (existingThumbprints.TryGetValue(thumbprint, out certificates) && !addedThumbprints.Contains(thumbprint))
{
foreach (var certificate in certificates)
{
Presentation.UpdateStatus("Enrolling Device", $"Configuring Certificates\r\nRemoving Certificate: '{certificate.GetNameInfo(X509NameType.DnsName, false)}' from {store.Name}@{store.Location}", true, -1, 1000);
store.Remove(certificate);
existingThumbprints.Remove(thumbprint);
}
}
}
}
}
foreach (var cert in certStoreRemove)
finally
{
results.Add(cert.Subject);
Presentation.UpdateStatus("Enrolling Device", string.Format("Configuring Wireless Certificates{0}Removing Certificate: '{1}' from {2}@{3}", Environment.NewLine, GetCertificateFriendlyName(cert), StoreName.ToString(), StoreLocation.ToString()), true, -1, 1500);
certStore.Remove(cert);
store.Close();
}
}
catch (Exception) { throw; }
finally
{
certStore.Close();
}
return results;
}
}
}
+277
View File
@@ -0,0 +1,277 @@
using Disco.Models.ClientServices;
using Disco.Models.ClientServices.EnrolmentInformation;
using System;
using System.Linq;
using System.Management;
namespace Disco.Client.Interop
{
public static class Hardware
{
private static DeviceHardware information;
public static DeviceHardware Information
{
get
{
if (information == null)
{
information = GatherInformation();
}
return information;
}
}
private static DeviceHardware GatherInformation()
{
var audit = new DeviceHardware();
audit.ApplyBIOSInformation();
audit.ApplySystemInformation();
audit.ApplyBaseBoardInformation();
audit.ApplySystemProductInformation();
if (string.IsNullOrWhiteSpace(audit.SerialNumber))
{
throw new Exception("This device has no serial number stored in BIOS or BaseBoard");
}
if (audit.SerialNumber.Length > 60)
{
throw new Exception($"The serial number reported by this device is over 60 characters long:\r\n{audit.SerialNumber}");
}
#warning TODO: Processors, PhysicalMemory, DiskDrives, etc
audit.NetworkAdapters = Network.GetNetworkAdapters();
return audit;
}
private static void ApplyBIOSInformation(this DeviceHardware DeviceHardware)
{
try
{
using (var mSearcher = new ManagementObjectSearcher("SELECT SerialNumber, SMBIOSBIOSVersion FROM Win32_BIOS WHERE PrimaryBios=true"))
{
using (var mResults = mSearcher.Get())
{
using (var mItem = mResults.Cast<ManagementObject>().FirstOrDefault())
{
if (mItem != null)
{
var serialNumber = (string)mItem.GetPropertyValue("SerialNumber");
if (!string.IsNullOrWhiteSpace(serialNumber))
{
DeviceHardware.SerialNumber = serialNumber.Trim();
}
ErrorReporting.DeviceIdentifier = DeviceHardware.SerialNumber;
}
else
{
throw new Exception("No Win32_BIOS WHERE PrimaryBios=true was found");
}
}
}
}
}
catch (Exception ex)
{
throw new Exception("Disco Client was unable to retrieve BIOS information from WMI", ex);
}
}
private static void ApplySystemInformation(this DeviceHardware DeviceHardware)
{
try
{
using (var mSearcher = new ManagementObjectSearcher("SELECT Manufacturer, Model, PartOfDomain, PCSystemType, Domain FROM Win32_ComputerSystem"))
{
using (var mResults = mSearcher.Get())
{
using (var mItem = mResults.Cast<ManagementObject>().FirstOrDefault())
{
if (mItem != null)
{
var manufacturer = (string)mItem.GetPropertyValue("Manufacturer");
if (!string.IsNullOrWhiteSpace(manufacturer))
{
DeviceHardware.Manufacturer = manufacturer.Trim();
}
var model = (string)mItem.GetPropertyValue("Model");
if (!string.IsNullOrWhiteSpace(model))
{
DeviceHardware.Model = model.ToString();
}
DeviceHardware.ModelType = ((PCSystemTypes)mItem.GetPropertyValue("PCSystemType")).Description();
}
else
{
throw new Exception("No Win32_ComputerSystem was found");
}
}
}
}
}
catch (Exception ex)
{
throw new Exception("Disco Client was unable to retrieve ComputerSystem information from WMI", ex);
}
}
public static void ApplySystemInformation(this Enrol Enrol)
{
try
{
using (var mSearcher = new ManagementObjectSearcher("SELECT PartOfDomain, Domain FROM Win32_ComputerSystem"))
{
using (var mResults = mSearcher.Get())
{
using (var mItem = mResults.Cast<ManagementObject>().FirstOrDefault())
{
if (mItem != null)
{
Enrol.IsPartOfDomain = (bool)mItem.GetPropertyValue("PartOfDomain");
if (Enrol.IsPartOfDomain)
{
Enrol.DNSDomainName = (string)mItem.GetPropertyValue("Domain");
}
}
else
{
throw new Exception("No Win32_ComputerSystem was found");
}
}
}
}
}
catch (Exception ex)
{
throw new Exception("Disco Client was unable to retrieve ComputerSystem information from WMI", ex);
}
}
private static void ApplyBaseBoardInformation(this DeviceHardware DeviceHardware)
{
// Added 2012-11-22 G# - Lenovo IdeaPad Serial SHIM
// http://www.discoict.com.au/forum/feature-requests/2012/11/serial-number-detection-on-ideapads.aspx
if (string.IsNullOrWhiteSpace(DeviceHardware.SerialNumber) ||
(DeviceHardware.Manufacturer.Equals("LENOVO", StringComparison.OrdinalIgnoreCase) &&
(DeviceHardware.Model.Equals("S10-3", StringComparison.OrdinalIgnoreCase) // S10-3
|| DeviceHardware.Model.Equals("2957", StringComparison.OrdinalIgnoreCase)))) // S10-2
{
try
{
using (var mSearcher = new ManagementObjectSearcher("SELECT SerialNumber FROM Win32_BaseBoard"))
{
using (var mResults = mSearcher.Get())
{
using (var mItem = mResults.Cast<ManagementObject>().FirstOrDefault())
{
if (mItem != null)
{
var serialNumber = (string)mItem.GetPropertyValue("SerialNumber");
if (!string.IsNullOrWhiteSpace(serialNumber))
{
DeviceHardware.SerialNumber = serialNumber.Trim();
ErrorReporting.DeviceIdentifier = DeviceHardware.SerialNumber;
}
}
else
{
throw new Exception("No Win32_BaseBoard was found");
}
}
}
}
}
catch (Exception ex)
{
throw new Exception("Disco Client was unable to retrieve BaseBoard information from WMI", ex);
}
}
}
private static void ApplySystemProductInformation(this DeviceHardware DeviceHardware)
{
try
{
using (var mSearcher = new ManagementObjectSearcher("SELECT IdentifyingNumber, UUID FROM Win32_ComputerSystemProduct"))
{
using (var mResults = mSearcher.Get())
{
using (var mItem = mResults.Cast<ManagementObject>().FirstOrDefault())
{
if (mItem != null)
{
if (DeviceHardware.SerialNumber == null)
{
var serialNumber = mItem.GetPropertyValue("IdentifyingNumber") as string;
if (!string.IsNullOrWhiteSpace(serialNumber))
{
DeviceHardware.SerialNumber = serialNumber.Trim();
ErrorReporting.DeviceIdentifier = DeviceHardware.SerialNumber;
}
}
var uUID = (string)mItem.GetPropertyValue("UUID");
if (!string.IsNullOrWhiteSpace(uUID))
DeviceHardware.UUID = uUID.Trim();
}
else
{
throw new Exception("No Win32_ComputerSystemProduct was found");
}
}
}
}
}
catch (Exception ex)
{
throw new Exception("Disco Client was unable to retrieve ComputerSystemProduct information from WMI", ex);
}
}
private static string Description(this PCSystemTypes type)
{
switch (type)
{
case PCSystemTypes.Desktop:
return "Desktop";
case PCSystemTypes.Mobile:
return "Mobile";
case PCSystemTypes.Workstation:
return "Workstation";
case PCSystemTypes.EnterpriseServer:
return "Enterprise Server";
case PCSystemTypes.SmallOfficeAndHomeOfficeServer:
return "Small Office And Home Office Server";
case PCSystemTypes.AppliancePC:
return "Appliance PC";
case PCSystemTypes.PerformanceServer:
return "Performance Server";
case PCSystemTypes.Maximum:
return "Maximum";
case PCSystemTypes.Unknown:
default:
return "Unknown";
}
}
private enum PCSystemTypes : ushort
{
Unknown = 0,
Desktop,
Mobile,
Workstation,
EnterpriseServer,
SmallOfficeAndHomeOfficeServer,
AppliancePC,
PerformanceServer,
Maximum
}
}
}
+4 -31
View File
@@ -1,10 +1,6 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.Client.Interop
{
@@ -14,7 +10,7 @@ namespace Disco.Client.Interop
public static bool AddLocalGroupMembership(string GroupName, string UserSID, string Username, string UserDomain)
{
using (DirectoryEntry group = new DirectoryEntry(string.Format("WinNT://./{0},group", GroupName)))
using (DirectoryEntry group = new DirectoryEntry($"WinNT://./{GroupName},group"))
{
// Check to see if the User is already a member
foreach (object memberRef in (IEnumerable)group.Invoke("Members"))
@@ -22,38 +18,15 @@ namespace Disco.Client.Interop
using (DirectoryEntry member = new DirectoryEntry(memberRef))
{
var memberPath = member.Path;
if (memberPath.Equals(string.Format("WinNT://{0}/{1}", UserDomain, Username), StringComparison.OrdinalIgnoreCase) ||
memberPath.Equals(string.Format("WinNT://{0}", UserSID), StringComparison.OrdinalIgnoreCase))
if (memberPath.Equals($"WinNT://{UserDomain}/{Username}", StringComparison.OrdinalIgnoreCase) ||
memberPath.Equals($"WinNT://{UserSID}", StringComparison.OrdinalIgnoreCase))
return false;
}
}
group.Invoke("Add", string.Format("WinNT://{0}", UserSID));
group.Invoke("Add", $"WinNT://{UserSID}");
}
return true;
}
public static string CurrentUserDomain
{
get
{
return Environment.UserDomainName;
}
}
public static string CurrentUserName
{
get
{
return Environment.UserName;
}
}
public static string ComputerName
{
get
{
return Environment.MachineName;
}
}
}
}
@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Disco.Client.Interop.Native
{
public enum NetworkConnectionStatuses : ushort
{
Disconnected = 0,
Connecting,
Connected,
Disconnecting,
HardwareNotPresent,
HardwareDisabled,
HardwareMalfunction,
MediaDisconnected,
Authenticating,
AuthenticationSucceeded,
AuthenticationFailed,
InvalidAddress,
CredentialsRequired
}
}
@@ -0,0 +1,11 @@
using System;
namespace Disco.Client.Interop.Native
{
[Flags]
public enum ProfileInfoFlags : uint
{
WLAN_PROFILE_GROUP_POLICY = 1,
WLAN_PROFILE_USER = 2
}
}
@@ -0,0 +1,30 @@
using System;
using System.Runtime.InteropServices;
namespace Disco.Client.Interop.Native
{
/// <summary >
/// The WLAN_INTERFACE_INFO structure contains information about a wireless LAN interface.
/// </summary >
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WLAN_INTERFACE_INFO
{
/// <summary>
/// Contains the GUID of the interface.
/// </summary>
public Guid InterfaceGuid;
/// <summary>
/// Contains the description of the interface.
/// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string strInterfaceDescription;
/// <summary>
/// Contains a WLAN_INTERFACE_STATE value that indicates the current state of the interface.
/// Windows XP with SP3 and Wireless LAN API for Windows XP with SP2:  Only the wlan_interface_state_connected,
/// wlan_interface_state_disconnected, and wlan_interface_state_authenticating values are supported.
/// </summary>
public WLAN_INTERFACE_STATE isState;
}
}
@@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Disco.Client.Interop.Native
{
/// <summary>
/// The WLAN_INTERFACE_INFO_LIST structure contains an array of NIC interface information.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct WLAN_INTERFACE_INFO_LIST
{
/// <summary>
/// Contains the number of items in the InterfaceInfo member.
/// </summary>
public uint dwNumberOfItems;
/// <summary>
/// The index of the current item. The index of the first item is 0. dwIndex must be less than dwNumberOfItems.
/// This member is not used by the wireless service. Applications can use this member when processing individual
/// interfaces in the WLAN_INTERFACE_INFO_LIST structure. When an application passes this structure from one
/// function to another, it can set the value of dwIndex to the index of the item currently being processed.
/// This can help an application maintain state.
/// dwIndex should always be initialized before use.
/// </summary>
public uint dwIndex;
private IntPtr InterfaceInfoPtr;
/// <summary>
/// An array of WLAN_INTERFACE_INFO structures containing interface information.
/// </summary>
public IEnumerable<WLAN_INTERFACE_INFO> InterfaceInfo
{
get
{
var size = Marshal.SizeOf(typeof(WLAN_INTERFACE_INFO));
for (int i = 0; i < dwNumberOfItems; i++)
{
yield return (WLAN_INTERFACE_INFO)Marshal.PtrToStructure(InterfaceInfoPtr + (i * size), typeof(WLAN_INTERFACE_INFO));
}
}
}
public WLAN_INTERFACE_INFO_LIST(IntPtr Pointer)
{
dwNumberOfItems = (uint)Marshal.ReadInt32(Pointer, 0);
dwIndex = (uint)Marshal.ReadInt32(Pointer, 4);
InterfaceInfoPtr = Pointer + 8;
}
}
}
@@ -0,0 +1,43 @@
namespace Disco.Client.Interop.Native
{
/// <summary>
/// The WLAN_INTERFACE_STATE enumerated type indicates the state of an interface.
/// Windows XP with SP3 and Wireless LAN API for Windows XP with SP2:  Only the wlan_interface_state_connected,
/// wlan_interface_state_disconnected, and wlan_interface_state_authenticating values are supported.
/// </summary>
public enum WLAN_INTERFACE_STATE
{
/// <summary>
/// The interface is not ready to operate.
/// </summary>
wlan_interface_state_not_ready = 0,
/// <summary>
/// The interface is connected to a network.
/// </summary>
wlan_interface_state_connected = 1,
/// <summary>
/// The interface is the first node in an ad hoc network. No peer has connected.
/// </summary>
wlan_interface_state_ad_hoc_network_formed = 2,
/// <summary>
/// The interface is disconnecting from the current network.
/// </summary>
wlan_interface_state_disconnecting = 3,
/// <summary>
/// The interface is not connected to any network.
/// </summary>
wlan_interface_state_disconnected = 4,
/// <summary>
/// The interface is attempting to associate with a network.
/// </summary>
wlan_interface_state_associating = 5,
/// <summary>
/// Auto configuration is discovering the settings for the network.
/// </summary>
wlan_interface_state_discovering = 6,
/// <summary>
/// The interface is in the process of authenticating.
/// </summary>
wlan_interface_state_authenticating = 7,
}
}
@@ -0,0 +1,24 @@
using System.Runtime.InteropServices;
namespace Disco.Client.Interop.Native
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WLAN_PROFILE_INFO
{
/// <summary>
/// The name of the profile. This value may be the name of a domain if the profile is for provisioning. Profile names are case-sensitive.
/// This string must be NULL-terminated.
/// Windows XP with SP3 and Wireless LAN API for Windows XP with SP2:  The name of the profile is derived automatically from
/// the SSID of the wireless network. For infrastructure network profiles, the name of the profile is the SSID of the network.
/// For ad hoc network profiles, the name of the profile is the SSID of the ad hoc network followed by -adhoc.
/// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string strInterfaceDescription;
/// <summary>
/// A set of flags specifying settings for wireless profile. These values are defined in the Wlanapi.h header file.
/// Windows XP with SP3 and Wireless LAN API for Windows XP with SP2:  dwFlags must be 0. Per-user profiles are not supported.
/// </summary>
public ProfileInfoFlags dwFlags;
}
}
@@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Disco.Client.Interop.Native
{
public struct WLAN_PROFILE_INFO_LIST
{
/// <summary>
/// The number of wireless profile entries in the ProfileInfo member.
/// </summary>
public uint dwNumberOfItems;
/// <summary>
/// The index of the current item. The index of the first item is 0. The dwIndex member must be less than the dwNumberOfItems member.
/// This member is not used by the wireless service. Applications can use this member when processing individual profiles in the
/// WLAN_PROFILE_INFO_LIST structure. When an application passes this structure from one function to another, it can set the value
/// of dwIndex to the index of the item currently being processed. This can help an application maintain state.
/// dwIndex should always be initialized before use.
/// </summary>
public uint dwIndex;
private IntPtr ProfileInfoPointer;
/// <summary>
/// An array of WLAN_PROFILE_INFO structures containing interface information. The number of items in the array is specified in the dwNumberOfItems member.
/// </summary>
public IEnumerable<WLAN_PROFILE_INFO> ProfileInfo
{
get
{
var size = Marshal.SizeOf(typeof(WLAN_PROFILE_INFO));
for (int i = 0; i < dwNumberOfItems; i++)
{
yield return (WLAN_PROFILE_INFO)Marshal.PtrToStructure(ProfileInfoPointer + (i * size), typeof(WLAN_PROFILE_INFO));
}
}
}
public WLAN_PROFILE_INFO_LIST(IntPtr Pointer)
{
dwNumberOfItems = (uint)Marshal.ReadInt32(Pointer, 0);
dwIndex = (uint)Marshal.ReadInt32(Pointer, 4);
ProfileInfoPointer = Pointer + 8;
}
}
}
+207
View File
@@ -0,0 +1,207 @@
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Disco.Client.Interop.Native
{
public static class WlanApi
{
public const uint WLAN_API_VERSION_2_0 = 2; // Windows Vista WiFi API Version
public const int ERROR_SUCCESS = 0;
public const int ERROR_INVALID_PARAMETER = 87;
public const int ERROR_NOT_ENOUGH_MEMORY = 8;
/// <summary>
/// The WlanOpenHandle function opens a connection to the server.
/// </summary>
/// <param name="dwClientVersion">The highest version of the WLAN API that the client supports.
/// 1 = Client version for Windows XP with SP3 and Wireless LAN API for Windows XP with SP2.
/// 2 = Client version for Windows Vista and Windows Server 2008</param>
/// <param name="pReserved">Reserved for future use. Must be set to NULL.</param>
/// <param name="pdwNegotiatedVersion">The version of the WLAN API that will be used in this session. This value is usually the highest version supported by both the client and server.</param>
/// <param name="phClientHandle">A handle for the client to use in this session. This handle is used by other functions throughout the session.</param>
/// <returns>
/// If the function succeeds, the return value is ERROR_SUCCESS.
/// If the function fails, the return value may be one of the following return codes.
/// ERROR_INVALID_PARAMETER: pdwNegotiatedVersion is NULL, phClientHandle is NULL, or pReserved is not NULL.
/// ERROR_NOT_ENOUGH_MEMORY: Failed to allocate memory to create the client context.
/// RPC_STATUS: Various error codes.
/// ERROR_REMOTE_SESSION_LIMIT_EXCEEDED: Too many handles have been issued by the server.
/// </returns>
/// <remarks>
/// The version number specified by dwClientVersion and pdwNegotiatedVersion is a composite version number
/// made up of both major and minor versions. The major version is specified by the low-order word, and the
/// minor version is specified by the high-order word. The macros WLAN_API_VERSION_MAJOR(_v) and
/// WLAN_API_VERSION_MINOR(_v) return the major and minor version numbers respectively.
/// You can construct a version number using the macro WLAN_API_MAKE_VERSION(_major, _minor).
/// Windows XP with SP3 and Wireless LAN API for Windows XP with SP2:  WlanOpenHandle will return an
/// error message if the Wireless Zero Configuration (WZC) service has not been started or if the WZC service is not responsive.
/// </remarks>
[DllImport("Wlanapi.dll")]
public static extern uint WlanOpenHandle(uint dwClientVersion, IntPtr pReserved, out uint pdwNegotiatedVersion, out IntPtr phClientHandle);
/// <summary>
/// The WlanCloseHandle function closes a connection to the server.
/// </summary>
/// <param name="hClientHandle">The client's session handle, which identifies the connection to be closed. This handle was obtained by a previous call to the WlanOpenHandle function.</param>
/// <param name="pReserved">Reserved for future use. Set this parameter to NULL.</param>
/// <returns>
/// If the function succeeds, the return value is ERROR_SUCCESS.
/// If the function fails, the return value may be one of the following return codes.
/// ERROR_INVALID_PARAMETER: hClientHandle is NULL or invalid, or pReserved is not NULL.
/// ERROR_INVALID_HANDLE: The handle hClientHandle was not found in the handle table.
/// RPC_STATUS: Various error codes.
/// </returns>
/// <remarks>
/// After a connection has been closed, any attempted use of the closed handle can cause unexpected errors.
/// Upon closing, all outstanding notifications are discarded.
/// Do not call WlanCloseHandle from a callback function. If the client is in the middle of a
/// notification callback when WlanCloseHandle is called, the function waits for the callback to
/// finish before returning a value. Calling this function inside a callback function will result in
/// the call never completing. If both the callback function and the thread that closes the handle try
/// to acquire the same lock, a deadlock may occur. In addition, do not call WlanCloseHandle from
/// the DllMain function in an application DLL. This could also cause a deadlock.
/// </remarks>
[DllImport("Wlanapi")]
public static extern uint WlanCloseHandle(IntPtr hClientHandle, IntPtr pReserved);
/// <summary>
/// The WlanEnumInterfaces function enumerates all of the wireless LAN interfaces currently enabled on the local computer.
/// </summary>
/// <param name="hClientHandle">The client's session handle, obtained by a previous call to the WlanOpenHandle function.</param>
/// <param name="pReserved">Reserved for future use. This parameter must be set to NULL.</param>
/// <param name="ppInterfaceList">
/// A pointer to storage for a pointer to receive the returned list of wireless LAN interfaces in a WLAN_INTERFACE_INFO_LIST structure.
/// The buffer for the WLAN_INTERFACE_INFO_LIST returned is allocated by the WlanEnumInterfaces function if the call succeeds.
/// </param>
/// <returns>
/// If the function succeeds, the return value is ERROR_SUCCESS.
/// If the function fails, the return value may be one of the following return codes.
/// ERROR_INVALID_PARAMETER: A parameter is incorrect. This error is returned if the hClientHandle or ppInterfaceList parameter is NULL. This error is returned if the pReserved is not NULL.
/// This error is also returned if the hClientHandle parameter is not valid.
/// ERROR_INVALID_HANDLE: The handle hClientHandle was not found in the handle table.
/// RPC_STATUS: Various error codes.
/// ERROR_NOT_ENOUGH_MEMORY: Not enough memory is available to process this request and allocate memory for the query results.
/// </returns>
/// <remarks>
/// The WlanEnumInterfaces function allocates memory for the list of returned interfaces that is returned in the
/// buffer pointed to by the ppInterfaceList parameter when the function succeeds. The memory used for the buffer
/// pointed to by ppInterfaceList parameter should be released by calling the WlanFreeMemory function
/// after the buffer is no longer needed.
/// </remarks>
[DllImport("Wlanapi")]
public static extern uint WlanEnumInterfaces(IntPtr hClientHandle, IntPtr pReserved, out IntPtr ppInterfaceList);
/// <summary>
/// The WlanGetProfileList function retrieves the list of profiles in preference order.
/// </summary>
/// <param name="hClientHandle">The client's session handle, obtained by a previous call to the WlanOpenHandle function.</param>
/// <param name="pInterfaceGuid">The GUID of the wireless interface.</param>
/// <param name="pReserved">Reserved for future use. Must be set to NULL.</param>
/// <param name="ppProfileList">A PWLAN_PROFILE_INFO_LIST structure that contains the list of profile information.</param>
/// <returns>
/// If the function succeeds, the return value is ERROR_SUCCESS.
/// If the function fails, the return value may be one of the following return codes.
/// ERROR_INVALID_HANDLE: The handle hClientHandle was not found in the handle table.
/// ERROR_INVALID_PARAMETER: A parameter is incorrect.
/// ERROR_NOT_ENOUGH_MEMORY: Not enough memory is available to process this request and allocate memory for the query results.
/// RPC_STATUS: Various error codes.
/// </returns>
/// <remarks>
/// The WlanGetProfileList function returns only the basic information on the wireless profiles on a wireless interface.
/// The list of wireless profiles on a wireless interface are retrieved in the preference order. The WlanSetProfilePosition
/// can be used to change the preference order for the wireless profiles on a wireless interface.
/// More detailed information for a wireless profile on a wireless interface can be retrieved by using the WlanGetProfile
/// function. The WlanGetProfileCustomUserData function can be used to retrieve custom user data for a wireless profile on
/// a wireless interface. A list of the wireless interfaces and associated GUIDs on the local computer can be retrieved
/// using the WlanEnumInterfaces function.
/// The WlanGetProfileList function allocates memory for the list of profiles returned in the buffer pointed to by the
/// ppProfileList parameter. The caller is responsible for freeing this memory using the WlanFreeMemory function when
/// this buffer is no longer needed.
/// Windows XP with SP3 and Wireless LAN API for Windows XP with SP2:  Guest profiles, profiles with Wireless Provisioning
/// Service (WPS) authentication, and profiles with Wi-Fi Protected Access-None (WPA-None) authentication are not
/// supported. These types of profiles are not returned by WlanGetProfileList, even if a profile of this type appears
/// on the preferred profile list.
/// </remarks>
[DllImport("Wlanapi")]
public static extern uint WlanGetProfileList(IntPtr hClientHandle, Guid pInterfaceGuid, IntPtr pReserved, out IntPtr ppProfileList);
/// <summary>
/// The WlanGetProfile function retrieves all information about a specified wireless profile.
/// </summary>
/// <param name="hClientHandle">The client's session handle, obtained by a previous call to the WlanOpenHandle function.</param>
/// <param name="pInterfaceGuid">The GUID of the wireless interface. </param>
/// <param name="strProfileName">The name of the profile. Profile names are case-sensitive. This string must be NULL-terminated. The maximum length of the profile name is 255 characters. This means that the maximum length of this string, including the NULL terminator, is 256 characters.</param>
/// <param name="pReserved">Reserved for future use. Must be set to NULL.</param>
/// <param name="pstrProfileXml">A string that is the XML representation of the queried profile. There is no predefined maximum string length.</param>
/// <param name="pdwFlags">On input, a pointer to the address location used to provide additional information about the request. If this parameter is NULL on input, then no information on profile flags will be returned. On output, a pointer to the address location used to receive profile flags.</param>
/// <param name="pdwGrantedAccess">The access mask of the all-user profile.</param>
/// <returns>If the function succeeds, the return value is ERROR_SUCCESS.</returns>
[DllImport("Wlanapi", CharSet = CharSet.Unicode)]
public static extern uint WlanGetProfile(IntPtr hClientHandle, Guid pInterfaceGuid, [MarshalAs(UnmanagedType.LPWStr)] string strProfileName, IntPtr pReserved, out IntPtr pstrProfileXml, out uint pdwFlags, out IntPtr pdwGrantedAccess);
/// <summary>
/// The WlanSetProfile function sets the content of a specific profile.
/// </summary>
/// <param name="hClientHandle">The client's session handle, obtained by a previous call to the WlanOpenHandle function.</param>
/// <param name="pInterfaceGuid">The GUID of the interface.</param>
/// <param name="dwFlags">The flags to set on the profile.</param>
/// <param name="strProfileXml">Contains the XML representation of the profile. The WLANProfile element is the root profile element. To view sample profiles, see Wireless Profile Samples. There is no predefined maximum string length.</param>
/// <param name="strAllUserProfileSecurity">Sets the security descriptor string on the all-user profile. For more information about profile permissions, see the Remarks section.</param>
/// <param name="bOverwrite">Specifies whether this profile is overwriting an existing profile. If this parameter is FALSE and the profile already exists, the existing profile will not be overwritten and an error will be returned.</param>
/// <param name="pReserved">Reserved for future use. Must be set to NULL.</param>
/// <param name="pdwReasonCode">A WLAN_REASON_CODE value that indicates why the profile is not valid.</param>
/// <returns>If the function succeeds, the return value is ERROR_SUCCESS.</returns>
[DllImport("Wlanapi", CharSet = CharSet.Unicode)]
public static extern uint WlanSetProfile(IntPtr hClientHandle, Guid pInterfaceGuid, uint dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string strProfileXml, [MarshalAs(UnmanagedType.LPWStr)] string strAllUserProfileSecurity, bool bOverwrite, IntPtr pReserved, out uint pdwReasonCode);
/// <summary>
/// The WlanDeleteProfile function deletes a wireless profile for a wireless interface on the local computer.
/// </summary>
/// <param name="hClientHandle">The client's session handle, obtained by a previous call to the WlanOpenHandle function.</param>
/// <param name="pInterfaceGuid">The GUID of the interface from which to delete the profile. </param>
/// <param name="strProfileName">The name of the profile to be deleted. Profile names are case-sensitive. This string must be NULL-terminated.</param>
/// <param name="pReserved">Reserved for future use. Must be set to NULL.</param>
/// <returns>
/// If the function succeeds, the return value is ERROR_SUCCESS.
/// If the function fails, the return value may be one of the following return codes.
/// ERROR_INVALID_PARAMETER: The hClientHandle parameter is NULL or not valid, the pInterfaceGuid parameter is NULL, the strProfileName parameter is NULL, or pReserved is not NULL.
/// ERROR_INVALID_HANDLE: The handle specified in the hClientHandle parameter was not found in the handle table.
/// ERROR_NOT_FOUND: The wireless profile specified by strProfileName was not found in the profile store.
/// ERROR_ACCESS_DENIED: The caller does not have sufficient permissions to delete the profile.
/// RPC_STATUS: Various error codes.
/// </returns>
/// <remarks>
/// The WlanDeleteProfile function deletes a wireless profile for a wireless interface on the local computer.
/// All wireless LAN functions require an interface GUID for the wireless interface when performing profile operations.
/// When a wireless interface is removed, its state is cleared from Wireless LAN Service (WLANSVC) and no profile operations are possible.
/// The WlanDeleteProfile function can fail with ERROR_INVALID_PARAMETER if the wireless interface specified in the pInterfaceGuid parameter
/// for the wireless LAN profile has been removed from the system (a USB wireless adapter that has been removed, for example).
/// </remarks>
[DllImport("Wlanapi", CharSet = CharSet.Unicode)]
public static extern uint WlanDeleteProfile(IntPtr hClientHandle, Guid pInterfaceGuid, [MarshalAs(UnmanagedType.LPWStr)] string strProfileName, IntPtr pReserved);
/// <summary>
/// The WlanReasonCodeToString function retrieves a string that describes a specified reason code.
/// </summary>
/// <param name="dwReasonCode">A WLAN_REASON_CODE value of which the string description is requested.</param>
/// <param name="dwBufferSize">The size of the buffer used to store the string, in WCHAR. If the reason code string is longer than the buffer, it will be truncated and NULL-terminated. If dwBufferSize is larger than the actual amount of memory allocated to pStringBuffer, then an access violation will occur in the calling program.</param>
/// <param name="pStringBuffer">Pointer to a buffer that will receive the string. The caller must allocate memory to pStringBuffer before calling WlanReasonCodeToString.</param>
/// <param name="pReserved">Reserved for future use. Must be set to NULL.</param>
/// <returns>If the function succeeds, the return value is a pointer to a constant string.</returns>
[DllImport("Wlanapi", CharSet = CharSet.Unicode)]
public static extern uint WlanReasonCodeToString(uint dwReasonCode, uint dwBufferSize, ref StringBuilder pStringBuffer, IntPtr pReserved);
/// <summary>
/// The WlanFreeMemory function frees memory. Any memory returned from Native Wifi functions must be freed.
/// </summary>
/// <param name="pMemory">Pointer to the memory to be freed.</param>
/// <remarks>
/// If pMemory points to memory that has already been freed, an access violation or heap corruption may occur.
/// </remarks>
[DllImport("Wlanapi")]
public static extern void WlanFreeMemory(IntPtr pMemory);
}
}
+76 -300
View File
@@ -1,73 +1,68 @@
using System;
using Disco.Client.Interop.Native;
using Disco.Models.ClientServices.EnrolmentInformation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Runtime.InteropServices;
using System.Text;
namespace Disco.Client.Interop
{
public static class Network
{
private static List<NetworkAdapterInfo> NetworkAdapters { get; set; }
private static NetworkAdapterInfo PrimaryLanNetworkAdapter { get; set; }
private static NetworkAdapterInfo PrimaryWlanNetworkAdapter { get; set; }
public static void Initialize()
public static List<NetworkAdapter> GetNetworkAdapters()
{
// Get All Adapters
RetrieveLanAdapters();
var adapters = GetWmiNetworkAdapters();
if (NetworkAdapters.Count > 0)
if (adapters != null && adapters.Count > 0)
{
// Only Retrieve Wlan Adapters if at least one adapter was found by WMI
try
{
RetrieveWlanAdapters();
}
catch (DllNotFoundException)
{
// Ignore DllNotFoundException
// This which indicates 'Wlanapi.dll' isn't present (eg. Windows Servers)
}
// Determine Primary Adapters
// Lan
PrimaryLanNetworkAdapter = NetworkAdapters.Where(n => !n.IsWLanAdapter && n.NetConnectionId.StartsWith("Local Area Connection", StringComparison.OrdinalIgnoreCase)).OrderByDescending(n => n.Speed).FirstOrDefault();
// Might be too restrictive - remove name restriction just in case.
if (PrimaryLanNetworkAdapter == null)
PrimaryLanNetworkAdapter = NetworkAdapters.Where(n => !n.IsWLanAdapter).OrderByDescending(n => n.Speed).FirstOrDefault();
// Wan
PrimaryWlanNetworkAdapter = NetworkAdapters.Where(n => n.IsWLanAdapter).OrderByDescending(n => n.Speed).FirstOrDefault();
// Apply Wlan Information
adapters.ApplyWlanInformation();
}
}
private static void RetrieveLanAdapters()
return adapters;
}
private static List<NetworkAdapter> GetWmiNetworkAdapters()
{
// Get NetworkAdapter Information
try
{
using (ManagementObjectSearcher mSearcher = new ManagementObjectSearcher("SELECT Index, GUID, MACAddress, Name, NetConnectionID, Speed FROM Win32_NetworkAdapter WHERE PhysicalAdapter=true AND MACAddress IS NOT NULL AND Name IS NOT NULL AND NetConnectionID IS NOT NULL AND Speed IS NOT NULL"))
// Load Physical Adapters
using (var wmiSearcher = new ManagementObjectSearcher("SELECT DeviceID, GUID, Manufacturer, ProductName, AdapterType, MACAddress, Speed, NetConnectionID, NetConnectionStatus, NetEnabled FROM Win32_NetworkAdapter WHERE PhysicalAdapter=true AND MACAddress IS NOT NULL AND NetConnectionID IS NOT NULL AND Speed IS NOT NULL"))
{
using (ManagementObjectCollection mResults = mSearcher.Get())
using (var wmiResults = wmiSearcher.Get())
{
NetworkAdapters = new List<NetworkAdapterInfo>();
foreach (var mResult in mResults.Cast<ManagementObject>())
{
NetworkAdapterInfo nic = new NetworkAdapterInfo()
return wmiResults
.Cast<ManagementObject>()
.Select(wmiResult =>
{
Index = (UInt32)mResult.GetPropertyValue("Index"),
Guid = Guid.Parse((string)mResult.GetPropertyValue("GUID")),
MacAddress = mResult.GetPropertyValue("MACAddress").ToString(),
Name = mResult.GetPropertyValue("Name").ToString(),
NetConnectionId = mResult.GetPropertyValue("NetConnectionID").ToString(),
Speed = Convert.ToUInt64(mResult.GetPropertyValue("Speed")),
IsWLanAdapter = false
};
NetworkAdapters.Add(nic);
}
var adapter = new NetworkAdapter()
{
DeviceID = (string)wmiResult.GetPropertyValue("DeviceID"),
ConnectionIdentifier = Guid.Parse((string)wmiResult.GetPropertyValue("GUID")),
Manufacturer = (string)wmiResult.GetPropertyValue("Manufacturer"),
ProductName = (string)wmiResult.GetPropertyValue("ProductName"),
AdapterType = (string)wmiResult.GetPropertyValue("AdapterType"),
MACAddress = (string)wmiResult.GetPropertyValue("MACAddress"),
Speed = (ulong)wmiResult.GetPropertyValue("Speed"),
NetConnectionID = (string)wmiResult.GetPropertyValue("NetConnectionID"),
NetConnectionStatus = ((NetworkConnectionStatuses)wmiResult.GetPropertyValue("NetConnectionStatus")).Description(),
NetEnabled = (bool)wmiResult.GetPropertyValue("NetEnabled")
};
using (var wmiRelatedResults = wmiResult.GetRelated("Win32_NetworkAdapterConfiguration", "Win32_NetworkAdapterSetting", null, null, null, null, false, null))
{
var wmiConfiguration = wmiRelatedResults.Cast<ManagementObject>().First();
adapter.IPEnabled = (bool)wmiConfiguration.GetPropertyValue("IPEnabled");
if (adapter.IPEnabled)
{
adapter.IPAddresses = ((string[])wmiConfiguration.GetPropertyValue("IPAddress")).ToList();
}
}
return adapter;
})
.ToList();
}
}
}
@@ -77,259 +72,40 @@ namespace Disco.Client.Interop
}
}
private static void RetrieveWlanAdapters()
public static string Description(this NetworkConnectionStatuses Status)
{
WLAN_INTERFACE_INFO_LIST wlanApiInterfaceList;
IntPtr wlanApiHandle = IntPtr.Zero;
uint wlanApiServiceVersion = 0;
if (WlanOpenHandle(WLAN_API_VERSION_2_0, IntPtr.Zero, out wlanApiServiceVersion, ref wlanApiHandle) == ERROR_SUCCESS)
switch (Status)
{
IntPtr wlanApiInterfaceListPointer = IntPtr.Zero;
if (WlanEnumInterfaces(wlanApiHandle, IntPtr.Zero, ref wlanApiInterfaceListPointer) == ERROR_SUCCESS)
{
wlanApiInterfaceList = new WLAN_INTERFACE_INFO_LIST(wlanApiInterfaceListPointer);
WlanFreeMemory(wlanApiInterfaceListPointer);
}
else
{
// Error - No Wlan Adapters Reported
WlanCloseHandle(wlanApiHandle, IntPtr.Zero);
return;
}
WlanCloseHandle(wlanApiHandle, IntPtr.Zero);
}
else
{
// Error - No Wlan Adapters Reported
return;
}
if (wlanApiInterfaceList.InterfaceInfo != null)
{
foreach (var wlanApiAdapter in wlanApiInterfaceList.InterfaceInfo)
{
var wlanApiAdapterInfo = wlanApiAdapter;
var wmiAdapterInfo = NetworkAdapters.FirstOrDefault(n => n.Guid == wlanApiAdapterInfo.InterfaceGuid);
if (wmiAdapterInfo != null)
{
wmiAdapterInfo.IsWLanAdapter = true;
wmiAdapterInfo.WlanState = wlanApiAdapterInfo.isState;
}
}
case NetworkConnectionStatuses.Disconnected:
return "Disconnected";
case NetworkConnectionStatuses.Connecting:
return "Connecting";
case NetworkConnectionStatuses.Connected:
return "Connected";
case NetworkConnectionStatuses.Disconnecting:
return "Disconnecting";
case NetworkConnectionStatuses.HardwareNotPresent:
return "Hardware Not Present";
case NetworkConnectionStatuses.HardwareDisabled:
return "Hardware Disabled";
case NetworkConnectionStatuses.HardwareMalfunction:
return "Hardware Malfunction";
case NetworkConnectionStatuses.MediaDisconnected:
return "Media Disconnected";
case NetworkConnectionStatuses.Authenticating:
return "Authenticating";
case NetworkConnectionStatuses.AuthenticationSucceeded:
return "Authentication Succeeded";
case NetworkConnectionStatuses.AuthenticationFailed:
return "Authentication Failed";
case NetworkConnectionStatuses.InvalidAddress:
return "Invalid Address";
case NetworkConnectionStatuses.CredentialsRequired:
return "Credentials Required";
default:
return "Unknown";
}
}
public static string PrimaryLanMacAddress
{
get
{
// Return null if no Primary LAN Network Adapter found on this Device
return (PrimaryLanNetworkAdapter == null) ? null : PrimaryLanNetworkAdapter.MacAddress;
}
}
public static string PrimaryWlanMacAddress
{
get
{
// Return null if no Primary WLAN Network Adapter found on this Device
return (PrimaryWlanNetworkAdapter == null) ? null : PrimaryWlanNetworkAdapter.MacAddress;
}
}
private class NetworkAdapterInfo
{
public UInt32 Index { get; set; }
public Guid Guid { get; set; }
public string Name { get; set; }
public string NetConnectionId { get; set; }
public string MacAddress { get; set; }
public UInt64 Speed { get; set; }
public bool IsWLanAdapter { get; set; }
public WLAN_INTERFACE_STATE WlanState { get; set; }
public string WlanStateDescription
{
get
{
switch (WlanState)
{
case WLAN_INTERFACE_STATE.wlan_interface_state_not_ready:
return "Not Ready";
case WLAN_INTERFACE_STATE.wlan_interface_state_connected:
return "Connected";
case WLAN_INTERFACE_STATE.wlan_interface_state_ad_hoc_network_formed:
return "Ad Hoc Network Formed";
case WLAN_INTERFACE_STATE.wlan_interface_state_disconnecting:
return "Disconnecting";
case WLAN_INTERFACE_STATE.wlan_interface_state_disconnected:
return "Disconnected";
case WLAN_INTERFACE_STATE.wlan_interface_state_associating:
return "Associating";
case WLAN_INTERFACE_STATE.wlan_interface_state_discovering:
return "Discovering";
case WLAN_INTERFACE_STATE.wlan_interface_state_authenticating:
return "Authenticating";
default:
return "Unknown";
}
}
}
}
#region Wlan Win32 Interop
private const uint WLAN_API_VERSION_2_0 = 2; // Windows Vista WiFi API Version
private const int ERROR_SUCCESS = 0;
/// <summary >
/// Opens a connection to the server
/// </summary >
[DllImport("Wlanapi.dll")]
private static extern int WlanOpenHandle(
uint dwClientVersion,
IntPtr pReserved, //not in MSDN but required
[Out] out uint pdwNegotiatedVersion,
ref IntPtr ClientHandle);
/// <summary >
/// Closes a connection to the server
/// </summary >
[DllImport("Wlanapi", EntryPoint = "WlanCloseHandle")]
private static extern uint WlanCloseHandle(
[In] IntPtr hClientHandle,
IntPtr pReserved);
/// <summary >
/// Enumerates all wireless interfaces in the laptop
/// </summary >
[DllImport("Wlanapi", EntryPoint = "WlanEnumInterfaces")]
private static extern uint WlanEnumInterfaces(
[In] IntPtr hClientHandle,
IntPtr pReserved,
ref IntPtr ppInterfaceList);
/// <summary >
/// Frees memory returned by native WiFi functions
/// </summary >
[DllImport("Wlanapi", EntryPoint = "WlanFreeMemory")]
private static extern void WlanFreeMemory([In] IntPtr pMemory);
/// <summary>
/// Defines the state of the interface. e.g. connected, disconnected.
/// </summary>
private enum WLAN_INTERFACE_STATE
{
/// <summary>
/// wlan_interface_state_not_ready -> 0
/// </summary>
wlan_interface_state_not_ready = 0,
/// <summary>
/// wlan_interface_state_connected -> 1
/// </summary>
wlan_interface_state_connected = 1,
/// <summary>
/// wlan_interface_state_ad_hoc_network_formed -> 2
/// </summary>
wlan_interface_state_ad_hoc_network_formed = 2,
/// <summary>
/// wlan_interface_state_disconnecting -> 3
/// </summary>
wlan_interface_state_disconnecting = 3,
/// <summary>
/// wlan_interface_state_disconnected -> 4
/// </summary>
wlan_interface_state_disconnected = 4,
/// <summary>
/// wlan_interface_state_associating -> 5
/// </summary>
wlan_interface_state_associating = 5,
/// <summary>
/// wlan_interface_state_discovering -> 6
/// </summary>
wlan_interface_state_discovering = 6,
/// <summary>
/// wlan_interface_state_authenticating -> 7
/// </summary>
wlan_interface_state_authenticating = 7,
}
/// <summary >
/// Stores interface info
/// </summary >
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct WLAN_INTERFACE_INFO
{
/// GUID->_GUID
public Guid InterfaceGuid;
/// WCHAR[256]
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string strInterfaceDescription;
/// WLAN_INTERFACE_STATE->_WLAN_INTERFACE_STATE
public WLAN_INTERFACE_STATE isState;
}
/// <summary>
/// Contains an array of NIC information
/// </summary>
[StructLayout(LayoutKind.Sequential)]
private struct WLAN_INTERFACE_INFO_LIST
{
/// <summary>
/// Length of <see cref="InterfaceInfo"/> array
/// </summary>
public Int32 dwNumberOfItems;
/// <summary>
/// This member is not used by the wireless service. Applications can use this member when processing individual interfaces.
/// </summary>
public Int32 dwIndex;
/// <summary>
/// Array of WLAN interfaces.
/// </summary>
public WLAN_INTERFACE_INFO[] InterfaceInfo;
/// <summary>
/// Constructor for WLAN_INTERFACE_INFO_LIST.
/// Constructor is needed because the InterfaceInfo member varies based on how many adapters are in the system.
/// </summary>
/// <param name="pList">the unmanaged pointer containing the list.</param>
public WLAN_INTERFACE_INFO_LIST(IntPtr pList)
{
// The first 4 bytes are the number of WLAN_INTERFACE_INFO structures.
dwNumberOfItems = Marshal.ReadInt32(pList, 0);
// The next 4 bytes are the index of the current item in the unmanaged API.
dwIndex = Marshal.ReadInt32(pList, 4);
// Construct the array of WLAN_INTERFACE_INFO structures.
InterfaceInfo = new WLAN_INTERFACE_INFO[dwNumberOfItems];
for (int i = 0; i <= dwNumberOfItems - 1; i++)
{
// The offset of the array of structures is 8 bytes past the beginning.
// Then, take the index and multiply it by the number of bytes in the
// structure.
// The length of the WLAN_INTERFACE_INFO structure is 532 bytes - this
// was determined by doing a Marshall.SizeOf(WLAN_INTERFACE_INFO)
IntPtr pItemList = new IntPtr(pList.ToInt64() + (i * 532) + 8);
// Construct the WLAN_INTERFACE_INFO structure, marshal the unmanaged
// structure into it, then copy it to the array of structures.
InterfaceInfo[i] = (WLAN_INTERFACE_INFO)Marshal.PtrToStructure(pItemList, typeof(WLAN_INTERFACE_INFO));
}
}
}
#endregion
}
}
-201
View File
@@ -1,201 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
namespace Disco.Client.Interop
{
public static class SystemAudit
{
public static string DeviceSerialNumber { get; private set; }
public static string DeviceSMBIOSVersion { get; private set; }
public static string DeviceManufacturer { get; private set; }
public static string DeviceModel { get; private set; }
public static string DeviceType { get; private set; }
public static string DeviceUUID { get; private set; }
public static bool DeviceIsPartOfDomain { get; private set; }
public static string DeviceDNSDomainName { get; private set; }
public static void Initialize()
{
// Get BIOS Information
try
{
using (ManagementObjectSearcher mSearcher = new ManagementObjectSearcher("SELECT SerialNumber, SMBIOSBIOSVersion FROM Win32_BIOS WHERE PrimaryBios=true"))
{
using (ManagementObjectCollection mResults = mSearcher.Get())
{
using (var mItem = mResults.Cast<ManagementObject>().FirstOrDefault())
{
if (mItem != null)
{
DeviceSerialNumber = mItem.GetPropertyValue("SerialNumber") as string;
if (!string.IsNullOrEmpty(DeviceSerialNumber))
DeviceSerialNumber = DeviceSerialNumber.Trim();
ErrorReporting.DeviceIdentifier = DeviceSerialNumber;
DeviceSMBIOSVersion = mItem.GetPropertyValue("SMBIOSBIOSVersion") as string;
if (!string.IsNullOrEmpty(DeviceSMBIOSVersion))
DeviceSMBIOSVersion = DeviceSMBIOSVersion.Trim();
}
else
{
throw new Exception("No Win32_BIOS WHERE PrimaryBios=true was found");
}
}
}
}
}
catch (Exception ex)
{
throw new Exception("Disco Client was unable to retrieve BIOS information from WMI", ex);
}
// Get System Information
try
{
using (ManagementObjectSearcher mSearcher = new ManagementObjectSearcher("SELECT Manufacturer, Model, PartOfDomain, PCSystemType, Domain FROM Win32_ComputerSystem"))
{
using (ManagementObjectCollection mResults = mSearcher.Get())
{
using (var mItem = mResults.Cast<ManagementObject>().FirstOrDefault())
{
if (mItem != null)
{
DeviceManufacturer = mItem.GetPropertyValue("Manufacturer") as string;
if (!string.IsNullOrEmpty(DeviceManufacturer))
DeviceManufacturer = DeviceManufacturer.Trim();
DeviceModel = mItem.GetPropertyValue("Model") as string;
if (!string.IsNullOrEmpty(DeviceModel))
DeviceModel = DeviceModel.Trim();
DeviceIsPartOfDomain = (bool)mItem.GetPropertyValue("PartOfDomain");
DeviceType = PCSystemTypeToString((UInt16)mItem.GetPropertyValue("PCSystemType"));
DeviceDNSDomainName = DeviceIsPartOfDomain ? mItem.GetPropertyValue("Domain") as string : null;
}
else
{
throw new Exception("No Win32_ComputerSystem was found");
}
}
}
}
}
catch (Exception ex)
{
throw new Exception("Disco Client was unable to retrieve ComputerSystem information from WMI", ex);
}
// Get System Product Information
string ComputerSystemProductSerialNumber;
try
{
using (ManagementObjectSearcher mSearcher = new ManagementObjectSearcher("SELECT IdentifyingNumber, UUID FROM Win32_ComputerSystemProduct"))
{
using (ManagementObjectCollection mResults = mSearcher.Get())
{
using (var mItem = mResults.Cast<ManagementObject>().FirstOrDefault())
{
if (mItem != null)
{
ComputerSystemProductSerialNumber = mItem.GetPropertyValue("IdentifyingNumber") as string;
if (!string.IsNullOrEmpty(ComputerSystemProductSerialNumber))
ComputerSystemProductSerialNumber = ComputerSystemProductSerialNumber.Trim();
DeviceUUID = mItem.GetPropertyValue("UUID") as string;
if (!string.IsNullOrEmpty(DeviceUUID))
DeviceUUID = DeviceUUID.Trim();
}
else
{
throw new Exception("No Win32_ComputerSystemProduct was found");
}
}
}
}
}
catch (Exception ex)
{
throw new Exception("Disco Client was unable to retrieve ComputerSystemProduct information from WMI", ex);
}
// Added 2012-11-22 G# - Lenovo IdeaPad Serial SHIM
// http://www.discoict.com.au/forum/feature-requests/2012/11/serial-number-detection-on-ideapads.aspx
if (string.IsNullOrWhiteSpace(DeviceSerialNumber) ||
(DeviceManufacturer.Equals("LENOVO", StringComparison.OrdinalIgnoreCase) &&
(DeviceModel.Equals("S10-3", StringComparison.OrdinalIgnoreCase) // S10-3
|| DeviceModel.Equals("2957", StringComparison.OrdinalIgnoreCase)))) // S10-2
{
try
{
using (ManagementObjectSearcher mSearcher = new ManagementObjectSearcher("SELECT SerialNumber FROM Win32_BaseBoard"))
{
using (ManagementObjectCollection mResults = mSearcher.Get())
{
using (var mItem = mResults.Cast<ManagementObject>().FirstOrDefault())
{
if (mItem != null)
{
DeviceSerialNumber = mItem.GetPropertyValue("SerialNumber") as string;
if (!string.IsNullOrEmpty(DeviceSerialNumber))
DeviceSerialNumber = DeviceSerialNumber.Trim();
}
else
{
throw new Exception("No Win32_BaseBoard was found");
}
}
}
}
}
catch (Exception ex)
{
throw new Exception("Disco Client was unable to retrieve BaseBoard information from WMI", ex);
}
if (string.IsNullOrWhiteSpace(DeviceSerialNumber))
DeviceSerialNumber = ComputerSystemProductSerialNumber;
}
// End Added 2012-11-22 G#
ErrorReporting.DeviceIdentifier = DeviceSerialNumber;
// Validate Device 'State'
if (string.IsNullOrWhiteSpace(DeviceSerialNumber))
throw new Exception("This device has no serial number stored in BIOS or BaseBoard");
if (DeviceSerialNumber.Length > 60)
throw new Exception(string.Format("The serial number reported by this device is over 60 characters long:{0}{1}", Environment.NewLine, DeviceSerialNumber));
}
private static string PCSystemTypeToString(UInt16 PCSystemType)
{
switch (PCSystemType)
{
case 0:
return "Unknown";
case 1:
return "Desktop";
case 2:
return "Mobile";
case 3:
return "Workstation";
case 4:
return "EnterpriseServer";
case 5:
return "SmallOfficeAndHomeOfficeServer";
case 6:
return "AppliancePC";
case 7:
return "PerformanceServer";
case 8:
return "Maximum";
default:
return "Unknown";
}
}
}
}
+362
View File
@@ -0,0 +1,362 @@
using Disco.Client.Interop.Native;
using Disco.Models.ClientServices.EnrolmentInformation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Linq;
namespace Disco.Client.Interop
{
public static class WirelessNetwork
{
public static void ApplyWlanInformation(this List<NetworkAdapter> Adapters)
{
try
{
IntPtr wlanHandle;
uint wlanServiceVersion;
if (WlanApi.WlanOpenHandle(WlanApi.WLAN_API_VERSION_2_0, IntPtr.Zero, out wlanServiceVersion, out wlanHandle) == WlanApi.ERROR_SUCCESS)
{
try
{
IntPtr wlanInterfacesPtr;
if (WlanApi.WlanEnumInterfaces(wlanHandle, IntPtr.Zero, out wlanInterfacesPtr) == WlanApi.ERROR_SUCCESS)
{
try
{
var wlanInterfaces = new WLAN_INTERFACE_INFO_LIST(wlanInterfacesPtr);
foreach (var wlanInterface in wlanInterfaces.InterfaceInfo)
{
var adapter = Adapters.FirstOrDefault(a => a.ConnectionIdentifier == wlanInterface.InterfaceGuid);
if (adapter != null)
{
adapter.IsWlanAdapter = true;
adapter.WlanStatus = wlanInterface.isState.Description();
}
}
}
finally
{
WlanApi.WlanFreeMemory(wlanInterfacesPtr);
}
}
}
finally
{
WlanApi.WlanCloseHandle(wlanHandle, IntPtr.Zero);
}
}
}
catch (DllNotFoundException)
{
// Ignore
// Indicates 'Wlanapi.dll' isn't present (ie. Servers)
}
}
public static List<WirelessProfile> GetWirelessProfiles()
{
try
{
IntPtr wlanHandle;
uint wlanServiceVersion;
uint interopResult;
// Connect to wireless service
interopResult = WlanApi.WlanOpenHandle(WlanApi.WLAN_API_VERSION_2_0, IntPtr.Zero, out wlanServiceVersion, out wlanHandle);
if (interopResult != WlanApi.ERROR_SUCCESS)
{
throw new Exception($"Unable to connect to local wireless service. WlanOpenHandle returned: {interopResult}");
}
try
{
return GetWirelessProfiles(wlanHandle);
}
finally
{
WlanApi.WlanCloseHandle(wlanHandle, IntPtr.Zero);
}
}
catch (DllNotFoundException)
{
// Indicates 'Wlanapi.dll' isn't present (ie. Servers)
return null;
}
}
private static List<WirelessProfile> GetWirelessProfiles(IntPtr wlanHandle)
{
uint interopResult;
IntPtr wlanInterfacesPtr;
// Enumerate wireless interfaces
interopResult = WlanApi.WlanEnumInterfaces(wlanHandle, IntPtr.Zero, out wlanInterfacesPtr);
if (interopResult != WlanApi.ERROR_SUCCESS)
{
throw new Exception($"Unable to list interfaces with the local wireless service. WlanEnumInterfaces returned: {interopResult}");
}
try
{
var wlanInterfaces = new WLAN_INTERFACE_INFO_LIST(wlanInterfacesPtr);
var profiles = new List<WirelessProfile>();
foreach (var wlanInterface in wlanInterfaces.InterfaceInfo)
{
IntPtr wlanProfilesPtr;
// Enumerate wireless profiles for interface
interopResult = WlanApi.WlanGetProfileList(wlanHandle, wlanInterface.InterfaceGuid, IntPtr.Zero, out wlanProfilesPtr);
if (interopResult != WlanApi.ERROR_SUCCESS)
{
throw new Exception($"Unable to list wireless profiles for the {wlanInterface.InterfaceGuid} interface with the local wireless service. WlanGetProfileList returned: {interopResult}");
}
try
{
var wlanProfiles = new WLAN_PROFILE_INFO_LIST(wlanProfilesPtr);
foreach (var wlanProfile in wlanProfiles.ProfileInfo)
{
profiles.Add(new WirelessProfile()
{
Name = wlanProfile.strInterfaceDescription,
InterfaceGuid = wlanInterface.InterfaceGuid,
IsGroupPolicy = wlanProfile.dwFlags.HasFlag(ProfileInfoFlags.WLAN_PROFILE_GROUP_POLICY)
});
}
}
finally
{
WlanApi.WlanFreeMemory(wlanProfilesPtr);
}
}
return profiles;
}
finally
{
WlanApi.WlanFreeMemory(wlanInterfacesPtr);
}
}
public static void Apply(this WirelessProfileStore ProfileStore)
{
var adapters = Network.GetNetworkAdapters().Where(a => a.IsWlanAdapter).ToList();
try
{
IntPtr wlanHandle;
uint wlanServiceVersion;
uint interopResult;
// Connect to wireless service
interopResult = WlanApi.WlanOpenHandle(WlanApi.WLAN_API_VERSION_2_0, IntPtr.Zero, out wlanServiceVersion, out wlanHandle);
if (interopResult != WlanApi.ERROR_SUCCESS)
{
throw new Exception($"Unable to connect to local wireless service. WlanOpenHandle returned: {interopResult}");
}
try
{
var existingProfiles = GetWirelessProfiles(wlanHandle);
var addedProfiles = new List<string>();
// Remove Profiles
if (ProfileStore.RemoveNames != null && ProfileStore.RemoveNames.Count > 0)
{
var profileRemoved = false;
foreach (var removeName in ProfileStore.RemoveNames)
{
var foundProfiles = existingProfiles.Where(p => p.Name == removeName);
foreach (var profile in foundProfiles)
{
var adapter = adapters.FirstOrDefault(a => a.ConnectionIdentifier == profile.InterfaceGuid);
if (profile.IsGroupPolicy == true)
{
Presentation.UpdateStatus("Enrolling Device", $"Configuring Wireless Profiles\r\nUnable to remove Group Policy Wireless Profile '{removeName}' from '{adapter?.NetConnectionID ?? profile.InterfaceGuid.ToString()}'", true, -1, 3000);
}
else
{
Presentation.UpdateStatus("Enrolling Device", $"Configuring Wireless Profiles\r\nRemoving Wireless Profile '{removeName}' from '{adapter?.NetConnectionID ?? profile.InterfaceGuid.ToString()}'", true, -1, 1000);
interopResult = WlanApi.WlanDeleteProfile(wlanHandle, profile.InterfaceGuid.Value, profile.Name, IntPtr.Zero);
if (interopResult != WlanApi.ERROR_SUCCESS)
{
Presentation.UpdateStatus("Enrolling Device", $"Configuring Wireless Profiles\r\nFailed to remove Wireless Profile '{removeName}' from '{adapter?.NetConnectionID ?? profile.InterfaceGuid.ToString()}'; WlanDeleteProfile returned: {interopResult}", true, -1, 3000);
}
profileRemoved = true;
}
}
}
if (profileRemoved)
{
existingProfiles = GetWirelessProfiles(wlanHandle);
}
}
// Add Profiles
if (ProfileStore.Profiles != null && ProfileStore.Profiles.Count > 0)
{
foreach (var addProfile in ProfileStore.Profiles)
{
foreach (var adapter in adapters)
{
var existingProfile = existingProfiles.FirstOrDefault(p => p.Name == addProfile.Name && p.InterfaceGuid == adapter.ConnectionIdentifier);
if (addProfile.ForceDeployment.Value ||
existingProfile == null)
{
if (existingProfile != null && existingProfile.IsGroupPolicy.Value)
{
Presentation.UpdateStatus("Enrolling Device", $"Configuring Wireless Profiles\r\nUnable to replace Group Policy Wireless Profile '{addProfile.Name}' on '{adapter.NetConnectionID}'", true, -1, 3000);
}
else
{
uint pdwReasonCode;
Presentation.UpdateStatus("Enrolling Device", $"Configuring Wireless Profiles\r\nAdding Wireless Profile '{addProfile.Name}' on '{adapter.NetConnectionID}'", true, -1, 1000);
interopResult = WlanApi.WlanSetProfile(wlanHandle, adapter.ConnectionIdentifier, 0, addProfile.ProfileXml, null, true, IntPtr.Zero, out pdwReasonCode);
if (interopResult != WlanApi.ERROR_SUCCESS)
{
// Get Reason Code
var reason = new StringBuilder(256);
WlanApi.WlanReasonCodeToString(pdwReasonCode, (uint)reason.Capacity, ref reason, IntPtr.Zero);
Presentation.UpdateStatus("Enrolling Device", $"Configuring Wireless Profiles\r\nFailed to add Wireless Profile '{addProfile.Name}' on '{adapter.NetConnectionID}'; WlanSetProfile returned: {interopResult}; {reason.ToString()}", true, -1, 3000);
}
}
addedProfiles.Add(addProfile.Name);
}
}
}
}
// Transform Profiles
if (ProfileStore.Transformations != null && ProfileStore.Transformations.Count > 0)
{
foreach (var transformGroup in ProfileStore.Transformations.GroupBy(t => t.Name))
{
var profileName = transformGroup.Key;
// Don't transform if just added
if (!addedProfiles.Contains(transformGroup.Key))
{
foreach (var adapter in adapters)
{
var existingProfile = existingProfiles.FirstOrDefault(p => p.Name == profileName && p.InterfaceGuid == adapter.ConnectionIdentifier);
if (existingProfile != null)
{
if (existingProfile.IsGroupPolicy.Value)
{
Presentation.UpdateStatus("Enrolling Device", $"Configuring Wireless Profiles\r\nUnable to modify Group Policy Wireless Profile '{profileName}' on '{adapter.NetConnectionID}'", true, -1, 3000);
}
else
{
// Load profile
IntPtr pstrProfileXml;
uint pdwFlags;
IntPtr pdwGrantAccess;
interopResult = WlanApi.WlanGetProfile(wlanHandle, adapter.ConnectionIdentifier, profileName, IntPtr.Zero, out pstrProfileXml, out pdwFlags, out pdwGrantAccess);
if (interopResult == WlanApi.ERROR_SUCCESS)
{
try
{
var profileXml = Marshal.PtrToStringUni(pstrProfileXml);
var originalProfileXml = XElement.Parse(profileXml);
var transformProfileXml = originalProfileXml.ToString(SaveOptions.DisableFormatting);
// Apply Transforms
foreach (var transform in transformGroup)
{
var regex = new Regex(transform.RegularExpression, RegexOptions.Singleline);
transformProfileXml = regex.Replace(transformProfileXml, transform.RegularExpressionReplacement);
}
// Compare XML
var transformedProfileXml = XElement.Parse(transformProfileXml);
if (!XNode.DeepEquals(originalProfileXml, transformedProfileXml))
{
// Set Profile
uint pdwReasonCode;
Presentation.UpdateStatus("Enrolling Device", $"Configuring Wireless Profiles\r\nModifying Wireless Profile '{profileName}' on '{adapter.NetConnectionID}'", true, -1, 1000);
transformProfileXml = transformedProfileXml.ToString(SaveOptions.None);
interopResult = WlanApi.WlanSetProfile(wlanHandle, adapter.ConnectionIdentifier, 0, transformProfileXml, null, true, IntPtr.Zero, out pdwReasonCode);
if (interopResult != WlanApi.ERROR_SUCCESS)
{
// Get Reason Code
var reason = new StringBuilder(256);
WlanApi.WlanReasonCodeToString(pdwReasonCode, (uint)reason.Capacity, ref reason, IntPtr.Zero);
Presentation.UpdateStatus("Enrolling Device", $"Configuring Wireless Profiles\r\nFailed to modify Wireless Profile '{profileName}' to '{adapter.NetConnectionID}'; WlanSetProfile returned: {interopResult}; {reason.ToString()}", true, -1, 3000);
}
}
}
finally
{
WlanApi.WlanFreeMemory(pstrProfileXml);
}
}
else
{
Presentation.UpdateStatus("Enrolling Device", $"Configuring Wireless Profiles\r\nFailed to transform Wireless Profile '{profileName}' on '{adapter.NetConnectionID}'; WlanGetProfile returned: {interopResult}", true, -1, 3000);
}
}
}
}
}
}
}
}
finally
{
WlanApi.WlanCloseHandle(wlanHandle, IntPtr.Zero);
}
}
catch (DllNotFoundException)
{
// Indicates 'Wlanapi.dll' isn't present (ie. Servers)
// Ignore policies
}
}
public static string Description(this WLAN_INTERFACE_STATE State)
{
switch (State)
{
case WLAN_INTERFACE_STATE.wlan_interface_state_not_ready:
return "Not Ready";
case WLAN_INTERFACE_STATE.wlan_interface_state_connected:
return "Connected";
case WLAN_INTERFACE_STATE.wlan_interface_state_ad_hoc_network_formed:
return "Ad Hoc Network";
case WLAN_INTERFACE_STATE.wlan_interface_state_disconnecting:
return "Disconnecting";
case WLAN_INTERFACE_STATE.wlan_interface_state_disconnected:
return "Disconnected";
case WLAN_INTERFACE_STATE.wlan_interface_state_associating:
return "Associating";
case WLAN_INTERFACE_STATE.wlan_interface_state_discovering:
return "Discovering";
case WLAN_INTERFACE_STATE.wlan_interface_state_authenticating:
return "Authenticating";
default:
return "Unknown";
}
}
}
}
+5 -4
View File
@@ -5,6 +5,7 @@ using System.Reflection;
using System.Text;
using System.Threading;
using Disco.Client.Extensions;
using Disco.Client.Interop;
namespace Disco.Client
{
@@ -38,8 +39,8 @@ namespace Disco.Client
public static void WriteBanner()
{
StringBuilder message = new StringBuilder();
message.Append("Version: ").AppendLine(Assembly.GetExecutingAssembly().GetName().Version.ToString(3));
message.Append("Device: ").Append(Interop.SystemAudit.DeviceSerialNumber).Append(" (").Append(Interop.SystemAudit.DeviceManufacturer).Append(" ").Append(Interop.SystemAudit.DeviceModel).AppendLine(")");
message.AppendLine($"Version: {Assembly.GetExecutingAssembly().GetName().Version.ToString(3)}");
message.AppendLine($"Device: {Hardware.Information.SerialNumber} ({Hardware.Information.Manufacturer} {Hardware.Information.Model})");
Console.ForegroundColor = ConsoleColor.Yellow;
UpdateStatus("Preparation Client Started", message.ToString(), false, 0);
Console.ForegroundColor = ConsoleColor.White;
@@ -52,8 +53,8 @@ namespace Disco.Client
ClientServiceException clientServiceException = ex as ClientServiceException;
if (clientServiceException != null)
{
UpdateStatus(string.Format("An error occurred during {0}", clientServiceException.ServiceFeature),
clientServiceException.Message, false, 0);
UpdateStatus($"An error occurred during {clientServiceException.ServiceFeature}",
clientServiceException.Message, false, 0);
}
else
{
+11 -4
View File
@@ -20,6 +20,17 @@ namespace Disco.Client
{
bool keepProcessing;
#if DEBUG
if (args != null && args.Any(a => a.Equals("debug", StringComparison.OrdinalIgnoreCase)))
{
do
{
Console.WriteLine("Waiting for Debugger to Attach");
System.Threading.Thread.Sleep(1000);
} while (!System.Diagnostics.Debugger.IsAttached);
}
#endif
// Initialize Environment Settings
SetupEnvironment();
@@ -59,10 +70,6 @@ namespace Disco.Client
{
Presentation.DelayUI = true; // Add Delays on Error
}
// Initialize Interop
Interop.SystemAudit.Initialize();
Interop.Network.Initialize();
}
public static bool WhoAmI()
+2 -2
View File
@@ -31,5 +31,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
[assembly: AssemblyVersion("2.2.16272.1003")]
[assembly: AssemblyFileVersion("2.2.16272.1003")]
+17 -11
View File
@@ -1,6 +1,4 @@
//#define Debug
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -22,6 +20,14 @@ namespace Disco.ClientBootstrapper
private StringBuilder errorMessage;
private Process clientProcess;
#if DEBUG
public const string DiscoServerName = "WS-GSHARP";
public const int DiscoServerPort = 57252;
#else
public const string DiscoServerName = "DISCO";
public const int DiscoServerPort = 9292;
#endif
public BootstrapperLoop(IStatus StatusUI, LoopCompleteCallback Callback)
{
this.statusUI = StatusUI;
@@ -79,12 +85,12 @@ namespace Disco.ClientBootstrapper
// Check for Network Connectivity
statusUI.UpdateStatus(null, "Detecting Network", "Checking network connectivity, Please wait...", true, -1);
if (!Interop.NetworkInterop.PingDisco())
if (!Interop.NetworkInterop.PingDisco(DiscoServerName))
{
statusUI.UpdateStatus(null, "Detecting Network", "No network connectivity detected, Diagnosing...", true, -1);
statusUI_WriteAdapterInfo();
if (!Interop.NetworkInterop.PingDisco())
if (!Interop.NetworkInterop.PingDisco(DiscoServerName))
{
// Check for Wireless
var hasWireless = (Interop.NetworkInterop.NetworkAdapters.Count(na => na.IsWireless) > 0);
@@ -99,17 +105,17 @@ namespace Disco.ClientBootstrapper
statusUI_WriteAdapterInfo();
statusUI.UpdateStatus(null, null, null, true, i);
Program.SleepThread(500, false);
if (Interop.NetworkInterop.PingDisco())
if (Interop.NetworkInterop.PingDisco(DiscoServerName))
break;
}
if (!Interop.NetworkInterop.PingDisco())
if (!Interop.NetworkInterop.PingDisco(DiscoServerName))
{
statusUI.UpdateStatus(null, "Wireless Network Failed", "Unable to connect to the wireless network, please connect the network cable...", false);
Program.SleepThread(3000, false);
}
}
if (!Interop.NetworkInterop.PingDisco())
if (!Interop.NetworkInterop.PingDisco(DiscoServerName))
{
// Instruct user to connect network cable
statusUI.UpdateStatus(null, "Please connect the network cable", null);
@@ -118,13 +124,13 @@ namespace Disco.ClientBootstrapper
statusUI_WriteAdapterInfo();
statusUI.UpdateStatus(null, null, null, true, i);
Program.SleepThread(500, false);
if (Interop.NetworkInterop.PingDisco())
if (Interop.NetworkInterop.PingDisco(DiscoServerName))
break;
}
}
}
if (!Interop.NetworkInterop.PingDisco())
if (!Interop.NetworkInterop.PingDisco(DiscoServerName))
{
// Client Failed
if (this.mLoopCompleteCallback != null)
@@ -143,7 +149,7 @@ namespace Disco.ClientBootstrapper
// Don't use a proxy when downloading the Client
webClient.Proxy = new WebProxy();
webClient.DownloadFile("http://disco:9292/Services/Client/PreparationClient", clientSourceLocation);
webClient.DownloadFile($"http://{DiscoServerName}:{DiscoServerPort}/Services/Client/PreparationClient", clientSourceLocation);
}
// Unzip Client
@@ -28,6 +28,7 @@
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<AssemblyVersion>2.2.16272.1003</AssemblyVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
@@ -165,13 +165,13 @@ namespace Disco.ClientBootstrapper.Interop
}
}
public static bool PingDisco()
public static bool PingDisco(string ServerName)
{
using (Ping p = new Ping())
{
try
{
PingReply pr = p.Send("disco", 2000);
PingReply pr = p.Send(ServerName, 2000);
if (pr.Status == IPStatus.Success)
return true;
else
@@ -31,5 +31,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
[assembly: AssemblyVersion("2.2.16272.1003")]
[assembly: AssemblyFileVersion("2.2.16272.1003")]
@@ -36,7 +36,7 @@ namespace Disco.Data.Configuration.Modules
/// </summary>
public bool SearchWildcardSuffixOnly
{
get { return Get(false); }
get { return Get(true); }
set { Set(value); }
}
}
@@ -1,5 +1,5 @@
using Disco.Data.Repository;
using Disco.Models.BI.Job;
using Disco.Models.Services.Job;
using System;
using System.Collections.Generic;
@@ -59,13 +59,13 @@ namespace Disco.Data.Configuration.Modules
public LocationModes LocationMode
{
get { return Get<LocationModes>(LocationModes.Unrestricted); }
get { return Get(LocationModes.Unrestricted); }
set { Set(value); }
}
public List<string> LocationList
{
get { return Get<List<string>>(new List<string>()); }
get { return Get(new List<string>()); }
set { Set(value); }
}
}
@@ -284,12 +284,12 @@ namespace Disco.Data.Configuration
return
(short)(BitConverter.ToInt16(deploymentIdBytes, 0) ^
BitConverter.ToInt16(deploymentIdBytes, 2) ^
BitConverter.ToInt16(deploymentIdBytes, 2) ^
BitConverter.ToInt16(deploymentIdBytes, 2) ^
BitConverter.ToInt16(deploymentIdBytes, 2) ^
BitConverter.ToInt16(deploymentIdBytes, 2) ^
BitConverter.ToInt16(deploymentIdBytes, 2) ^
BitConverter.ToInt16(deploymentIdBytes, 2));
BitConverter.ToInt16(deploymentIdBytes, 4) ^
BitConverter.ToInt16(deploymentIdBytes, 6) ^
BitConverter.ToInt16(deploymentIdBytes, 8) ^
BitConverter.ToInt16(deploymentIdBytes, 10) ^
BitConverter.ToInt16(deploymentIdBytes, 12) ^
BitConverter.ToInt16(deploymentIdBytes, 14));
}
}
public UpdateResponseV2 UpdateLastCheckResponse
+8
View File
@@ -15,6 +15,7 @@
<TargetFrameworkProfile />
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
<RestorePackages>true</RestorePackages>
<AssemblyVersion>2.2.16272.1003</AssemblyVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@@ -150,6 +151,10 @@
<Compile Include="Migrations\201407260624238_DBv16.Designer.cs">
<DependentUpon>201407260624238_DBv16.cs</DependentUpon>
</Compile>
<Compile Include="Migrations\201609260741183_DBv17.cs" />
<Compile Include="Migrations\201609260741183_DBv17.Designer.cs">
<DependentUpon>201609260741183_DBv17.cs</DependentUpon>
</Compile>
<Compile Include="Migrations\Configuration.cs" />
<Compile Include="Migrations\DiscoDataMigrator.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
@@ -213,6 +218,9 @@
<EmbeddedResource Include="Migrations\201407260624238_DBv16.resx">
<DependentUpon>201407260624238_DBv16.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Migrations\201609260741183_DBv17.resx">
<DependentUpon>201609260741183_DBv17.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
+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 DBv17 : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(DBv17));
string IMigrationMetadata.Id
{
get { return "201609260741183_DBv17"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
@@ -0,0 +1,27 @@
namespace Disco.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class DBv17 : DbMigration
{
public override void Up()
{
RenameColumn("dbo.DeviceProfiles", "CertificateProviderId", "CertificateProviders");
AlterColumn("dbo.DeviceProfiles", "CertificateProviders", c => c.String(maxLength: 200));
AddColumn("dbo.DeviceProfiles", "CertificateAuthorityProviders", c => c.String(maxLength: 200));
AddColumn("dbo.DeviceProfiles", "WirelessProfileProviders", c => c.String(maxLength: 200));
// Migration support for eduSTAR.net plugin
Sql("UPDATE [DeviceProfiles] SET [CertificateAuthorityProviders]='EduSTARnetCertificateAuthorityProvider', [WirelessProfileProviders]='EduSTARnetWirelessProfileProvider' WHERE [CertificateProviders]='EduSTARnetCertificateProvider'");
}
public override void Down()
{
AddColumn("dbo.DeviceProfiles", "CertificateProviderId", c => c.String(maxLength: 64));
DropColumn("dbo.DeviceProfiles", "WirelessProfileProviders");
DropColumn("dbo.DeviceProfiles", "CertificateAuthorityProviders");
DropColumn("dbo.DeviceProfiles", "CertificateProviders");
}
}
}
File diff suppressed because one or more lines are too long
+2 -2
View File
@@ -31,5 +31,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
[assembly: AssemblyVersion("2.2.16272.1003")]
[assembly: AssemblyFileVersion("2.2.16272.1003")]
-6
View File
@@ -273,12 +273,6 @@ namespace Disco.Data.Repository
case "OrganisationalUnit":
dp.OrganisationalUnit = configurationItem.Value;
break;
case "AllocateWirelessCertificate":
if (bool.Parse(configurationItem.Value))
dp.CertificateProviderId = "";
else
dp.CertificateProviderId = null;
break;
default:
continue; // Unknown Configuration Item - Leave in DB & Ignore
}
-35
View File
@@ -1,35 +0,0 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Disco.Models.BI.Device
{
public class ImportDevice
{
[Required, StringLength(60)]
public string SerialNumber { get; set; }
public int? DeviceModelId { get; set; }
[Range(1, int.MaxValue, ErrorMessage = "A valid Device Profile is Required")]
public int DeviceProfileId { get; set; }
public int? DeviceBatchId { get; set; }
[StringLength(50)]
public string AssignedUserId { get; set; }
[StringLength(250)]
public string Location { get; set; }
[StringLength(40)]
public string AssetNumber { get; set; }
public Repository.Device Device { get; set; }
public Repository.DeviceModel DeviceModel { get; set; }
public Repository.DeviceProfile DeviceProfile { get; set; }
public Repository.DeviceBatch DeviceBatch { get; set; }
public Repository.User AssignedUser { get; set; }
public Dictionary<string, string> Errors { get; set; }
}
}
@@ -1,11 +0,0 @@
using System.Collections.Generic;
namespace Disco.Models.BI.Device
{
public class ImportDeviceSession
{
public string ImportParseTaskId { get; set; }
public string ImportFilename { get; set; }
public List<ImportDevice> ImportDevices { get; set; }
}
}
+13 -16
View File
@@ -1,7 +1,5 @@
using System;
using Disco.Models.ClientServices.EnrolmentInformation;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Disco.Models.ClientServices
{
@@ -12,21 +10,20 @@ namespace Disco.Models.ClientServices
get { return "Enrol"; }
}
public string DeviceSerialNumber { get; set; }
public string DeviceUUID { get; set; }
public string SerialNumber { get; set; }
public string DeviceDNSDomainName { get; set; }
public string DeviceComputerName { get; set; }
public bool DeviceIsPartOfDomain { get; set; }
public string DeviceManufacturer { get; set; }
public string DeviceModel { get; set; }
public string DeviceModelType { get; set; }
public string DNSDomainName { get; set; }
public string ComputerName { get; set; }
public bool IsPartOfDomain { get; set; }
public string DeviceLanMacAddress { get; set; }
public string DeviceWlanMacAddress { get; set; }
public string RunningUserName { get; set; }
public string RunningUserDomain { get; set; }
public bool RunningInteractively { get; internal set; }
public List<string> DeviceCertificates { get; set; }
public DeviceHardware Hardware { get; set; }
public List<Certificate> Certificates { get; set; }
public List<WirelessProfile> WirelessProfiles { get; set; }
}
}
+14 -17
View File
@@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Disco.Models.ClientServices.EnrolmentInformation;
namespace Disco.Models.ClientServices
{
@@ -9,22 +6,22 @@ namespace Disco.Models.ClientServices
{
public string SessionId { get; set; }
public string DeviceDomainName { get; set; }
public string DeviceComputerName { get; set; }
public string DeviceAssignedUserDomain { get; set; }
public string DeviceAssignedUserName { get; set; }
public string DeviceAssignedUserSID { get; set; }
public string DeviceAssignedUserUsername { get; set; }
public string DomainName { get; set; }
public string ComputerName { get; set; }
public bool DeviceAssignedUserIsLocalAdmin { get; set; }
public string AssignedUserDomain { get; set; }
public string AssignedUserUsername { get; set; }
public string AssignedUserSID { get; set; }
public string AssignedUserDescription { get; set; }
public string OfflineDomainJoin { get; set; }
public string DeviceCertificate { get; set; }
public List<string> DeviceCertificateRemoveExisting { get; set; }
public bool AssignedUserIsLocalAdmin { get; set; }
public string OfflineDomainJoinManifest { get; set; }
public CertificateStore Certificates { get; set; }
public WirelessProfileStore WirelessProfiles { get; set; }
// Actions
public bool AllowBootstrapperUninstall { get; set; }
public bool RequireReboot { get; set; }
@@ -0,0 +1,19 @@
using System;
namespace Disco.Models.ClientServices.EnrolmentInformation
{
public class Certificate
{
public string Store { get; set; }
public string SubjectName { get; set; }
public string Thumbprint { get; set; }
public string FriendlyName { get; set; }
public string DnsName { get; set; }
public int Version { get; set; }
public string SignatureAlgorithm { get; set; }
public string Issuer { get; set; }
public DateTime NotAfter { get; set; }
public DateTime NotBefore { get; set; }
public bool HasPrivateKey { get; set; }
}
}
@@ -0,0 +1,16 @@
using System.Collections.Generic;
namespace Disco.Models.ClientServices.EnrolmentInformation
{
public class CertificateStore
{
public List<byte[]> TrustedRootCertificates { get; set; }
public List<string> TrustedRootRemoveThumbprints { get; set; }
public List<byte[]> IntermediateCertificates { get; set; }
public List<string> IntermediateRemoveThumbprints { get; set; }
public List<byte[]> PersonalCertificates { get; set; }
public List<string> PersonalRemoveThumbprints { get; set; }
}
}
@@ -0,0 +1,20 @@
using System.Collections.Generic;
namespace Disco.Models.ClientServices.EnrolmentInformation
{
public class DeviceHardware
{
public string SerialNumber { get; set; }
public string UUID { get; set; }
public string Manufacturer { get; set; }
public string Model { get; set; }
public string ModelType { get; set; }
public List<Processor> Processors { get; set; }
public List<PhysicalMemory> PhysicalMemory { get; set; }
public List<DiskDrive> DiskDrives { get; set; }
public List<NetworkAdapter> NetworkAdapters { get; set; }
}
}
@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
namespace Disco.Models.ClientServices.EnrolmentInformation
{
public class DiskDrive
{
public string DeviceID { get; set; }
public string Manufacturer { get; set; }
public string Model { get; set; }
public string MediaType { get; set; }
public string InterfaceType { get; set; }
public string SerialNumber { get; set; }
public string FirmwareRevision { get; set; }
public DateTime InstallDate { get; set; }
public ulong Size { get; set; }
public List<DiskDrivePartition> Partitions { get; set; }
}
}
@@ -0,0 +1,16 @@
using System.Collections.Generic;
namespace Disco.Models.ClientServices.EnrolmentInformation
{
public class DiskDrivePartition
{
public bool DeviceID { get; set; }
public bool Bootable { get; set; }
public bool BootPartition { get; set; }
public bool PrimaryParition { get; set; }
public ulong Size { get; set; }
public ulong StartingOffset { get; set; }
public List<DiskLogical> LogicalDisks { get; set; }
}
}
@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.Models.ClientServices.EnrolmentInformation
{
public class DiskLogical
{
public string DeviceID { get; set; }
public string Description { get; set; }
public int DriveType { get; set; }
public int MediaType { get; set; }
public string FileSystem { get; set; }
public ulong Size { get; set; }
public ulong FreeSpace { get; set; }
public string VolumeName { get; set; }
public string VolumeSerialNumber { get; set; }
}
}
@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
namespace Disco.Models.ClientServices.EnrolmentInformation
{
public class NetworkAdapter
{
public string DeviceID { get; set; }
public Guid ConnectionIdentifier { get; set; }
public bool IsWlanAdapter { get; set; }
public string Manufacturer { get; set; }
public string ProductName { get; set; }
public string AdapterType { get; set; }
public string MACAddress { get; set; }
public ulong Speed { get; set; }
public string NetConnectionID { get; set; }
public string NetConnectionStatus { get; set; }
public string WlanStatus { get; set; }
public bool NetEnabled { get; set; }
public bool IPEnabled { get; set; }
public List<string> IPAddresses { get; set; }
}
}
@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.Models.ClientServices.EnrolmentInformation
{
public class PhysicalMemory
{
public string Tag { get; set; }
public string SerialNumber { get; set; }
public string Manufacturer { get; set; }
public string PartNumber { get; set; }
public ulong Capacity { get; set; }
public int ClockSpeed { get; set; }
public int Voltage { get; set; }
public string Location { get; set; }
}
}
@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.Models.ClientServices.EnrolmentInformation
{
public class Processor
{
public string DeviceID { get; set; }
public string Manufacturer { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Architecture { get; set; }
public short Family { get; set; }
public int MaxClockSpeed { get; set; }
public int NumberOfCores { get; set; }
public int NumberOfLogicalProcessors { get; set; }
}
}
@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
namespace Disco.Models.ClientServices.EnrolmentInformation
{
public class WirelessProfile
{
/// <summary>
/// The name of the wireless profile, typically the SSID
/// </summary>
public string Name { get; set; }
/// <summary>
/// The guid of the associated interface.
/// </summary>
public Guid? InterfaceGuid { get; set; }
/// <summary>
/// Indicates the profile is deployed via Group Policy and therefore read-only
/// </summary>
public bool? IsGroupPolicy { get; set; }
/// <summary>
/// Indicates the profile should be overwritten even if it already exists
/// </summary>
public bool? ForceDeployment { get; set; }
/// <summary>
/// The wireless profile XML definition
/// </summary>
public string ProfileXml { get; set; }
}
}
@@ -0,0 +1,24 @@
using System.Collections.Generic;
namespace Disco.Models.ClientServices.EnrolmentInformation
{
public class WirelessProfileStore
{
/// <summary>
/// A list of wireless profiles to add to the client device.
/// </summary>
public List<WirelessProfile> Profiles { get; set; }
/// <summary>
/// A list of transformations to be applied to existing XML wireless profiles found on the client device.
/// </summary>
public List<WirelessProfileTransformation> Transformations { get; set; }
/// <summary>
/// A list of wireless profile names to be removed from the client device.
/// </summary>
public List<string> RemoveNames { get; set; }
}
}
@@ -0,0 +1,22 @@
namespace Disco.Models.ClientServices.EnrolmentInformation
{
public class WirelessProfileTransformation
{
/// <summary>
/// The name of the wireless profile related to this transformation, typically the SSID
/// </summary>
public string Name { get; set; }
/// <summary>
/// The regular expression to evaluate against the wireless profile XML
/// </summary>
public string RegularExpression { get; set; }
/// <summary>
/// The replacement string used when evaluating the regular expression
/// </summary>
public string RegularExpressionReplacement { get; set; }
}
}
@@ -13,7 +13,7 @@ namespace Disco.Models.ClientServices
public override string ToString()
{
return string.Format("{0} ({1})", DisplayName, Username);
return $"{DisplayName} ({Username})";
}
}
}
+17 -8
View File
@@ -13,6 +13,7 @@
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
<AssemblyVersion>2.2.16272.1003</AssemblyVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@@ -48,7 +49,20 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="BI\Job\LocationModes.cs" />
<Compile Include="BI\Config\OrganisationAddress.cs" />
<Compile Include="ClientServices\EnrolmentInformation\DiskLogical.cs" />
<Compile Include="ClientServices\EnrolmentInformation\DeviceHardware.cs" />
<Compile Include="ClientServices\EnrolmentInformation\DiskDrive.cs" />
<Compile Include="ClientServices\EnrolmentInformation\DiskDrivePartition.cs" />
<Compile Include="ClientServices\EnrolmentInformation\NetworkAdapter.cs" />
<Compile Include="ClientServices\EnrolmentInformation\PhysicalMemory.cs" />
<Compile Include="ClientServices\EnrolmentInformation\Processor.cs" />
<Compile Include="ClientServices\EnrolmentInformation\CertificateStore.cs" />
<Compile Include="ClientServices\EnrolmentInformation\WirelessProfile.cs" />
<Compile Include="ClientServices\EnrolmentInformation\WirelessProfileStore.cs" />
<Compile Include="ClientServices\EnrolmentInformation\WirelessProfileTransformation.cs" />
<Compile Include="Services\Jobs\LocationModes.cs" />
<Compile Include="ClientServices\EnrolmentInformation\Certificate.cs" />
<Compile Include="ClientServices\Register.cs" />
<Compile Include="ClientServices\RegisterResponse.cs" />
<Compile Include="Repository\Attachment\AttachmentTypes.cs" />
@@ -60,12 +74,9 @@
<Compile Include="Services\Authorization\IAuthorizationToken.cs" />
<Compile Include="Services\Authorization\IClaimNavigatorItem.cs" />
<Compile Include="Services\Authorization\IRoleToken.cs" />
<Compile Include="BI\Config\OrganisationAddress.cs" />
<Compile Include="BI\Device\ImportDevice.cs" />
<Compile Include="BI\Device\ImportDeviceSession.cs" />
<Compile Include="Services\Documents\DocumentState.cs" />
<Compile Include="BI\Expressions\IImageExpressionResult.cs" />
<Compile Include="BI\Job\Statistics\DailyOpenedClosedItem.cs" />
<Compile Include="Services\Jobs\Statistics\DailyOpenedClosedItem.cs" />
<Compile Include="ClientServices\EnrolResponse.cs" />
<Compile Include="ClientServices\MacEnrol.cs" />
<Compile Include="ClientServices\MacEnrolResponse.cs" />
@@ -184,9 +195,7 @@
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Folder Include="BI\DocumentTemplate\" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
+2 -2
View File
@@ -31,5 +31,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
[assembly: AssemblyVersion("2.2.16272.1003")]
[assembly: AssemblyFileVersion("2.2.16272.1003")]
@@ -61,10 +61,14 @@ namespace Disco.Models.Repository
return string.Format("{0} ({1})", this.Name, this.ShortName);
}
// 2012-06-21
// public bool AllocateCertificate { get; set; } // Renamed from 'AllocateWirelessCertificate'
[StringLength(64)]
public string CertificateProviderId { get; set; }
[StringLength(200)]
public string CertificateProviders { get; set; }
[StringLength(200)]
public string CertificateAuthorityProviders { get; set; }
[StringLength(200)]
public string WirelessProfileProviders { get; set; }
public const string DefaultComputerNameTemplate = "DeviceProfile.ShortName + '-' + SerialNumber";
@@ -1,11 +1,6 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
namespace Disco.Models.BI.Job
namespace Disco.Models.Services.Job
{
public enum LocationModes
{
@@ -1,6 +1,6 @@
using System;
namespace Disco.Models.BI.Job.Statistics
namespace Disco.Models.Services.Job.Statistics
{
public class DailyOpenedClosedItem
{
@@ -1,17 +1,14 @@
using System;
using Disco.Models.BI.Config;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.Models.UI.Config.DeviceProfile
{
public interface ConfigDeviceProfileShowModel : BaseUIModel
{
Disco.Models.Repository.DeviceProfile DeviceProfile { get; set; }
Disco.Models.BI.Config.OrganisationAddress DefaultOrganisationAddress { get; set; }
Repository.DeviceProfile DeviceProfile { get; set; }
OrganisationAddress DefaultOrganisationAddress { get; set; }
List<Disco.Models.BI.Config.OrganisationAddress> OrganisationAddresses { get; set; }
List<OrganisationAddress> OrganisationAddresses { get; set; }
int DeviceCount { get; set; }
int DeviceDecommissionedCount { get; set; }
@@ -1,9 +1,5 @@
using Disco.Models.BI.Job;
using System;
using Disco.Models.Services.Job;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.Models.UI.Config.JobPreferences
{
@@ -1,8 +1,5 @@
using System;
using Disco.Models.BI.Config;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.Models.UI.Config.Organisation
{
@@ -10,6 +7,6 @@ namespace Disco.Models.UI.Config.Organisation
{
string OrganisationName { get; set; }
bool MultiSiteMode { get; set; }
List<Models.BI.Config.OrganisationAddress> OrganisationAddresses { get; set; }
List<OrganisationAddress> OrganisationAddresses { get; set; }
}
}
+8 -7
View File
@@ -1,21 +1,22 @@
using Disco.Models.Services.Jobs.JobLists;
using Disco.Models.BI.Config;
using Disco.Models.Services.Jobs.JobLists;
using System.Collections.Generic;
namespace Disco.Models.UI.Device
{
public interface DeviceShowModel : BaseUIModel
{
Disco.Models.Repository.Device Device { get; set; }
Repository.Device Device { get; set; }
List<Disco.Models.Repository.DeviceProfile> DeviceProfiles { get; set; }
Disco.Models.BI.Config.OrganisationAddress DeviceProfileDefaultOrganisationAddress { get; set; }
List<Repository.DeviceProfile> DeviceProfiles { get; set; }
OrganisationAddress DeviceProfileDefaultOrganisationAddress { get; set; }
List<Disco.Models.Repository.DeviceBatch> DeviceBatches { get; set; }
List<Repository.DeviceBatch> DeviceBatches { get; set; }
JobTableModel Jobs { get; set; }
List<Disco.Models.Repository.DeviceCertificate> Certificates { get; set; }
List<Repository.DeviceCertificate> Certificates { get; set; }
List<Disco.Models.Repository.DocumentTemplate> DocumentTemplates { get; set; }
List<Repository.DocumentTemplate> DocumentTemplates { get; set; }
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
using Disco.Models.BI.Job;
using Disco.Models.Services.Job;
using Disco.Models.Services.Jobs.JobLists;
using System;
using System.Collections.Generic;
@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Common.Logging" publicKeyToken="af08829b84f0328e" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.1.0.0" newVersion="2.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.1.0.0" newVersion="2.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
@@ -0,0 +1,103 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{35E90902-D5A6-4C14-BA6B-2DF976E4B96A}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Disco.Services.Plugins.ManifestGenerator</RootNamespace>
<AssemblyName>Disco.Services.Plugins.ManifestGenerator</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<AssemblyVersion>2.0.16272.1003</AssemblyVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.Net.Http.Extensions, Version=2.2.22.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Net.Http.2.2.22\lib\net45\System.Net.Http.Extensions.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Net.Http.Primitives, Version=4.2.22.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Net.Http.2.2.22\lib\net45\System.Net.Http.Primitives.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Net.Http.WebRequest" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Disco.BI\Disco.BI.csproj">
<Project>{095e6f94-3c34-47ae-bb83-46203535e0f6}</Project>
<Name>Disco.BI</Name>
</ProjectReference>
<ProjectReference Include="..\Disco.Data\Disco.Data.csproj">
<Project>{85a6bd19-2c64-4746-8f2c-a68a86e8c2d7}</Project>
<Name>Disco.Data</Name>
</ProjectReference>
<ProjectReference Include="..\Disco.Models\Disco.Models.csproj">
<Project>{fbc05512-fcca-4b16-9e76-8c413c5de6c9}</Project>
<Name>Disco.Models</Name>
</ProjectReference>
<ProjectReference Include="..\Disco.Services\Disco.Services.csproj">
<Project>{b80a737f-bd6a-4986-9182-dd7b932bd950}</Project>
<Name>Disco.Services</Name>
</ProjectReference>
<ProjectReference Include="..\Disco.Web.Extensions\Disco.Web.Extensions.csproj">
<Project>{c433efba-8608-4451-874b-af32c8536792}</Project>
<Name>Disco.Web.Extensions</Name>
</ProjectReference>
<ProjectReference Include="..\Disco.Web\Disco.Web.csproj">
<Project>{241f4f43-6acb-482d-8cbf-8f4e4b4db0fe}</Project>
<Name>Disco.Web</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets" Condition="Exists('..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" />
<Target Name="EnsureBclBuildImported" BeforeTargets="BeforeBuild" Condition="'$(BclBuildImported)' == ''">
<Error Condition="!Exists('..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" Text="This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=317567." HelpKeyword="BCLBUILD2001" />
<Error Condition="Exists('..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" Text="The build restored NuGet packages. Build the project again to include these packages in the build. For more information, see http://go.microsoft.com/fwlink/?LinkID=317568." HelpKeyword="BCLBUILD2002" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
@@ -0,0 +1,144 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
namespace Disco.Services.Plugins.ManifestGenerator
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 1)
{
throw new ArgumentException("Only one command-line argument is expected, the path to the plugin assembly");
}
var assemblyPath = args[0];
var assemblyFileInfo = new FileInfo(assemblyPath);
// Ensure File Exists
if (!assemblyFileInfo.Exists)
{
throw new ArgumentException($"File not found at: {assemblyFileInfo.FullName}");
}
Console.WriteLine("Disco Plugin: Generating Manifest");
AppDomain.CurrentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad;
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
// Load Plugin Assembly
Assembly assembly;
try
{
assembly = Assembly.LoadFile(assemblyFileInfo.FullName);
}
catch (Exception ex)
{
throw new Exception($"Unable to load the Assembly: {assemblyFileInfo.FullName}", ex);
}
// Load Reference Assemblies
foreach (var referenceAssembly in assemblyFileInfo.Directory.GetFiles("*.dll"))
{
if (referenceAssembly.FullName != assemblyFileInfo.FullName)
{
if (!PluginManifest.PluginExcludedAssemblies.Any(excludeAssembly => referenceAssembly.Name.StartsWith(excludeAssembly, StringComparison.OrdinalIgnoreCase)))
{
try
{
Assembly.LoadFile(referenceAssembly.FullName);
}
catch (Exception ex)
{
Console.WriteLine($"Disco Plugin: Warning: Unable to load reference '{referenceAssembly.FullName}'; {ex.Message}");
}
}
}
}
// Create Manifest
var manifest = PluginManifest.FromPluginAssembly(assembly);
var manifestFilePath = Path.Combine(assemblyFileInfo.DirectoryName, "manifest.json");
File.WriteAllText(manifestFilePath, manifest.ToManifestFile());
Console.WriteLine("Disco Plugin: Manifest Created");
Console.WriteLine("Disco Plugin: Building Package");
var packageFileName = $"{manifest.Id}-{manifest.Version}.discoPlugin";
var packageFilePath = Path.Combine(assemblyFileInfo.DirectoryName, packageFileName);
// Delete Existing Package Files
foreach (var existingPackages in assemblyFileInfo.Directory.EnumerateFiles($"{manifest.Id}*.discoPlugin"))
{
existingPackages.Delete();
}
// Exclude Disco Provided Assemblies
List<string> excludedFiles = PluginManifest.PluginExcludedAssemblies.ToList();
// Exclude the Package File
excludedFiles.Add(packageFileName);
using (FileStream packageStream = new FileStream(packageFilePath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None))
{
using (ZipArchive package = new ZipArchive(packageStream, ZipArchiveMode.Create))
{
BuildZipPackage(package, string.Empty, assemblyFileInfo.Directory, excludedFiles);
}
}
Console.WriteLine($"Disco Plugin: Package Build: '{packageFileName}'");
}
static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
Console.WriteLine("CurrentDomain_AssemblyResolve: {0} - {1}", args.Name, args.RequestingAssembly.FullName);
foreach (var loadedAssembly in AppDomain.CurrentDomain.GetAssemblies())
{
if (loadedAssembly.FullName == args.Name)
return loadedAssembly;
}
return null;
}
static void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args)
{
Console.WriteLine("CurrentDomain_AssemblyLoad: {0} - {1}", args.LoadedAssembly.FullName, args.LoadedAssembly.Location);
}
static void BuildZipPackage(ZipArchive package, string relativePath, DirectoryInfo directory, List<string> excludedFiles)
{
foreach (var subDirectory in directory.EnumerateDirectories())
{
BuildZipPackage(package, string.Concat(relativePath, subDirectory.Name, "\\"), subDirectory, excludedFiles);
}
foreach (var file in directory.EnumerateFiles())
{
if (!excludedFiles.Any(excludeRule => file.Name.StartsWith(excludeRule, StringComparison.OrdinalIgnoreCase)))
{
var archiveEntry = package.CreateEntry(string.Concat(relativePath, file.Name), CompressionLevel.Fastest);
using (var archiveStream = archiveEntry.Open())
{
using (var fileStream = file.OpenRead())
{
fileStream.CopyTo(archiveStream);
}
}
}
}
}
}
}
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Disco ICT - Plugin Manifest Generator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("https://discoict.com.au")]
[assembly: AssemblyProduct("Disco ICT")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("35e90902-d5a6-4c14-ba6b-2df976e4b96a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.16272.1003")]
[assembly: AssemblyFileVersion("2.0.16272.1003")]
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Bcl" version="1.1.9" targetFramework="net452" />
<package id="Microsoft.Bcl.Build" version="1.0.14" targetFramework="net452" />
<package id="Microsoft.Net.Http" version="2.2.22" targetFramework="net452" />
</packages>
@@ -1,18 +1,95 @@
using Disco.Data.Repository;
using Disco.Models.Repository;
using Disco.Services.Authorization;
using Disco.Services.Documents.ManagedGroups;
using Disco.Services.Users;
using Exceptionless;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.Services
{
public static class AttachmentActionExtensions
{
#region Delete
public static bool CanDelete(this DeviceAttachment da)
{
if (UserService.CurrentAuthorization.Has(Claims.Device.Actions.RemoveAnyAttachments))
return true;
if (UserService.CurrentAuthorization.Has(Claims.Device.Actions.RemoveOwnAttachments)
&& da.TechUserId.Equals(UserService.CurrentUserId, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
public static void OnDelete(this DeviceAttachment da, DiscoDataContext Database)
{
if (!da.CanDelete())
throw new InvalidOperationException("Deletion of Attachment is Denied");
var attachmentId = da.Id;
var documentTemplateId = da.DocumentTemplateId;
var deviceSerialNumber = da.DeviceSerialNumber;
da.RepositoryDelete(Database);
Database.DeviceAttachments.Remove(da);
DocumentTemplateManagedGroups.TriggerDeviceAttachmentDeleted(Database, attachmentId, documentTemplateId, deviceSerialNumber);
}
public static bool CanDelete(this JobAttachment ja)
{
if (UserService.CurrentAuthorization.Has(Claims.Job.Actions.RemoveAnyAttachments))
return true;
if (UserService.CurrentAuthorization.Has(Claims.Job.Actions.RemoveOwnAttachments)
&& ja.TechUserId.Equals(UserService.CurrentUserId, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
public static void OnDelete(this JobAttachment ja, DiscoDataContext Database)
{
if (!ja.CanDelete())
throw new InvalidOperationException("Deletion of Attachment is Denied");
var attachmentId = ja.Id;
var documentTemplateId = ja.DocumentTemplateId;
var jobId = ja.JobId;
ja.RepositoryDelete(Database);
Database.JobAttachments.Remove(ja);
DocumentTemplateManagedGroups.TriggerJobAttachmentDeleted(Database, attachmentId, documentTemplateId, jobId);
}
public static bool CanDelete(this UserAttachment ua)
{
if (UserService.CurrentAuthorization.Has(Claims.User.Actions.RemoveAnyAttachments))
return true;
if (UserService.CurrentAuthorization.Has(Claims.User.Actions.RemoveOwnAttachments)
&& ua.TechUserId.Equals(UserService.CurrentUserId, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
public static void OnDelete(this UserAttachment ua, DiscoDataContext Database)
{
if (!ua.CanDelete())
throw new InvalidOperationException("Deletion of Attachment is Denied");
var attachmentId = ua.Id;
var documentTemplateId = ua.DocumentTemplateId;
var userId = ua.UserId;
ua.RepositoryDelete(Database);
Database.UserAttachments.Remove(ua);
DocumentTemplateManagedGroups.TriggerUserAttachmentDeleted(Database, attachmentId, documentTemplateId, userId);
}
#endregion
public static DeviceAttachment CreateAttachment(this Device Device, DiscoDataContext Database, User CreatorUser, string Filename, string MimeType, string Comments, Stream Content, DocumentTemplate DocumentTemplate = null, Image PdfThumbnail = null)
{
if (string.IsNullOrEmpty(MimeType) || MimeType.Equals("unknown/unknown", StringComparison.OrdinalIgnoreCase))
@@ -149,8 +226,8 @@ namespace Disco.Services
{
using (Image sourceImage = Image.FromStream(Source))
{
Thumbnail = sourceImage.ResizeImage(48, 48);
using (Image mimeTypeIcon = Disco.Services.Properties.Resources.MimeType_img16)
Thumbnail = sourceImage.ResizeImage(48, 48, Brushes.Black);
using (Image mimeTypeIcon = Properties.Resources.MimeType_img16)
{
Thumbnail.EmbedIconOverlay(mimeTypeIcon);
}
@@ -177,8 +254,15 @@ namespace Disco.Services
var pageSize = pdfiumDocument.PageSizes[0];
var size = ImagingExtensions.CalculateResize((int)pageSize.Width, (int)pageSize.Height, 48, 48);
Thumbnail = pdfiumDocument.Render(0, (int)size.Width, (int)size.Height, 72, 72, true);
return true;
using (var sourceImage = pdfiumDocument.Render(0, (int)size.Width, (int)size.Height, 72, 72, true))
{
Thumbnail = sourceImage.ResizeImage(48, 48, Brushes.White);
using (Image mimeTypeIcon = Properties.Resources.MimeType_pdf16)
{
Thumbnail.EmbedIconOverlay(mimeTypeIcon);
}
return true;
}
}
}
}
@@ -1,21 +1,16 @@
using Disco.Data.Repository;
using Disco.Models.Services.Authorization;
using Disco.Models.Repository;
using Disco.Models.Services.Authorization;
using Disco.Services.Users;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.BI.Extensions
namespace Disco.Services
{
public static class AuthorizationRoleExtensions
{
public static void Delete(this IRoleToken roleToken, DiscoDataContext Database)
{
var role = Database.AuthorizationRoles.Find(roleToken.Role.Id);
var role = Database.AuthorizationRoles.Find(roleToken.Role.Id);
UserService.DeleteAuthorizationRole(Database, roleToken.Role);
}
@@ -1,14 +1,16 @@
using Disco.Data.Repository;
using Disco.Models.ClientServices;
using Disco.Services.Authorization;
using Disco.Services.Devices.Enrolment;
using Disco.Services.Users;
using System;
using System.Web;
namespace Disco.BI.Extensions
namespace Disco.Services
{
public static class ClientServicesExtensions
{
public static EnrolResponse BuildResponse(this Enrol request)
{
if (HttpContext.Current == null)
@@ -20,7 +22,7 @@ namespace Disco.BI.Extensions
using (DiscoDataContext database = new DiscoDataContext())
{
EnrolResponse response = DeviceBI.DeviceEnrol.Enrol(database, username, request);
EnrolResponse response = DeviceEnrolment.Enrol(database, username, request);
database.SaveChanges();
return response;
}
@@ -59,24 +61,7 @@ namespace Disco.BI.Extensions
using (DiscoDataContext database = new DiscoDataContext())
{
MacEnrolResponse response = DeviceBI.DeviceEnrol.MacEnrol(database, request, false);
database.SaveChanges();
return response;
}
}
public static RegisterResponse BuildResponse(this Register request)
{
if (HttpContext.Current == null)
throw new PlatformNotSupportedException("This function can only be accessed from within ASP.NET");
string username = null;
if (HttpContext.Current.Request.IsAuthenticated)
username = HttpContext.Current.User.Identity.Name;
using (DiscoDataContext database = new DiscoDataContext())
{
RegisterResponse response = DeviceBI.DeviceEnrol.Register(database, username, request);
MacEnrolResponse response = DeviceEnrolment.MacEnrol(database, request, false);
database.SaveChanges();
return response;
}
@@ -1,16 +1,16 @@
using Disco.Data.Repository;
using Disco.Models.Repository;
using Disco.Services;
using Disco.Services.Authorization;
using Disco.Services.Interop.ActiveDirectory;
using Disco.Services.Users;
using System;
using System.Linq;
namespace Disco.BI.Extensions
namespace Disco.Services
{
public static class DeviceActionExtensions
{
public static bool IsDecommissioned(this Device d)
{
return d.DecommissionedDate.HasValue;
@@ -187,5 +187,6 @@ namespace Disco.BI.Extensions
Database.Devices.Remove(d);
}
#endregion
}
}
@@ -7,7 +7,7 @@ using Disco.Services.Users;
using System;
using System.Linq;
namespace Disco.BI.Extensions
namespace Disco.Services
{
public static class DeviceBatchExtensions
{
@@ -1,14 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Disco.Data.Repository;
using Disco.Models.Repository;
using Disco.Data.Repository;
using System;
namespace Disco.BI.DeviceBI
namespace Disco.Services.Devices
{
public static class BatchUtilities
public static class DeviceBatches
{
public static DeviceBatch DefaultNewDeviceBatch(DiscoDataContext Database)
{
return new DeviceBatch()
@@ -0,0 +1,116 @@
using Disco.Data.Repository;
using Disco.Models.ClientServices;
using Disco.Models.ClientServices.EnrolmentInformation;
using Disco.Models.Repository;
using Disco.Services.Plugins.Features.CertificateAuthorityProvider;
using Disco.Services.Plugins.Features.CertificateProvider;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
namespace Disco.Services
{
public static class DeviceCertificateExtensions
{
public static CertificateStore ProvisionCertificates(this Device device, DiscoDataContext Database, Enrol Enrolment, out List<DeviceCertificate> ProvisionedCertificates)
{
var personalCertificates = new List<byte[]>();
var personalCertificatesRemove = new List<string>();
var intermediateCertificates = new List<byte[]>();
var intermediateCertificatesRemove = new List<string>();
var trustedRootCertificates = new List<byte[]>();
var trustedRootCertificatesRemove = new List<string>();
ProvisionedCertificates = new List<DeviceCertificate>();
foreach (var pluginFeature in device.DeviceProfile.GetCertificateProviders())
{
using (var providerFeature = pluginFeature.CreateInstance<CertificateProviderFeature>())
{
var personalResult = providerFeature.ProvisionPersonalCertificate(Database, device, Enrolment);
if (personalResult != null)
{
if (personalResult.AllocatedCertificates != null && personalResult.AllocatedCertificates.Count > 0)
{
// Avoid transporting certificates if they are already installed
foreach (var certificate in personalResult.AllocatedCertificates)
{
var x509Certificate = new X509Certificate2(certificate.Content, "password");
if (!Enrolment.Certificates.Any(c => c.Thumbprint.Equals(x509Certificate.Thumbprint, StringComparison.OrdinalIgnoreCase)))
{
personalCertificates.Add(certificate.Content);
ProvisionedCertificates.Add(certificate);
}
}
}
if (personalResult.RemoveCertificateThumbprints != null && personalResult.RemoveCertificateThumbprints.Count > 0)
{
personalCertificatesRemove.AddRange(personalResult.RemoveCertificateThumbprints);
}
}
}
}
foreach (var pluginFeature in device.DeviceProfile.GetCertificateAuthorityProviders())
{
using (var providerFeature = pluginFeature.CreateInstance<CertificateAuthorityProviderFeature>())
{
var caResult = providerFeature.ProvisionAuthorityCertificates(Database, device, Enrolment);
if (caResult.TrustedRootCertificates != null && caResult.TrustedRootCertificates.Count > 0)
{
trustedRootCertificates.AddRange(caResult.TrustedRootCertificates);
}
if (caResult.TrustedRootCertificateRemoveThumbprints != null && caResult.TrustedRootCertificateRemoveThumbprints.Count > 0)
{
trustedRootCertificatesRemove.AddRange(caResult.TrustedRootCertificateRemoveThumbprints);
}
if (caResult.IntermediateCertificates != null && caResult.IntermediateCertificates.Count > 0)
{
intermediateCertificates.AddRange(caResult.IntermediateCertificates);
}
if (caResult.IntermediateCertificateRemoveThumbprints != null && caResult.IntermediateCertificateRemoveThumbprints.Count > 0)
{
intermediateCertificatesRemove.AddRange(caResult.IntermediateCertificateRemoveThumbprints);
}
}
}
if (personalCertificates.Count == 0 && personalCertificatesRemove.Count == 0 &&
intermediateCertificates.Count == 0 && intermediateCertificatesRemove.Count == 0 &&
trustedRootCertificates.Count == 0 && trustedRootCertificatesRemove.Count == 0)
{
return null;
}
else
{
return new CertificateStore()
{
TrustedRootCertificates = trustedRootCertificates.Count > 0 ? trustedRootCertificates : null,
TrustedRootRemoveThumbprints = trustedRootCertificatesRemove.Count > 0 ? trustedRootCertificatesRemove : null,
IntermediateCertificates = intermediateCertificates.Count > 0 ? intermediateCertificates : null,
IntermediateRemoveThumbprints = intermediateCertificatesRemove.Count > 0 ? intermediateCertificatesRemove : null,
PersonalCertificates = personalCertificates.Count > 0 ? personalCertificates : null,
PersonalRemoveThumbprints = personalCertificatesRemove.Count > 0 ? personalCertificatesRemove : null
};
}
}
public static DateTime? CertificateExpirationDate(this DeviceCertificate wc)
{
if (wc.Content == null || wc.Content.Length == 0)
{
return null;
}
var c = new X509Certificate2(wc.Content, "password");
return c.NotAfter;
}
}
}
@@ -2,11 +2,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace Disco.BI.Extensions
namespace Disco.Services
{
public static class DeviceDetailExtensions
{
@@ -1,22 +1,21 @@
using Disco.Data.Repository;
using Disco.Data.Repository;
using Disco.Models.Repository;
using Disco.Models.Services.Documents;
using Disco.Services;
using Disco.Services.Authorization;
using Disco.Services.Expressions;
using Disco.Services.Interop.ActiveDirectory;
using Disco.Services.Users;
using Exceptionless;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.BI.Extensions
namespace Disco.Services
{
public static class DeviceExtensions
{
public static string ComputerNameRender(this Device device, DiscoDataContext Database, ADDomain Domain)
{
if (Domain == null)

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