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,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,28 +0,0 @@
using Disco.Data.Repository;
using Disco.Models.Services.Authorization;
using Disco.Models.Repository;
using Disco.Services.Users;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Disco.BI.Extensions
{
public static class AuthorizationRoleExtensions
{
public static void Delete(this IRoleToken roleToken, DiscoDataContext Database)
{
var role = Database.AuthorizationRoles.Find(roleToken.Role.Id);
UserService.DeleteAuthorizationRole(Database, roleToken.Role);
}
public static void Delete(this AuthorizationRole role, DiscoDataContext Database)
{
UserService.DeleteAuthorizationRole(Database, role);
}
}
}
@@ -1,86 +0,0 @@
using Disco.Data.Repository;
using Disco.Models.ClientServices;
using Disco.Services.Authorization;
using Disco.Services.Users;
using System;
using System.Web;
namespace Disco.BI.Extensions
{
public static class ClientServicesExtensions
{
public static EnrolResponse BuildResponse(this Enrol 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())
{
EnrolResponse response = DeviceBI.DeviceEnrol.Enrol(database, username, request);
database.SaveChanges();
return response;
}
}
public static WhoAmIResponse BuildResponse(this WhoAmI 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;
if (username == null)
throw new InvalidOperationException("Unauthenticated Http Context");
using (DiscoDataContext database = new DiscoDataContext())
{
AuthorizationToken token = UserService.GetAuthorization(username, database, true);
WhoAmIResponse response = new WhoAmIResponse()
{
Username = token.User.UserId,
DisplayName = token.User.DisplayName,
Type = token.Has(Claims.ComputerAccount) ? "Computer Account" : "User Account"
};
return response;
}
}
public static MacEnrolResponse BuildResponse(this MacEnrol request)
{
if (HttpContext.Current == null)
throw new PlatformNotSupportedException("This function can only be accessed from within ASP.NET");
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);
database.SaveChanges();
return response;
}
}
}
}
@@ -1,191 +0,0 @@
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
{
public static class DeviceActionExtensions
{
public static bool IsDecommissioned(this Device d)
{
return d.DecommissionedDate.HasValue;
}
public static bool CanCreateJob(this Device d)
{
if (!JobActionExtensions.CanCreate())
return false;
return !d.IsDecommissioned();
}
public static bool CanUpdateAssignment(this Device d)
{
if (!UserService.CurrentAuthorization.Has(Claims.Device.Actions.AssignUser))
return false;
return !d.IsDecommissioned();
}
public static bool CanUpdateDeviceProfile(this Device d)
{
if (!UserService.CurrentAuthorization.Has(Claims.Device.Properties.DeviceProfile))
return false;
return !d.IsDecommissioned();
}
public static bool CanUpdateDeviceBatch(this Device d)
{
if (!UserService.CurrentAuthorization.Has(Claims.Device.Properties.DeviceBatch))
return false;
return !d.IsDecommissioned();
}
public static bool CanUpdateTrustEnrol(this Device d)
{
if (!UserService.CurrentAuthorization.Has(Claims.Device.Actions.AllowUnauthenticatedEnrol))
return false;
return !d.IsDecommissioned() && !d.AllowUnauthenticatedEnrol;
}
public static bool CanUpdateUntrustEnrol(this Device d)
{
if (!UserService.CurrentAuthorization.Has(Claims.Device.Actions.AllowUnauthenticatedEnrol))
return false;
return !d.IsDecommissioned() && d.AllowUnauthenticatedEnrol;
}
#region Decommission
public static bool CanDecommission(this Device d)
{
if (!UserService.CurrentAuthorization.Has(Claims.Device.Actions.Decommission))
return false;
if (d.DecommissionedDate.HasValue)
return false; // Already Decommissioned
if (d.AssignedUserId != null)
return false; // User Assigned to Device
if (d.Jobs.Count(j => !j.ClosedDate.HasValue) > 0)
return false; // Device linked to > 0 Open Jobs
return true;
}
public static void OnDecommission(this Device d, Disco.Models.Repository.DecommissionReasons Reason)
{
if (!d.CanDecommission())
throw new InvalidOperationException("Decommission of Device is Denied");
d.DecommissionedDate = DateTime.Now;
d.DecommissionReason = Reason;
// Disable AD Account
if (ActiveDirectory.IsValidDomainAccountId(d.DeviceDomainId))
{
var adAccount = d.ActiveDirectoryAccount();
if (adAccount != null && !adAccount.IsCriticalSystemObject)
{
adAccount.DisableAccount();
}
}
}
#endregion
#region Recommission
public static bool CanRecommission(this Device d)
{
if (!UserService.CurrentAuthorization.Has(Claims.Device.Actions.Recommission))
return false;
return d.DecommissionedDate.HasValue;
}
public static void OnRecommission(this Device d)
{
if (!d.CanRecommission())
throw new InvalidOperationException("Recommission of Device is Denied");
d.DecommissionedDate = null;
d.DecommissionReason = null;
// Enable AD Account
if (ActiveDirectory.IsValidDomainAccountId(d.DeviceDomainId))
{
var adAccount = d.ActiveDirectoryAccount();
if (adAccount != null && !adAccount.IsCriticalSystemObject)
{
adAccount.EnableAccount();
}
}
}
#endregion
#region Delete
public static bool CanDelete(this Device d)
{
if (!UserService.CurrentAuthorization.Has(Claims.Device.Actions.Delete))
return false;
return d.DecommissionedDate.HasValue;
}
public static void OnDelete(this Device d, DiscoDataContext Database)
{
// Delete Jobs
foreach (Job j in Database.Jobs.Where(i => i.DeviceSerialNumber == d.SerialNumber))
{
if (j.UserId == null)
{ // No User associated, thus must Delete whole Job
if (j.CanDelete())
j.OnDelete(Database);
else
throw new InvalidOperationException(string.Format("Deletion of Device is Denied (See Job# {0})", j.Id));
}
else
{
// User associated to Job, thus just remove Devices' association
j.DeviceSerialNumber = null;
// Write Job Log
JobLog jobLog = new JobLog()
{
JobId = j.Id,
TechUserId = UserService.CurrentUser.UserId,
Timestamp = DateTime.Now,
Comments = string.Format("# Device Deleted\r\n\r\nSerial Number: **{0}**\r\nComputer Name: **{1}**\r\nModel: **{2}**\r\nProfile: **{3}**",
d.SerialNumber, d.DeviceDomainId, d.DeviceModel, d.DeviceProfile)
};
Database.JobLogs.Add(jobLog);
}
}
// Disable Wireless Certificates
foreach (var wc in Database.DeviceCertificates.Where(i => i.DeviceSerialNumber == d.SerialNumber))
{
wc.DeviceSerialNumber = null;
wc.Enabled = false;
}
// Delete Device Details
foreach (var dd in Database.DeviceDetails.Where(i => i.DeviceSerialNumber == d.SerialNumber))
Database.DeviceDetails.Remove(dd);
// Delete Device Attachments
foreach (var da in Database.DeviceAttachments.Where(i => i.DeviceSerialNumber == d.SerialNumber))
{
da.RepositoryDelete(Database);
Database.DeviceAttachments.Remove(da);
}
// Delete Device User Assignments
foreach (var dua in Database.DeviceUserAssignments.Where(i => i.DeviceSerialNumber == d.SerialNumber))
Database.DeviceUserAssignments.Remove(dua);
Database.Devices.Remove(d);
}
#endregion
}
}
@@ -1,40 +0,0 @@
using Disco.Data.Repository;
using Disco.Models.Repository;
using Disco.Services.Authorization;
using Disco.Services.Devices.ManagedGroups;
using Disco.Services.Interop.ActiveDirectory;
using Disco.Services.Users;
using System;
using System.Linq;
namespace Disco.BI.Extensions
{
public static class DeviceBatchExtensions
{
public static bool CanDelete(this DeviceBatch db, DiscoDataContext Database)
{
if (!UserService.CurrentAuthorization.Has(Claims.Config.DeviceBatch.Delete))
return false;
// Can't Delete if Contains Devices
var deviceCount = Database.Devices.Count(d => d.DeviceBatchId == db.Id);
if (deviceCount > 0)
return false;
return true;
}
public static void Delete(this DeviceBatch db, DiscoDataContext Database)
{
if (!db.CanDelete(Database))
throw new InvalidOperationException("The state of this Device Batch doesn't allow it to be deleted");
// Remove Linked Group
ActiveDirectory.Context.ManagedGroups.Remove(DeviceBatchDevicesManagedGroup.GetKey(db));
ActiveDirectory.Context.ManagedGroups.Remove(DeviceBatchAssignedUsersManagedGroup.GetKey(db));
// Delete Batch
Database.DeviceBatches.Remove(db);
}
}
}
@@ -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,162 +0,0 @@
using Disco.Models.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace Disco.BI.Extensions
{
public static class DeviceDetailExtensions
{
#region Helpers
private static string GetDetail(this IEnumerable<DeviceDetail> details, string Scope, string Key)
{
if (details == null)
throw new ArgumentNullException("details");
if (string.IsNullOrEmpty(Scope))
throw new ArgumentNullException("Scope");
if (string.IsNullOrEmpty(Key))
throw new ArgumentNullException("Key");
var detail = details.Where(d => d.Key == Key).FirstOrDefault();
if (detail == null)
return null;
else
return detail.Value;
}
private static void SetDetail(this Device device, string Scope, string Key, string Value)
{
if (device == null)
throw new ArgumentNullException("device");
if (string.IsNullOrEmpty(Scope))
throw new ArgumentNullException("Scope");
if (string.IsNullOrEmpty(Key))
throw new ArgumentNullException("Key");
var detail = device.DeviceDetails.Where(d => d.Scope == Scope && d.Key == Key).FirstOrDefault();
// No Detail Stored & Set to Null
if (detail == null && Value == null)
return;
if (detail == null)
{
detail = new DeviceDetail()
{
DeviceSerialNumber = device.SerialNumber,
Scope = Scope,
Key = Key,
Value = Value
};
device.DeviceDetails.Add(detail);
}
if (detail.Value != Value)
{
if (Value == null)
{
device.DeviceDetails.Remove(detail);
}
else
{
detail.Value = Value;
}
}
}
#endregion
#region LanMacAddress
/// <summary>
/// Gets the LanMacAddress Device Detail Value
/// </summary>
/// <returns>The LanMacAddress or null</returns>
public static string LanMacAddress(this IEnumerable<DeviceDetail> details)
{
return details.GetDetail(DeviceDetail.ScopeHardware, DeviceDetail.HardwareKeyLanMacAddress);
}
/// <summary>
/// Sets the LanMacAddress Device Detail Value
/// </summary>
public static void LanMacAddress(this IEnumerable<DeviceDetail> details, Device device, string LanMacAddress)
{
device.SetDetail(DeviceDetail.ScopeHardware, DeviceDetail.HardwareKeyLanMacAddress, LanMacAddress);
}
#endregion
#region WLanMacAddress
/// <summary>
/// Gets the WLanMacAddress Device Detail Value
/// </summary>
/// <returns>The WLanMacAddress or null</returns>
public static string WLanMacAddress(this IEnumerable<DeviceDetail> details)
{
return details.GetDetail(DeviceDetail.ScopeHardware, DeviceDetail.HardwareKeyWLanMacAddress);
}
/// <summary>
/// Sets the WLanMacAddress Device Detail Value
/// </summary>
public static void WLanMacAddress(this IEnumerable<DeviceDetail> details, Device device, string WLanMacAddress)
{
device.SetDetail(DeviceDetail.ScopeHardware, DeviceDetail.HardwareKeyWLanMacAddress, WLanMacAddress);
}
#endregion
#region ACAdapter
/// <summary>
/// Gets the ACAdapter Device Detail Value
/// </summary>
/// <returns>The ACAdapter or null</returns>
public static string ACAdapter(this IEnumerable<DeviceDetail> details)
{
return details.GetDetail(DeviceDetail.ScopeHardware, DeviceDetail.HardwareKeyACAdapter);
}
/// <summary>
/// Sets the ACAdapter Device Detail Value
/// </summary>
public static void ACAdapter(this IEnumerable<DeviceDetail> details, Device device, string ACAdapter)
{
device.SetDetail(DeviceDetail.ScopeHardware, DeviceDetail.HardwareKeyACAdapter, ACAdapter);
}
#endregion
#region Battery
/// <summary>
/// Gets the Battery Device Detail Value
/// </summary>
/// <returns>The Battery or null</returns>
public static string Battery(this IEnumerable<DeviceDetail> details)
{
return details.GetDetail(DeviceDetail.ScopeHardware, DeviceDetail.HardwareKeyBattery);
}
/// <summary>
/// Sets the Battery Device Detail Value
/// </summary>
public static void Battery(this IEnumerable<DeviceDetail> details, Device device, string Battery)
{
device.SetDetail(DeviceDetail.ScopeHardware, DeviceDetail.HardwareKeyBattery, Battery);
}
#endregion
#region Keyboard
/// <summary>
/// Gets the Keyboard Device Detail Value
/// </summary>
/// <returns>The Keyboard or null</returns>
public static string Keyboard(this IEnumerable<DeviceDetail> details)
{
return details.GetDetail(DeviceDetail.ScopeHardware, DeviceDetail.HardwareKeyKeyboard);
}
/// <summary>
/// Sets the Keyboard Device Detail Value
/// </summary>
public static void Keyboard(this IEnumerable<DeviceDetail> details, Device device, string Keyboard)
{
device.SetDetail(DeviceDetail.ScopeHardware, DeviceDetail.HardwareKeyKeyboard, Keyboard);
}
#endregion
}
}
-215
View File
@@ -1,215 +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.Expressions;
using Disco.Services.Interop.ActiveDirectory;
using Disco.Services.Users;
using Exceptionless;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Disco.BI.Extensions
{
public static class DeviceExtensions
{
public static string ComputerNameRender(this Device device, DiscoDataContext Database, ADDomain Domain)
{
if (Domain == null)
throw new ArgumentNullException("Domain");
var deviceProfile = device.DeviceProfile;
Expression computerNameTemplateExpression = null;
computerNameTemplateExpression = ExpressionCache.GetValue(DeviceProfileExtensions.ComputerNameExpressionCacheModule, deviceProfile.Id.ToString(), () =>
{
// Removed 2012-06-14 G# - Properties moved to DeviceProfile model & DB Migrated in DBv3.
//return Expressions.Expression.TokenizeSingleDynamic(null, deviceProfile.Configuration(context).ComputerNameTemplate, 0);
return Expression.TokenizeSingleDynamic(null, deviceProfile.ComputerNameTemplate, 0);
});
var evaluatorVariables = Expression.StandardVariables(null, Database, UserService.CurrentUser, DateTime.Now, null);
string rendered;
try
{
rendered = computerNameTemplateExpression.EvaluateFirst<string>(device, evaluatorVariables);
}
catch (Exception ex)
{
ex.ToExceptionless().AddObject(deviceProfile.ComputerNameTemplate, "ComputerNameTemplate").Submit();
throw new InvalidOperationException(string.Format("An error occurred rendering the computer name: [{0}] {1}", ex.GetType().Name, ex.Message), ex.InnerException);
}
if (rendered == null || rendered.Length > 24)
{
throw new InvalidOperationException("The rendered computer name would be invalid or longer than 24 characters");
}
return string.Format(@"{0}\{1}", Domain.NetBiosName, rendered);
}
public static List<DocumentTemplate> AvailableDocumentTemplates(this Device d, DiscoDataContext Database, User User, DateTime TimeStamp)
{
List<DocumentTemplate> ats = Database.DocumentTemplates
.Where(at => at.Scope == DocumentTemplate.DocumentTemplateScopes.Device).ToList();
return ats.Where(at => at.FilterExpressionMatches(d, Database, User, TimeStamp, DocumentState.DefaultState())).ToList();
}
public static bool UpdateLastNetworkLogonDate(this Device Device)
{
return ADNetworkLogonDatesUpdateTask.UpdateLastNetworkLogonDate(Device);
}
public static Device AddOffline(this Device d, DiscoDataContext Database)
{
// Just Include:
// - Serial Number
// - Asset Number
// - Profile Id
// - Assigned User Id
// - Batch
// Enforce Authorization
var auth = UserService.CurrentAuthorization;
if (!auth.Has(Claims.Device.Properties.AssetNumber))
d.AssetNumber = null;
if (!auth.Has(Claims.Device.Properties.Location))
d.Location = null;
if (!auth.Has(Claims.Device.Properties.DeviceBatch))
d.DeviceBatchId = null;
if (!auth.Has(Claims.Device.Properties.DeviceProfile))
d.DeviceProfileId = Database.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId;
if (!auth.Has(Claims.Device.Actions.AssignUser))
d.AssignedUserId = null;
// Batch
DeviceBatch db = default(DeviceBatch);
if (d.DeviceBatchId.HasValue)
db = Database.DeviceBatches.Find(d.DeviceBatchId.Value);
// Default Device Model
DeviceModel dm = default(DeviceModel);
if (db != null && db.DefaultDeviceModelId.HasValue)
dm = Database.DeviceModels.Find(db.DefaultDeviceModelId); // From Batch
else
dm = Database.DeviceModels.Find(1); // Default
Device d2 = new Device()
{
SerialNumber = d.SerialNumber.ToUpper(),
AssetNumber = d.AssetNumber,
Location = d.Location,
CreatedDate = DateTime.Now,
DeviceProfileId = d.DeviceProfileId,
DeviceProfile = Database.DeviceProfiles.Find(d.DeviceProfileId),
AllowUnauthenticatedEnrol = true,
DeviceModelId = dm.Id,
DeviceModel = dm,
DeviceBatchId = d.DeviceBatchId,
DeviceBatch = db
};
Database.Devices.Add(d2);
if (!string.IsNullOrEmpty(d.AssignedUserId))
{
User u = UserService.GetUser(ActiveDirectory.ParseDomainAccountId(d.AssignedUserId), Database, true);
d2.AssignDevice(Database, u);
}
return d2;
}
public static DeviceUserAssignment AssignDevice(this Device d, DiscoDataContext Database, User u)
{
DeviceUserAssignment newDua = default(DeviceUserAssignment);
// Mark existing assignments as Unassigned
foreach (var dua in Database.DeviceUserAssignments.Where(m => m.DeviceSerialNumber == d.SerialNumber && !m.UnassignedDate.HasValue))
dua.UnassignedDate = DateTime.Now;
if (u != null)
{
// Add new Assignment
newDua = new DeviceUserAssignment()
{
DeviceSerialNumber = d.SerialNumber,
AssignedUserId = u.UserId,
AssignedDate = DateTime.Now
};
Database.DeviceUserAssignments.Add(newDua);
d.AssignedUserId = u.UserId;
d.AssignedUser = u;
}
else
{
d.AssignedUserId = null;
}
// Update AD Account
if (ActiveDirectory.IsValidDomainAccountId(d.DeviceDomainId))
{
var adMachineAccount = ActiveDirectory.RetrieveADMachineAccount(d.DeviceDomainId);
if (adMachineAccount != null)
adMachineAccount.SetDescription(d);
}
return newDua;
}
public static string ReasonMessage(this DecommissionReasons r)
{
switch (r)
{
case DecommissionReasons.EndOfLife:
return "End of Life";
case DecommissionReasons.Sold:
return "Sold";
case DecommissionReasons.Stolen:
return "Stolen";
case DecommissionReasons.Lost:
return "Lost";
case DecommissionReasons.Damaged:
return "Damaged";
case DecommissionReasons.Donated:
return "Donated";
case DecommissionReasons.Returned:
return "Returned";
default:
return "Unknown";
}
}
public static string ReasonMessage(this DecommissionReasons? r)
{
if (!r.HasValue)
return "Not Decommissioned";
return r.Value.ReasonMessage();
}
public static string StatusCode(this Device Device)
{
if (Device.DecommissionedDate.HasValue)
return "Decommissioned";
if (!Device.EnrolledDate.HasValue)
return "NotEnrolled";
return "Active";
}
public static string Status(this Device Device)
{
if (Device.DecommissionedDate.HasValue)
return string.Format("Decommissioned ({0})", Device.DecommissionReason.ReasonMessage());
if (!Device.EnrolledDate.HasValue)
return "Not Enrolled";
return "Active";
}
}
}
@@ -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,70 +0,0 @@
using Disco.Data.Repository;
using Disco.Models.BI.Config;
using Disco.Models.Repository;
using Disco.Services.Authorization;
using Disco.Services.Devices.ManagedGroups;
using Disco.Services.Expressions;
using Disco.Services.Interop.ActiveDirectory;
using Disco.Services.Users;
using System;
using System.Linq;
namespace Disco.BI.Extensions
{
public static class DeviceProfileExtensions
{
public const string ComputerNameExpressionCacheModule = "ComputerNameTemplate";
public static void ComputerNameInvalidateCache(this DeviceProfile deviceProfile)
{
ExpressionCache.InvalidateKey(ComputerNameExpressionCacheModule, deviceProfile.Id.ToString());
}
public static OrganisationAddress DefaultOrganisationAddressDetails(this DeviceProfile deviceProfile, DiscoDataContext Database)
{
if (deviceProfile.DefaultOrganisationAddress.HasValue)
{
return Database.DiscoConfiguration.OrganisationAddresses.GetAddress(deviceProfile.DefaultOrganisationAddress.Value);
}
else
{
return null;
}
}
public static bool CanDelete(this DeviceProfile dp, DiscoDataContext Database)
{
if (!UserService.CurrentAuthorization.Has(Claims.Config.DeviceProfile.Delete))
return false;
// Can't Delete Default Profile (Id: 1)
if (dp.Id == 1)
return false;
// Can't Delete if Contains Devices
if (Database.Devices.Count(d => d.DeviceProfileId == dp.Id) > 0)
return false;
return true;
}
public static void Delete(this DeviceProfile dp, DiscoDataContext Database)
{
if (!dp.CanDelete(Database))
throw new InvalidOperationException("The state of this Device Profile doesn't allow it to be deleted");
// Update Defaults
if (Database.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId == dp.Id)
Database.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId = 1;
if (Database.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId == dp.Id)
Database.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId = 1;
// Remove Linked Group
ActiveDirectory.Context.ManagedGroups.Remove(DeviceProfileDevicesManagedGroup.GetKey(dp));
ActiveDirectory.Context.ManagedGroups.Remove(DeviceProfileAssignedUsersManagedGroup.GetKey(dp));
// Delete Profile
Database.DeviceProfiles.Remove(dp);
}
}
}
@@ -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;
@@ -1,725 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Exceptionless;
using Disco.Data.Repository;
using Disco.Models.BI.Config;
using Disco.Models.Repository;
using Disco.Services.Plugins;
using Disco.Services.Plugins.Features.WarrantyProvider;
using Disco.Services.Users;
using Disco.Services.Authorization;
using Disco.Services.Plugins.Features.RepairProvider;
using PublishJobResult = Disco.Models.Services.Interop.DiscoServices.PublishJobResult;
using DiscoServicesJobs = Disco.Services.Interop.DiscoServices.Jobs;
using Disco.Services;
namespace Disco.BI.Extensions
{
public static class JobActionExtensions
{
#region Create
public static bool CanCreate()
{
if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.Create))
return false;
if (!UserService.CurrentAuthorization.HasAny(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))
return false;
return true;
}
#endregion
#region Device Held
public static bool CanDeviceHeld(this Job j)
{
if (!UserService.CurrentAuthorization.Has(Claims.Job.Properties.DeviceHeld))
return false;
return (!j.ClosedDate.HasValue) && (j.DeviceSerialNumber != null) &&
(!j.DeviceHeld.HasValue || j.DeviceReturnedDate.HasValue);
}
public static void OnDeviceHeld(this Job j, User Technician)
{
if (!j.CanDeviceHeld())
throw new InvalidOperationException("Holding Device was Denied");
j.DeviceHeld = DateTime.Now;
j.DeviceHeldTechUserId = Technician.UserId;
j.DeviceReadyForReturn = null;
j.DeviceReadyForReturnTechUserId = null;
j.DeviceReturnedDate = null;
j.DeviceReturnedTechUserId = null;
}
#endregion
#region Device Ready for Return
public static bool CanDeviceReadyForReturn(this Job j)
{
if (!UserService.CurrentAuthorization.Has(Claims.Job.Properties.DeviceReadyForReturn))
return false;
return (!j.ClosedDate.HasValue) && j.DeviceHeld.HasValue &&
!j.DeviceReadyForReturn.HasValue && !j.DeviceReturnedDate.HasValue;
}
public static void OnDeviceReadyForReturn(this Job j, User Technician)
{
if (!j.CanDeviceReadyForReturn())
throw new InvalidOperationException("Device Ready for Return was Denied");
j.DeviceReadyForReturn = DateTime.Now;
j.DeviceReadyForReturnTechUserId = Technician.UserId;
}
#endregion
#region Device Returned
public static bool CanDeviceReturned(this Job j)
{
if (!UserService.CurrentAuthorization.Has(Claims.Job.Properties.DeviceReturned))
return false;
return (!j.ClosedDate.HasValue) && j.DeviceHeld.HasValue &&
!j.DeviceReturnedDate.HasValue;
}
public static void OnDeviceReturned(this Job j, User Technician)
{
if (!j.CanDeviceReturned())
throw new InvalidOperationException("Device Return was Denied");
j.DeviceReturnedDate = DateTime.Now;
j.DeviceReturnedTechUserId = Technician.UserId;
}
#endregion
#region Waiting For User Action
public static bool CanWaitingForUserAction(this Job j)
{
if (!UserService.CurrentAuthorization.Has(Claims.Job.Properties.WaitingForUserAction))
return false;
return !j.ClosedDate.HasValue && (j.UserId != null) && !j.WaitingForUserAction.HasValue;
}
public static void OnWaitingForUserAction(this Job j, DiscoDataContext Database, User Technician, string Reason)
{
if (!j.CanWaitingForUserAction())
throw new InvalidOperationException("Waiting for User Action was Denied");
j.WaitingForUserAction = DateTime.Now;
// Write Log
JobLog jobLog = new JobLog()
{
JobId = j.Id,
TechUserId = Technician.UserId,
Timestamp = DateTime.Now,
Comments = string.Format("# Waiting on User Action\r\n{0}", string.IsNullOrWhiteSpace(Reason) ? "<no reason provided>" : Reason)
};
Database.JobLogs.Add(jobLog);
}
#endregion
#region Not Waiting For User Action
public static bool CanNotWaitingForUserAction(this Job j)
{
if (!UserService.CurrentAuthorization.Has(Claims.Job.Properties.NotWaitingForUserAction))
return false;
return j.WaitingForUserAction.HasValue;
}
public static void OnNotWaitingForUserAction(this Job j, DiscoDataContext Database, User Technician, string Resolution)
{
if (!j.CanNotWaitingForUserAction())
throw new InvalidOperationException("Not Waiting for User Action was Denied");
j.WaitingForUserAction = null;
// Write Log
JobLog jobLog = new JobLog()
{
JobId = j.Id,
TechUserId = Technician.UserId,
Timestamp = DateTime.Now,
Comments = string.Format("# User Action Resolved\r\n{0}", string.IsNullOrWhiteSpace(Resolution) ? "<no comment provided>" : Resolution)
};
Database.JobLogs.Add(jobLog);
}
#endregion
#region Log Warranty
public static bool CanLogWarranty(this Job j)
{
if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.LogWarranty))
return false;
return !j.ClosedDate.HasValue &&
(j.DeviceSerialNumber != null) &&
j.JobTypeId == JobType.JobTypeIds.HWar &&
!j.JobMetaWarranty.ExternalLoggedDate.HasValue;
}
public static void OnLogWarranty(this Job j, DiscoDataContext Database, string FaultDescription, List<JobAttachment> SendAttachments, PluginFeatureManifest WarrantyProviderDefinition, OrganisationAddress Address, User TechUser, Dictionary<string, string> WarrantyProviderProperties)
{
if (!j.CanLogWarranty())
throw new InvalidOperationException("Log Warranty was Denied");
PublishJobResult publishJobResult = null;
using (WarrantyProviderFeature WarrantyProvider = WarrantyProviderDefinition.CreateInstance<WarrantyProviderFeature>())
{
if (SendAttachments != null && SendAttachments.Count > 0)
{
publishJobResult = DiscoServicesJobs.Publish(
Database,
j,
TechUser,
WarrantyProvider.WarrantyProviderId,
null,
FaultDescription,
SendAttachments,
AttachmentDataStoreExtensions.RepositoryFilename);
if (!publishJobResult.Success)
throw new Exception(string.Format("Disco ICT Online Services failed with the following message: ", publishJobResult.ErrorMessage));
if (string.IsNullOrWhiteSpace(FaultDescription))
FaultDescription = publishJobResult.PublishMessage;
else
FaultDescription = string.Concat(FaultDescription, Environment.NewLine, "___", Environment.NewLine, publishJobResult.PublishMessage);
}
string submitDescription;
if (string.IsNullOrWhiteSpace(FaultDescription))
submitDescription = j.GenerateFaultDescriptionFooter(Database, WarrantyProviderDefinition);
else
submitDescription = string.Concat(FaultDescription, Environment.NewLine, Environment.NewLine, j.GenerateFaultDescriptionFooter(Database, WarrantyProviderDefinition));
string providerRef = WarrantyProvider.SubmitJob(Database, j, Address, TechUser, submitDescription, WarrantyProviderProperties);
j.JobMetaWarranty.ExternalLoggedDate = DateTime.Now;
j.JobMetaWarranty.ExternalName = WarrantyProvider.WarrantyProviderId;
if (providerRef != null && providerRef.Length > 100)
j.JobMetaWarranty.ExternalReference = providerRef.Substring(0, 100);
else
j.JobMetaWarranty.ExternalReference = providerRef;
// Write Log
JobLog jobLog = new JobLog()
{
JobId = j.Id,
TechUserId = TechUser.UserId,
Timestamp = DateTime.Now,
Comments = string.Format("# Warranty Claim Submitted\r\nProvider: **{0}**\r\nAddress: **{1}**\r\nReference: **{2}**\r\n___\r\n```{3}```", WarrantyProvider.Manifest.Name, Address.Name, providerRef, FaultDescription)
};
Database.JobLogs.Add(jobLog);
if (publishJobResult != null)
{
try
{
DiscoServicesJobs.UpdateRecipientReference(Database, j, publishJobResult.Id, publishJobResult.Secret, j.JobMetaWarranty.ExternalReference);
}
catch (Exception ex) { ex.ToExceptionless().Submit(); } // Ignore Errors as this is not completely necessary
}
}
}
public static void OnLogWarranty(this Job j, DiscoDataContext Database, string FaultDescription, string ManualProviderName, string ManualProviderReference, OrganisationAddress Address, User TechUser)
{
if (!j.CanLogWarranty())
throw new InvalidOperationException("Log Warranty was Denied");
j.JobMetaWarranty.ExternalLoggedDate = DateTime.Now;
j.JobMetaWarranty.ExternalName = ManualProviderName;
if (ManualProviderReference != null && ManualProviderReference.Length > 100)
j.JobMetaWarranty.ExternalReference = ManualProviderReference.Substring(0, 100);
else
j.JobMetaWarranty.ExternalReference = ManualProviderReference;
// Write Log
JobLog jobLog = new JobLog()
{
JobId = j.Id,
TechUserId = TechUser.UserId,
Timestamp = DateTime.Now,
Comments = string.Format("# Manual Warranty Claim Submitted\r\nProvider: **{0}**\r\nAddress: **{1}**\r\nReference: **{2}**\r\n___\r\n```{3}```", ManualProviderName, Address.Name, ManualProviderReference ?? "<none>", FaultDescription)
};
Database.JobLogs.Add(jobLog);
}
#endregion
#region Convert HWar to HNWar
public static bool CanConvertHWarToHNWar(this Job j)
{
if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.ConvertHWarToHNWar))
return false;
return !j.ClosedDate.HasValue && (j.DeviceSerialNumber != null) &&
j.JobTypeId == JobType.JobTypeIds.HWar && string.IsNullOrEmpty(j.JobMetaWarranty.ExternalReference);
}
public static void OnConvertHWarToHNWar(this Job j, DiscoDataContext Database)
{
if (!j.CanConvertHWarToHNWar())
throw new InvalidOperationException("Convert HWar to HNWar was Denied");
var techUser = UserService.CurrentUser;
// Remove JobMetaWarranty
if (j.JobMetaWarranty != null)
Database.JobMetaWarranties.Remove(j.JobMetaWarranty);
// Add JobMetaNonWarranty
var metaHNWar = new JobMetaNonWarranty() { Job = j };
Database.JobMetaNonWarranties.Add(metaHNWar);
// Swap Job Sub Types
List<string> jobSubTypes = j.JobSubTypes.Select(jst => jst.Id).ToList();
j.JobSubTypes.Clear();
foreach (var jst in Database.JobSubTypes.Where(i => i.JobTypeId == JobType.JobTypeIds.HNWar && jobSubTypes.Contains(i.Id)))
j.JobSubTypes.Add(jst);
// Add Components
var components = Database.DeviceComponents.Include("JobSubTypes").Where(c => !c.DeviceModelId.HasValue || c.DeviceModelId == j.Device.DeviceModelId);
var jobComponents = new List<DeviceComponent>();
foreach (var component in components)
{
if (component.JobSubTypes.Count == 0)
{
jobComponents.Add(component);
}
else
{
foreach (var st in component.JobSubTypes)
{
foreach (var jst in j.JobSubTypes)
{
if (st.JobTypeId == jst.JobTypeId && st.Id == jst.Id)
{
jobComponents.Add(component);
break;
}
}
if (jobComponents.Contains(component))
break;
}
}
}
foreach (var component in jobComponents)
{
Database.JobComponents.Add(new JobComponent()
{
Job = j,
TechUserId = techUser.UserId,
Cost = component.Cost,
Description = component.Description
});
}
// Write Log
JobLog jobLog = new JobLog()
{
JobId = j.Id,
TechUserId = techUser.UserId,
Timestamp = DateTime.Now,
Comments = string.Format("# Job Type Converted\r\nFrom: **{0}**\r\nTo: **{1}**", Database.JobTypes.Find(JobType.JobTypeIds.HWar), Database.JobTypes.Find(JobType.JobTypeIds.HNWar))
};
Database.JobLogs.Add(jobLog);
j.JobTypeId = JobType.JobTypeIds.HNWar;
}
#endregion
#region Warranty Completed
public static bool CanWarrantyCompleted(this Job j)
{
return (j.JobTypeId == JobType.JobTypeIds.HWar) &&
j.JobMetaWarranty.ExternalLoggedDate.HasValue &&
!j.JobMetaWarranty.ExternalCompletedDate.HasValue;
}
public static void OnWarrantyCompleted(this Job j)
{
if (!j.CanWarrantyCompleted())
throw new InvalidOperationException("Warranty Completed was Denied");
j.JobMetaWarranty.ExternalCompletedDate = DateTime.Now;
}
#endregion
#region Insurance Claim Form Sent
public static bool CanInsuranceClaimFormSent(this Job j)
{
if (!UserService.CurrentAuthorization.Has(Claims.Job.Properties.NonWarrantyProperties.InsuranceClaimFormSent))
return false;
return (j.JobTypeId == JobType.JobTypeIds.HNWar) &&
j.JobMetaNonWarranty.IsInsuranceClaim &&
!j.JobMetaInsurance.ClaimFormSentDate.HasValue;
}
public static void OnInsuranceClaimFormSent(this Job j)
{
if (!j.CanInsuranceClaimFormSent())
throw new InvalidOperationException("Insurance Claim Form Sent was Denied");
var techUser = UserService.CurrentUser;
j.JobMetaInsurance.ClaimFormSentDate = DateTime.Now;
j.JobMetaInsurance.ClaimFormSentUserId = techUser.UserId;
}
#endregion
#region Log Repair
public static bool CanLogRepair(this Job j)
{
if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.LogRepair))
return false;
return (j.JobTypeId == JobType.JobTypeIds.HNWar) &&
(j.DeviceSerialNumber != null) &&
!j.JobMetaNonWarranty.RepairerLoggedDate.HasValue &&
!j.JobMetaNonWarranty.RepairerCompletedDate.HasValue;
}
public static void OnLogRepair(this Job j, DiscoDataContext Database, string RepairDescription, List<JobAttachment> SendAttachments, PluginFeatureManifest RepairProviderDefinition, OrganisationAddress Address, User TechUser, Dictionary<string, string> RepairProviderProperties)
{
if (!j.CanLogRepair())
throw new InvalidOperationException("Log Repair was Denied");
PublishJobResult publishJobResult = null;
using (RepairProviderFeature RepairProvider = RepairProviderDefinition.CreateInstance<RepairProviderFeature>())
{
if (SendAttachments != null && SendAttachments.Count > 0)
{
publishJobResult = DiscoServicesJobs.Publish(
Database,
j,
TechUser,
RepairProvider.ProviderId,
null,
RepairDescription,
SendAttachments,
AttachmentDataStoreExtensions.RepositoryFilename);
if (!publishJobResult.Success)
throw new Exception(string.Format("Disco ICT Online Services failed with the following message: ", publishJobResult.ErrorMessage));
if (string.IsNullOrWhiteSpace(RepairDescription))
RepairDescription = publishJobResult.PublishMessage;
else
RepairDescription = string.Concat(RepairDescription, Environment.NewLine, "___", Environment.NewLine, publishJobResult.PublishMessage);
}
string submitDescription;
if (string.IsNullOrWhiteSpace(RepairDescription))
submitDescription = j.GenerateFaultDescriptionFooter(Database, RepairProviderDefinition);
else
submitDescription = string.Concat(RepairDescription, Environment.NewLine, Environment.NewLine, j.GenerateFaultDescriptionFooter(Database, RepairProviderDefinition));
string providerRef = RepairProvider.SubmitJob(Database, j, Address, TechUser, submitDescription, RepairProviderProperties);
j.JobMetaNonWarranty.RepairerLoggedDate = DateTime.Now;
j.JobMetaNonWarranty.RepairerName = RepairProvider.ProviderId;
if (providerRef != null && providerRef.Length > 100)
j.JobMetaNonWarranty.RepairerReference = providerRef.Substring(0, 100);
else
j.JobMetaNonWarranty.RepairerReference = providerRef;
// Write Log
JobLog jobLog = new JobLog()
{
JobId = j.Id,
TechUserId = TechUser.UserId,
Timestamp = DateTime.Now,
Comments = string.Format("# Repair Request Submitted\r\nProvider: **{0}**\r\nAddress: **{1}**\r\nReference: **{2}**\r\n___\r\n```{3}```", RepairProvider.Manifest.Name, Address.Name, providerRef, RepairDescription)
};
Database.JobLogs.Add(jobLog);
if (publishJobResult != null)
{
try
{
DiscoServicesJobs.UpdateRecipientReference(Database, j, publishJobResult.Id, publishJobResult.Secret, j.JobMetaNonWarranty.RepairerReference);
}
catch (Exception ex) { ex.ToExceptionless().Submit(); } // Ignore Errors as this is not completely necessary
}
}
}
public static void OnLogRepair(this Job j, DiscoDataContext Database, string FaultDescription, string ManualProviderName, string ManualProviderReference, OrganisationAddress Address, User TechUser)
{
if (!j.CanLogRepair())
throw new InvalidOperationException("Log Repair was Denied");
j.JobMetaNonWarranty.RepairerLoggedDate = DateTime.Now;
j.JobMetaNonWarranty.RepairerName = ManualProviderName;
if (ManualProviderReference != null && ManualProviderReference.Length > 100)
j.JobMetaNonWarranty.RepairerReference = ManualProviderReference.Substring(0, 100);
else
j.JobMetaNonWarranty.RepairerReference = ManualProviderReference;
// Write Log
JobLog jobLog = new JobLog()
{
JobId = j.Id,
TechUserId = TechUser.UserId,
Timestamp = DateTime.Now,
Comments = string.Format("# Manual Repair Request Submitted\r\nProvider: **{0}**\r\nAddress: **{1}**\r\nReference: **{2}**\r\n___\r\n```{3}```", ManualProviderName, Address.Name, ManualProviderReference ?? "<none>", FaultDescription)
};
Database.JobLogs.Add(jobLog);
}
#endregion
#region Repair Complete
public static bool CanRepairComplete(this Job j)
{
if (!UserService.CurrentAuthorization.Has(Claims.Job.Properties.NonWarrantyProperties.RepairerCompletedDate))
return false;
return (j.JobTypeId == JobType.JobTypeIds.HNWar) &&
j.JobMetaNonWarranty.RepairerLoggedDate.HasValue &&
!j.JobMetaNonWarranty.RepairerCompletedDate.HasValue;
}
public static void OnRepairComplete(this Job j)
{
if (!j.CanRepairComplete())
throw new InvalidOperationException("Repair Complete was Denied");
j.JobMetaNonWarranty.RepairerCompletedDate = DateTime.Now;
}
#endregion
#region Close
public static void OnCloseNormally(this Job j, User Technician)
{
if (!j.CanCloseNormally())
throw new InvalidOperationException("Close was Denied");
j.ClosedDate = DateTime.Now;
j.ClosedTechUserId = Technician.UserId;
}
private static bool CanCloseNever(this Job j, JobQueueJob IgnoreJobQueueJob = null)
{
if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.Close))
return true;
if (j.ClosedDate.HasValue)
return true; // Job already Closed
if (j.DeviceHeld.HasValue && !j.DeviceReturnedDate.HasValue)
return true; // Device not returned to User
if (j.WaitingForUserAction.HasValue)
return true; // Job waiting on User Action
if (j.JobQueues != null)
{
if (IgnoreJobQueueJob == null)
{
if (j.JobQueues.Any(jqj => !jqj.RemovedDate.HasValue))
return true; // Job associated with a Job Queue
}
else
{
if (j.JobQueues.Any(jqj => jqj.Id != IgnoreJobQueueJob.Id && !jqj.RemovedDate.HasValue))
return true; // Job associated with a Job Queue
}
}
return false;
}
public static bool CanCloseNormally(this Job j)
{
if (j.CanCloseNever())
return false;
return j.CanCloseNormallyInternal();
}
private static bool CanCloseNormallyInternal(this Job j)
{
switch (j.JobTypeId)
{
case JobType.JobTypeIds.HWar:
if (!string.IsNullOrEmpty(j.JobMetaWarranty.ExternalReference) && !j.JobMetaWarranty.ExternalCompletedDate.HasValue)
return false; // Job Logged (Warranty) but not completed
break;
case JobType.JobTypeIds.HNWar:
if (j.JobMetaNonWarranty.RepairerLoggedDate.HasValue && !j.JobMetaNonWarranty.RepairerCompletedDate.HasValue)
return false; // Job Logged (Repair) but not completed
if (j.JobMetaNonWarranty.AccountingChargeRequiredDate.HasValue && !j.JobMetaNonWarranty.AccountingChargeAddedDate.HasValue)
return false; // Accounting Charge Required, but not added
if ((j.JobMetaNonWarranty.AccountingChargeRequiredDate.HasValue || j.JobMetaNonWarranty.AccountingChargeAddedDate.HasValue) && !j.JobMetaNonWarranty.AccountingChargePaidDate.HasValue)
return false; // Accounting Charge Required or Added, but not paid
if (j.JobMetaNonWarranty.IsInsuranceClaim && !j.JobMetaInsurance.ClaimFormSentDate.HasValue)
return false; // Is Insurance Claim, but claim form not sent
break;
}
return true;
}
public static bool CanCloseJobNormallyAfterRemoved(this JobQueueJob jqj)
{
if (jqj.Job.CanCloseNever(jqj))
return false;
return jqj.Job.CanCloseNormallyInternal();
}
#endregion
#region Force Close
public static bool CanCloseForced(this Job j)
{
List<string> reasons;
return CanCloseForced(j, out reasons);
}
public static bool CanCloseForced(this Job j, out List<string> Reasons)
{
Reasons = null;
if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.ForceClose))
return false;
if (j.CanCloseNever())
return false;
if (j.CanCloseNormally())
return false;
Reasons = new List<string>();
switch (j.JobTypeId)
{
case JobType.JobTypeIds.HWar:
if (!string.IsNullOrEmpty(j.JobMetaWarranty.ExternalReference) && !j.JobMetaWarranty.ExternalCompletedDate.HasValue)
Reasons.Add("Warranty Job Not Completed"); // Job Logged (Warranty) but not completed
break;
case JobType.JobTypeIds.HNWar:
if (j.JobMetaNonWarranty.RepairerLoggedDate.HasValue && !j.JobMetaNonWarranty.RepairerCompletedDate.HasValue)
Reasons.Add("Repair Job Not Completed"); // Job Logged (Repair) but not completed
if (j.JobMetaNonWarranty.AccountingChargeRequiredDate.HasValue && (!j.JobMetaNonWarranty.AccountingChargeAddedDate.HasValue && !j.JobMetaNonWarranty.AccountingChargePaidDate.HasValue))
Reasons.Add("Accounting Charge Required But Not Added Or Paid"); // Accounting Charge Required, but not added or paid
else if (j.JobMetaNonWarranty.AccountingChargeRequiredDate.HasValue && !j.JobMetaNonWarranty.AccountingChargeAddedDate.HasValue)
Reasons.Add("Accounting Charge Required But Not Added"); // Accounting Charge Required, but not added
else if (j.JobMetaNonWarranty.AccountingChargeAddedDate.HasValue && !j.JobMetaNonWarranty.AccountingChargePaidDate.HasValue)
Reasons.Add("Accounting Charge Added But Not Paid"); // Accounting Charge Added, but not paid
else if (j.JobMetaNonWarranty.AccountingChargeRequiredDate.HasValue && !j.JobMetaNonWarranty.AccountingChargePaidDate.HasValue)
Reasons.Add("Accounting Charge Required But Not Paid"); // Accounting Charge Required, but not paid
if (j.JobMetaNonWarranty.IsInsuranceClaim && !j.JobMetaInsurance.ClaimFormSentDate.HasValue)
Reasons.Add("Insurance Claim Form Not Sent"); // Is Insurance Claim, but claim form not sent
break;
}
return (Reasons.Count > 0);
}
public static void OnCloseForced(this Job j, DiscoDataContext Database, User Technician, string Reason)
{
if (!j.CanCloseForced())
throw new InvalidOperationException("Force Close was Denied");
// Write Log
JobLog jobLog = new JobLog()
{
JobId = j.Id,
TechUserId = Technician.UserId,
Timestamp = DateTime.Now,
Comments = string.Format("# Job Forcibly Closed\r\n{0}", string.IsNullOrWhiteSpace(Reason) ? "<no reason provided>" : Reason)
};
Database.JobLogs.Add(jobLog);
j.ClosedDate = DateTime.Now;
j.ClosedTechUserId = Technician.UserId;
}
#endregion
#region Reopen
public static bool CanReopen(this Job j)
{
if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.Reopen))
return false;
return j.ClosedDate.HasValue;
}
public static void OnReopen(this Job j)
{
if (!j.CanReopen())
throw new InvalidOperationException("Reopen was Denied");
j.ClosedDate = null;
j.ClosedTechUserId = null;
}
#endregion
#region Delete
public static bool CanDelete(this Job j)
{
if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.Delete))
return false;
return j.ClosedDate.HasValue;
}
public static void OnDelete(this Job j, DiscoDataContext Database)
{
// Job Sub Types
j.JobSubTypes.Clear();
// Job Attachments
foreach (var ja in j.JobAttachments.ToArray())
ja.OnDelete(Database);
j.JobAttachments.Clear();
// Job Components
foreach (var jc in j.JobComponents.ToArray())
Database.JobComponents.Remove(jc);
j.JobComponents.Clear();
// Job Queue Jobs
foreach (var jqj in j.JobQueues.ToArray())
Database.JobQueueJobs.Remove(jqj);
j.JobQueues.Clear();
// Job Logs
foreach (var jl in j.JobLogs.ToArray())
Database.JobLogs.Remove(jl);
j.JobLogs.Clear();
// Job Meta
if (j.JobMetaInsurance != null)
{
Database.JobMetaInsurances.Remove(j.JobMetaInsurance);
j.JobMetaInsurance = null;
}
if (j.JobMetaNonWarranty != null)
{
Database.JobMetaNonWarranties.Remove(j.JobMetaNonWarranty);
j.JobMetaNonWarranty = null;
}
if (j.JobMetaWarranty != null)
{
Database.JobMetaWarranties.Remove(j.JobMetaWarranty);
j.JobMetaWarranty = null;
}
// Job
Database.Jobs.Remove(j);
}
#endregion
}
}
-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;
}
}
}
@@ -1,80 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Disco.Models.Repository;
using System.ComponentModel.DataAnnotations;
namespace Disco.BI.Extensions
{
public static class JobFlagExtensions
{
private static Dictionary<string, Dictionary<long, string>> allFlags;
private static void CacheAllFlags()
{
if (allFlags == null)
{
var fType = typeof(Job.UserManagementFlags);
var fMembers = fType.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
var flags = new Dictionary<string, Dictionary<long, string>>();
foreach (var f in fMembers)
{
DisplayAttribute display = (DisplayAttribute)(f.GetCustomAttributes(typeof(DisplayAttribute), false)[0]);
string gn = display.GroupName;
Dictionary<long, string> g;
if (!flags.TryGetValue(gn, out g))
{
g = new Dictionary<long, string>();
flags.Add(gn, g);
}
g[(long)f.GetRawConstantValue()] = display.Name;
}
allFlags = flags;
}
}
public static Dictionary<string, List<Tuple<long, string, bool>>> ValidFlagsGrouped(this Job j)
{
Dictionary<string, List<Tuple<long, string, bool>>> validFlags = new Dictionary<string, List<Tuple<long, string, bool>>>();
CacheAllFlags();
var currentFlags = (long)(j.Flags ?? 0);
foreach (var jt in j.JobSubTypes)
{
Dictionary<long, string> g;
if (allFlags.TryGetValue(jt.Id, out g))
{
validFlags[jt.Id] = g.Select(f => new Tuple<long, string, bool>(f.Key, f.Value, ((currentFlags & f.Key) == f.Key))).ToList();
}
else
{
validFlags[jt.Id] = null;
}
}
return validFlags;
}
public static Dictionary<long, Tuple<string, bool>> ValidFlags(this Job j)
{
Dictionary<long, Tuple<string, bool>> validFlags = new Dictionary<long, Tuple<string, bool>>();
CacheAllFlags();
var currentFlags = (long)(j.Flags ?? 0);
foreach (var jt in j.JobSubTypes)
{
Dictionary<long, string> g;
if (allFlags.TryGetValue(jt.Id, out g))
{
foreach (var f in g)
validFlags[f.Key] = new Tuple<string, bool>(string.Format("{0}: {1}", jt.Description, f.Value), ((currentFlags & f.Key) == f.Key));
}
}
return validFlags;
}
}
}
@@ -1,213 +0,0 @@
using Disco.Data.Repository;
using Disco.Models.Repository;
using Disco.Services.Authorization;
using Disco.Services.Jobs.JobQueues;
using Disco.Services.Users;
using System;
using System.Linq;
namespace Disco.BI.Extensions
{
public static class JobQueueActionExtensions
{
#region Edit Sla
public static bool CanEditSla(this JobQueueJob jqj)
{
if (jqj.RemovedDate.HasValue)
return false;
if (UserService.CurrentAuthorization.Has(Claims.Job.Properties.JobQueueProperties.EditAnySLA))
{
// Can edit ANY queue
return true;
}
else if (UserService.CurrentAuthorization.Has(Claims.Job.Properties.JobQueueProperties.EditOwnSLA))
{
// Can edit from OWN queue
return JobQueueService.UsersQueues(UserService.CurrentUser).Any(q => q.JobQueue.Id == jqj.JobQueueId);
}
else
{
return false;
}
}
public static void OnEditSla(this JobQueueJob jqj, DateTime? SlaExpiresDate)
{
if (!jqj.CanEditSla())
throw new InvalidOperationException("Editing job SLA for this queue is denied");
if (SlaExpiresDate.HasValue && jqj.AddedDate > SlaExpiresDate.Value)
throw new ArgumentException("The SLA Expires Date must be greater than the Added Date", "SLAExpiresDate");
jqj.SLAExpiresDate = SlaExpiresDate;
}
#endregion
#region Edit Priority
public static bool CanEditPriority(this JobQueueJob jqj)
{
if (jqj.RemovedDate.HasValue)
return false;
if (UserService.CurrentAuthorization.Has(Claims.Job.Properties.JobQueueProperties.EditAnyPriority))
{
// Can edit ANY queue
return true;
}
else if (UserService.CurrentAuthorization.Has(Claims.Job.Properties.JobQueueProperties.EditOwnPriority))
{
// Can edit from OWN queue
return JobQueueService.UsersQueues(UserService.CurrentUser).Any(q => q.JobQueue.Id == jqj.JobQueueId);
}
else
{
return false;
}
}
public static void OnEditPriority(this JobQueueJob jqj, JobQueuePriority Priority)
{
if (!jqj.CanEditPriority())
throw new InvalidOperationException("Editing job priority for this queue is denied");
jqj.Priority = Priority;
}
#endregion
#region Edit Comments
private static bool CanEditComments(this JobQueueJob jqj)
{
if (UserService.CurrentAuthorization.Has(Claims.Job.Properties.JobQueueProperties.EditAnyComments))
{
// Can edit ANY queue
return true;
}
else if (UserService.CurrentAuthorization.Has(Claims.Job.Properties.JobQueueProperties.EditOwnComments))
{
// Can edit from OWN queue
return JobQueueService.UsersQueues(UserService.CurrentUser).Any(q => q.JobQueue.Id == jqj.JobQueueId);
}
else
{
return false;
}
}
public static bool CanEditAddedComment(this JobQueueJob jqj)
{
return jqj.CanEditComments();
}
public static bool CanEditRemovedComment(this JobQueueJob jqj)
{
if (!jqj.RemovedDate.HasValue)
return false;
return jqj.CanEditComments();
}
public static void OnEditAddedComment(this JobQueueJob jqj, string AddedComment)
{
if (!jqj.CanEditAddedComment())
throw new InvalidOperationException("Editing job added comments for this queue is denied");
jqj.AddedComment = string.IsNullOrWhiteSpace(AddedComment) ? null : AddedComment.Trim();
}
public static void OnEditRemovedComment(this JobQueueJob jqj, string RemovedComment)
{
if (!jqj.CanEditRemovedComment())
throw new InvalidOperationException("Editing job removed comments for this queue is denied");
jqj.RemovedComment = string.IsNullOrWhiteSpace(RemovedComment) ? null : RemovedComment.Trim();
}
#endregion
#region Remove
public static bool CanRemove(this JobQueueJob jqj)
{
if (jqj.RemovedDate.HasValue)
return false;
if (UserService.CurrentAuthorization.Has(Claims.Job.Actions.RemoveAnyQueues))
{
// Can remove from ANY queue
return true;
}
else if (UserService.CurrentAuthorization.Has(Claims.Job.Actions.RemoveOwnQueues))
{
// Can remove from OWN queue
return JobQueueService.UsersQueues(UserService.CurrentUser).Any(q => q.JobQueue.Id == jqj.JobQueueId);
}
else
{
return false;
}
}
public static void OnRemove(this JobQueueJob jqj, User Technician, string Comment)
{
if (!jqj.CanRemove())
throw new InvalidOperationException("Removing job from queue is denied");
jqj.RemovedDate = DateTime.Now;
jqj.RemovedUserId = Technician.UserId;
jqj.RemovedComment = string.IsNullOrWhiteSpace(Comment) ? null : Comment.Trim();
}
#endregion
#region Add
public static bool CanAddQueues(this Job j)
{
// Job Closed?
if (j.ClosedDate.HasValue)
return false;
if (UserService.CurrentAuthorization.HasAny(Claims.Job.Actions.AddAnyQueues, Claims.Job.Actions.AddOwnQueues))
return true;
return false;
}
public static bool CanAddQueue(this Job j, JobQueue jq)
{
// Shortcut
if (!j.CanAddQueues())
return false;
// Already in Queue?
if (j.JobQueues.Any(jjq => !jjq.RemovedDate.HasValue && jjq.JobQueueId == jq.Id))
return false;
// Can add ANY queue
if (UserService.CurrentAuthorization.Has(Claims.Job.Actions.AddAnyQueues))
return true;
// Can add OWN queue
if (UserService.CurrentAuthorization.Has(Claims.Job.Actions.AddOwnQueues))
{
return JobQueueService.UsersQueues(UserService.CurrentUser).Any(q => q.JobQueue.Id == jq.Id);
}
return false;
}
public static JobQueueJob OnAddQueue(this Job j, DiscoDataContext Database, JobQueue jq, User Technician, string Comment, DateTime? SLAExpires, JobQueuePriority Priority)
{
if (!j.CanAddQueue(jq))
throw new InvalidOperationException("Adding job to queue is denied");
if (SLAExpires.HasValue && SLAExpires.Value < DateTime.Now)
throw new ArgumentException("The SLA Date must be greater than the current time", "SLAExpires");
var jqj = new JobQueueJob()
{
JobQueueId = jq.Id,
JobId = j.Id,
AddedDate = DateTime.Now,
AddedUserId = Technician.UserId,
AddedComment = string.IsNullOrWhiteSpace(Comment) ? null : Comment.Trim(),
SLAExpiresDate = SLAExpires,
Priority = Priority
};
Database.JobQueueJobs.Add(jqj);
return jqj;
}
#endregion
}
}
-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,85 +0,0 @@
using Disco.Data.Repository;
using Disco.Models.Repository;
using Disco.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
{
public static class UserFlagActionExtensions
{
#region Edit Comments
public static bool CanEditComments(this UserFlagAssignment fa)
{
return UserService.CurrentAuthorization.Has(Claims.User.Actions.EditFlags);
}
public static void OnEditComments(this UserFlagAssignment fa, string Comments)
{
if (!fa.CanEditComments())
throw new InvalidOperationException("Editing comments for user flags is denied");
fa.Comments = string.IsNullOrWhiteSpace(Comments) ? null : Comments.Trim();
}
#endregion
#region Remove
public static bool CanRemove(this UserFlagAssignment fa)
{
if (fa.RemovedDate.HasValue)
return false;
return UserService.CurrentAuthorization.Has(Claims.User.Actions.RemoveFlags);
}
public static void OnRemove(this UserFlagAssignment fa, User Technician)
{
if (!fa.CanRemove())
throw new InvalidOperationException("Removing user flags is denied");
fa.RemovedDate = DateTime.Now;
fa.RemovedUserId = Technician.UserId;
}
#endregion
#region Add
public static bool CanAddUserFlags(this User u)
{
return UserService.CurrentAuthorization.Has(Claims.User.Actions.AddFlags);
}
public static bool CanAddUserFlag(this User u, UserFlag flag)
{
// Shortcut
if (!u.CanAddUserFlags())
return false;
// Already has User Flag?
if (u.UserFlagAssignments.Any(fa => !fa.RemovedDate.HasValue && fa.UserFlagId == flag.Id))
return false;
return true;
}
public static UserFlagAssignment OnAddUserFlag(this User u, DiscoDataContext Database, UserFlag flag, User Technician, string Comments)
{
if (!u.CanAddUserFlag(flag))
throw new InvalidOperationException("Adding user flag is denied");
var fa = new UserFlagAssignment()
{
UserFlagId = flag.Id,
UserId = u.UserId,
AddedDate = DateTime.Now,
AddedUserId = Technician.UserId,
Comments = string.IsNullOrWhiteSpace(Comments) ? null : Comments.Trim()
};
Database.UserFlagAssignments.Add(fa);
return fa;
}
#endregion
}
}
@@ -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;
}
}
}