Permissions & Authorization for Users #24

Initial Release; Includes Database and MVC refactoring
This commit is contained in:
Gary Sharp
2013-10-10 19:13:16 +11:00
parent 172ce5524a
commit a099d68915
458 changed files with 40221 additions and 12130 deletions
@@ -0,0 +1,233 @@
using Disco.BI.Extensions;
using Disco.BI.Interop.ActiveDirectory;
using Disco.Models.Interop.ActiveDirectory;
using Disco.Models.Repository;
using Disco.Services.Authorization;
using Disco.Services.Users;
using Disco.Services.Web;
using System;
using System.Linq;
using System.Web.Mvc;
namespace Disco.Web.Areas.API.Controllers
{
[DiscoAuthorize(Claims.DiscoAdminAccount)]
public partial class AuthorizationRoleController : AuthorizedDatabaseController
{
#region Properties
const string pName = "name";
public virtual ActionResult Update(int id, string key, string value = null, bool redirect = false)
{
try
{
if (id < 0)
throw new ArgumentOutOfRangeException("id");
if (string.IsNullOrEmpty(key))
throw new ArgumentNullException("key");
var authorizationRole = Database.AuthorizationRoles.Find(id);
if (authorizationRole != null)
{
switch (key.ToLower())
{
case pName:
UpdateName(authorizationRole, value);
break;
default:
throw new Exception("Invalid Update Key");
}
}
else
{
return Json("Invalid Authorization Role Id", JsonRequestBehavior.AllowGet);
}
if (redirect)
return RedirectToAction(MVC.Config.AuthorizationRole.Index(authorizationRole.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet);
}
}
private void UpdateName(AuthorizationRole AuthorizationRole, string Name)
{
if (string.IsNullOrWhiteSpace(Name))
throw new ArgumentNullException("Name", "Authorization Role Name is required");
else
{
if (AuthorizationRole.Name != Name)
{
// Check for Duplicates
var d = Database.AuthorizationRoles.Where(db => db.Id != AuthorizationRole.Id && db.Name == Name).Count();
if (d > 0)
{
throw new Exception("An Authorization Role with that name already exists");
}
AuthorizationRole.Name = Name;
UserService.UpdateAuthorizationRole(Database, AuthorizationRole);
}
}
}
private void UpdateClaims(AuthorizationRole AuthorizationRole, string[] ClaimKeys)
{
var claims = Claims.BuildClaims(ClaimKeys);
AuthorizationRole.SetClaims(claims);
UserService.UpdateAuthorizationRole(Database, AuthorizationRole);
}
private void UpdateSubjects(AuthorizationRole AuthorizationRole, string[] Subjects)
{
string subjectIds = null;
// Validate Subjects
if (Subjects != null && Subjects.Length > 0)
{
var subjects = Subjects.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.Trim()).Select(s => new Tuple<string, IActiveDirectoryObject>(s, ActiveDirectory.GetObject(s))).ToList();
var invalidSubjects = subjects.Where(s => s.Item2 == null).ToList();
if (invalidSubjects.Count > 0)
throw new ArgumentException(string.Format("Subjects not found: {0}", string.Join(", ", invalidSubjects)), "Subjects");
subjectIds = string.Join(",", subjects.Select(s => s.Item2.SamAccountName).OrderBy(s => s));
if (string.IsNullOrEmpty(subjectIds))
subjectIds = null;
}
if (AuthorizationRole.SubjectIds != subjectIds)
{
AuthorizationRole.SubjectIds = subjectIds;
UserService.UpdateAuthorizationRole(Database, AuthorizationRole);
}
}
public virtual ActionResult UpdateName(int id, string RoleName = null, bool redirect = false)
{
return Update(id, pName, RoleName, redirect);
}
public virtual ActionResult UpdateClaims(int id, string[] ClaimKeys = null, bool redirect = false)
{
try
{
if (id < 0)
throw new ArgumentOutOfRangeException("id");
var authorizationRole = Database.AuthorizationRoles.Find(id);
if (authorizationRole != null)
{
UpdateClaims(authorizationRole, ClaimKeys);
}
else
{
return Json("Invalid Authorization Role Id", JsonRequestBehavior.AllowGet);
}
if (redirect)
return RedirectToAction(MVC.Config.AuthorizationRole.Index(authorizationRole.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet);
}
}
public virtual ActionResult UpdateSubjects(int id, string[] Subjects = null, bool redirect = false)
{
try
{
if (id < 0)
throw new ArgumentOutOfRangeException("id");
var authorizationRole = Database.AuthorizationRoles.Find(id);
if (authorizationRole != null)
{
UpdateSubjects(authorizationRole, Subjects);
}
else
{
return Json("Invalid Authorization Role Id", JsonRequestBehavior.AllowGet);
}
if (redirect)
return RedirectToAction(MVC.Config.AuthorizationRole.Index(authorizationRole.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet);
}
}
#endregion
#region Actions
public virtual ActionResult Delete(int id, Nullable<bool> redirect = false)
{
try
{
var ar = Database.AuthorizationRoles.Find(id);
if (ar != null)
{
ar.Delete(Database);
Database.SaveChanges();
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Config.AuthorizationRole.Index(null));
else
return Json("OK", JsonRequestBehavior.AllowGet);
}
throw new Exception("Invalid Authorization Role Id");
}
catch (Exception ex)
{
if (redirect.HasValue && redirect.Value)
throw;
else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet);
}
}
#endregion
public virtual ActionResult SearchSubjects(string term)
{
var groupResults = BI.Interop.ActiveDirectory.ActiveDirectory.SearchGroups(term).Cast<IActiveDirectoryObject>();
var userResults = BI.Interop.ActiveDirectory.ActiveDirectory.SearchUsers(term).Cast<IActiveDirectoryObject>();
var results = groupResults.Concat(userResults).OrderBy(r => r.SamAccountName)
.Select(r => Models.AuthorizationRole.SubjectItem.FromActiveDirectoryObject(r)).ToList();
return Json(results, JsonRequestBehavior.AllowGet);
}
public virtual ActionResult Subject(string Id)
{
var subject = ActiveDirectory.GetObject(Id);
if (subject == null || !(subject is ActiveDirectoryUserAccount || subject is ActiveDirectoryGroup))
return Json(null, JsonRequestBehavior.AllowGet);
else
return Json(Models.AuthorizationRole.SubjectItem.FromActiveDirectoryObject(subject), JsonRequestBehavior.AllowGet);
}
}
}
@@ -1,23 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Disco.Services.Authorization;
using Disco.Services.Web;
using System;
using System.Web.Mvc;
using Disco.BI.Extensions;
namespace Disco.Web.Areas.API.Controllers
{
public partial class BootstrapperController : dbAdminController
[DiscoAuthorize(Claims.Config.Enrolment.Configure)]
public partial class BootstrapperController : AuthorizedDatabaseController
{
public virtual ActionResult MacSshUsername(string MacSshUsername)
{
try
{
if (!string.IsNullOrWhiteSpace(MacSshUsername))
{
dbContext.DiscoConfiguration.Bootstrapper.MacSshUsername = MacSshUsername;
dbContext.SaveChanges();
Database.DiscoConfiguration.Bootstrapper.MacSshUsername = MacSshUsername;
Database.SaveChanges();
return Json("OK", JsonRequestBehavior.AllowGet);
}
else
@@ -36,8 +34,8 @@ namespace Disco.Web.Areas.API.Controllers
{
if (!string.IsNullOrWhiteSpace(MacSshPassword))
{
dbContext.DiscoConfiguration.Bootstrapper.MacSshPassword = MacSshPassword;
dbContext.SaveChanges();
Database.DiscoConfiguration.Bootstrapper.MacSshPassword = MacSshPassword;
Database.SaveChanges();
return Json("OK", JsonRequestBehavior.AllowGet);
}
else
@@ -1,19 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Disco.BI;
using Disco.BI.Extensions;
using Disco.BI.Extensions;
using Disco.Models.Repository;
using Disco.Services.Authorization;
using Disco.Services.Web;
using Disco.Web.Extensions;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web.Mvc;
namespace Disco.Web.Areas.API.Controllers
{
public partial class DeviceBatchController : dbAdminController
public partial class DeviceBatchController : AuthorizedDatabaseController
{
const string pName = "name";
const string pPurchaseDate = "purchasedate";
const string pSupplier = "supplier";
@@ -29,15 +28,18 @@ namespace Disco.Web.Areas.API.Controllers
const string pInsuranceDetails = "insurancedetails";
const string pComments = "comments";
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
public virtual ActionResult Update(int id, string key, string value = null, bool redirect = false)
{
Authorization.Require(Claims.Config.DeviceBatch.Configure);
try
{
if (id < 0)
throw new ArgumentOutOfRangeException("id");
if (string.IsNullOrEmpty(key))
throw new ArgumentNullException("key");
var deviceBatch = dbContext.DeviceBatches.Find(id);
var deviceBatch = Database.DeviceBatches.Find(id);
if (deviceBatch != null)
{
switch (key.ToLower())
@@ -107,62 +109,86 @@ namespace Disco.Web.Areas.API.Controllers
}
#region Update Shortcut Methods
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
public virtual ActionResult UpdateName(int id, string BatchName = null, bool redirect = false)
{
return Update(id, pName, BatchName, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
public virtual ActionResult UpdatePurchaseDate(int id, string PurchaseDate = null, bool redirect = false)
{
return Update(id, pPurchaseDate, PurchaseDate, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
public virtual ActionResult UpdateSupplier(int id, string Supplier = null, bool redirect = false)
{
return Update(id, pSupplier, Supplier, redirect);
}
[ValidateInput(false)]
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure), ValidateInput(false)]
public virtual ActionResult UpdatePurchaseDetails(int id, string PurchaseDetails = null, bool redirect = false)
{
return Update(id, pPurchaseDetails, PurchaseDetails, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
public virtual ActionResult UpdateUnitCost(int id, string UnitCost = null, bool redirect = false)
{
return Update(id, pUnitCost, UnitCost, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
public virtual ActionResult UpdateUnitQuantity(int id, string UnitQuantity = null, bool redirect = false)
{
return Update(id, pUnitQuantity, UnitQuantity, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
public virtual ActionResult UpdateDefaultDeviceModelId(int id, string DefaultDeviceModelId = null, bool redirect = false)
{
return Update(id, pDefaultDeviceModelId, DefaultDeviceModelId, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
public virtual ActionResult UpdateWarrantyValidUntil(int id, string WarrantyValidUntil = null, bool redirect = false)
{
return Update(id, pWarrantyValidUntil, WarrantyValidUntil, redirect);
}
[ValidateInput(false)]
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure), ValidateInput(false)]
public virtual ActionResult UpdateWarrantyDetails(int id, string WarrantyDetails = null, bool redirect = false)
{
return Update(id, pWarrantyDetails, WarrantyDetails, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
public virtual ActionResult UpdateInsuredDate(int id, string InsuredDate = null, bool redirect = false)
{
return Update(id, pInsuredDate, InsuredDate, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
public virtual ActionResult UpdateInsuranceSupplier(int id, string InsuranceSupplier = null, bool redirect = false)
{
return Update(id, pInsuranceSupplier, InsuranceSupplier, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
public virtual ActionResult UpdateInsuredUntil(int id, string InsuredUntil = null, bool redirect = false)
{
return Update(id, pInsuredUntil, InsuredUntil, redirect);
}
[ValidateInput(false)]
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure), ValidateInput(false)]
public virtual ActionResult UpdateInsuranceDetails(int id, string InsuranceDetails = null, bool redirect = false)
{
return Update(id, pInsuranceDetails, InsuranceDetails, redirect);
}
[ValidateInput(false)]
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure), ValidateInput(false)]
public virtual ActionResult UpdateComments(int id, string Comments = null, bool redirect = false)
{
return Update(id, pComments, Comments, redirect);
@@ -177,14 +203,14 @@ namespace Disco.Web.Areas.API.Controllers
else
{
// Check for Duplicates
var d = dbContext.DeviceBatches.Where(db => db.Id != deviceBatch.Id && db.Name == Name).Count();
var d = Database.DeviceBatches.Where(db => db.Id != deviceBatch.Id && db.Name == Name).Count();
if (d > 0)
{
throw new Exception("A Device Batch with that name already exists");
}
deviceBatch.Name = Name;
}
dbContext.SaveChanges();
Database.SaveChanges();
}
private void UpdatePurchaseDate(DeviceBatch deviceBatch, string PurchaseDate)
{
@@ -202,7 +228,7 @@ namespace Disco.Web.Areas.API.Controllers
throw new Exception("Invalid Date Format");
}
}
dbContext.SaveChanges();
Database.SaveChanges();
}
private void UpdateSupplier(DeviceBatch deviceBatch, string Supplier)
{
@@ -210,7 +236,7 @@ namespace Disco.Web.Areas.API.Controllers
deviceBatch.Supplier = null;
else
deviceBatch.Supplier = Supplier;
dbContext.SaveChanges();
Database.SaveChanges();
}
private void UpdatePurchaseDetails(DeviceBatch deviceBatch, string PurchaseDetails)
{
@@ -218,7 +244,7 @@ namespace Disco.Web.Areas.API.Controllers
deviceBatch.PurchaseDetails = null;
else
deviceBatch.PurchaseDetails = PurchaseDetails;
dbContext.SaveChanges();
Database.SaveChanges();
}
private void UpdateUnitCost(DeviceBatch deviceBatch, string UnitCost)
{
@@ -236,7 +262,7 @@ namespace Disco.Web.Areas.API.Controllers
throw new Exception("Invalid Currency Format");
}
}
dbContext.SaveChanges();
Database.SaveChanges();
}
private void UpdateUnitQuantity(DeviceBatch deviceBatch, string UnitQuantity)
{
@@ -254,7 +280,7 @@ namespace Disco.Web.Areas.API.Controllers
throw new Exception("Invalid Number");
}
}
dbContext.SaveChanges();
Database.SaveChanges();
}
private void UpdateDefaultDeviceModelId(DeviceBatch deviceBatch, string DefaultDeviceModelId)
{
@@ -263,13 +289,13 @@ namespace Disco.Web.Areas.API.Controllers
int bId;
if (int.TryParse(DefaultDeviceModelId, out bId))
{
var dm = dbContext.DeviceModels.Find(bId);
var dm = Database.DeviceModels.Find(bId);
if (dm != null)
{
deviceBatch.DefaultDeviceModelId = dm.Id;
deviceBatch.DefaultDeviceModel = dm;
dbContext.SaveChanges();
Database.SaveChanges();
return;
}
}
@@ -280,7 +306,7 @@ namespace Disco.Web.Areas.API.Controllers
deviceBatch.DefaultDeviceModelId = null;
deviceBatch.DefaultDeviceModel = null;
dbContext.SaveChanges();
Database.SaveChanges();
return;
}
throw new Exception("Invalid Device Model Id");
@@ -301,7 +327,7 @@ namespace Disco.Web.Areas.API.Controllers
throw new Exception("Invalid Date Format");
}
}
dbContext.SaveChanges();
Database.SaveChanges();
}
private void UpdateWarrantyDetails(DeviceBatch deviceBatch, string WarrantyDetails)
{
@@ -309,7 +335,7 @@ namespace Disco.Web.Areas.API.Controllers
deviceBatch.WarrantyDetails = null;
else
deviceBatch.WarrantyDetails = WarrantyDetails;
dbContext.SaveChanges();
Database.SaveChanges();
}
private void UpdateInsuredDate(DeviceBatch deviceBatch, string InsuredDate)
{
@@ -327,7 +353,7 @@ namespace Disco.Web.Areas.API.Controllers
throw new Exception("Invalid Date Format");
}
}
dbContext.SaveChanges();
Database.SaveChanges();
}
private void UpdateInsuranceSupplier(DeviceBatch deviceBatch, string InsuranceSupplier)
{
@@ -335,7 +361,7 @@ namespace Disco.Web.Areas.API.Controllers
deviceBatch.InsuranceSupplier = null;
else
deviceBatch.InsuranceSupplier = InsuranceSupplier;
dbContext.SaveChanges();
Database.SaveChanges();
}
private void UpdateInsuredUntil(DeviceBatch deviceBatch, string InsuredUntil)
{
@@ -353,7 +379,7 @@ namespace Disco.Web.Areas.API.Controllers
throw new Exception("Invalid Date Format");
}
}
dbContext.SaveChanges();
Database.SaveChanges();
}
private void UpdateInsuranceDetails(DeviceBatch deviceBatch, string InsuranceDetails)
{
@@ -361,7 +387,7 @@ namespace Disco.Web.Areas.API.Controllers
deviceBatch.InsuranceDetails = null;
else
deviceBatch.InsuranceDetails = InsuranceDetails;
dbContext.SaveChanges();
Database.SaveChanges();
}
private void UpdateComments(DeviceBatch deviceBatch, string Comments)
{
@@ -369,21 +395,22 @@ namespace Disco.Web.Areas.API.Controllers
deviceBatch.Comments = null;
else
deviceBatch.Comments = Comments;
dbContext.SaveChanges();
Database.SaveChanges();
}
#endregion
#region Actions
[DiscoAuthorize(Claims.Config.DeviceBatch.Delete)]
public virtual ActionResult Delete(int id, Nullable<bool> redirect = false)
{
try
{
var db = dbContext.DeviceBatches.Find(id);
var db = Database.DeviceBatches.Find(id);
if (db != null)
{
db.Delete(dbContext);
dbContext.SaveChanges();
db.Delete(Database);
Database.SaveChanges();
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Config.DeviceBatch.Index(null));
else
@@ -403,27 +430,32 @@ namespace Disco.Web.Areas.API.Controllers
#endregion
#region Index
[DiscoAuthorize(Claims.Config.DeviceBatch.Show)]
public virtual ActionResult Index(int? id)
{
if (id.HasValue)
{
dbContext.Configuration.ProxyCreationEnabled = false;
DeviceBatch deviceBatch = dbContext.DeviceBatches.FirstOrDefault(db => db.Id == id);
Database.Configuration.ProxyCreationEnabled = false;
DeviceBatch deviceBatch = Database.DeviceBatches.FirstOrDefault(db => db.Id == id);
return Json(deviceBatch, JsonRequestBehavior.AllowGet);
}
else
{
var deviceBatches = dbContext.DeviceBatches.ToArray();
var deviceBatches = Database.DeviceBatches.ToArray();
return Json(deviceBatches, JsonRequestBehavior.AllowGet);
}
}
#endregion
#region Timeline
[DiscoAuthorizeAll(Claims.Config.DeviceBatch.Show, Claims.Config.DeviceBatch.ShowTimeline)]
public virtual ActionResult Timeline()
{
var batchesInformation = dbContext.DeviceBatches.Select(db => new
var batchesInformation = Database.DeviceBatches.Select(db => new
{
Name = db.Name,
Comments = db.Comments,
@@ -466,13 +498,15 @@ namespace Disco.Web.Areas.API.Controllers
#endregion
#region Exporting
[DiscoAuthorizeAll(Claims.Config.DeviceBatch.Show, Claims.Device.Actions.Export)]
public virtual ActionResult ExportDevices(int id)
{
DeviceBatch db = dbContext.DeviceBatches.Find(id);
DeviceBatch db = Database.DeviceBatches.Find(id);
if (db == null)
throw new ArgumentNullException("id", "Invalid Device Batch Id");
var devices = dbContext.Devices.Where(d => !d.DecommissionedDate.HasValue && d.DeviceBatchId == db.Id);
var devices = Database.Devices.Where(d => !d.DecommissionedDate.HasValue && d.DeviceBatchId == db.Id);
var export = BI.DeviceBI.Importing.Export.GenerateExport(devices);
@@ -480,6 +514,7 @@ namespace Disco.Web.Areas.API.Controllers
return File(export, "text/csv", filename);
}
#endregion
}
@@ -1,17 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Disco.Services.Authorization;
using Disco.Services.Web;
using System;
using System.Web.Mvc;
namespace Disco.Web.Areas.API.Controllers
{
public partial class DeviceCertificateController : dbAdminController
public partial class DeviceCertificateController : AuthorizedDatabaseController
{
[DiscoAuthorize(Claims.Config.DeviceCertificate.DownloadCertificates)]
public virtual ActionResult Download(int id)
{
var wc = dbContext.DeviceCertificates.Find(id);
var wc = Database.DeviceCertificates.Find(id);
if (wc == null)
{
throw new Exception("Invalid Device Certificate Id");
@@ -1,16 +1,17 @@
using System;
using System.Collections.Generic;
using Disco.BI.Extensions;
using Disco.BI.Interop.ActiveDirectory;
using Disco.Services.Authorization;
using Disco.Services.Users;
using Disco.Services.Web;
using System;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Disco.BI.Extensions;
using Disco.BI;
using Disco.BI.Interop.ActiveDirectory;
using System.IO;
namespace Disco.Web.Areas.API.Controllers
{
public partial class DeviceController : dbAdminController
public partial class DeviceController : AuthorizedDatabaseController
{
const string pDeviceProfileId = "deviceprofileid";
@@ -22,7 +23,7 @@ namespace Disco.Web.Areas.API.Controllers
public virtual ActionResult Update(string id, string key, string value = null, bool redirect = false)
{
dbContext.Configuration.LazyLoadingEnabled = true;
Database.Configuration.LazyLoadingEnabled = true;
try
{
@@ -30,27 +31,33 @@ namespace Disco.Web.Areas.API.Controllers
throw new ArgumentNullException("id");
if (string.IsNullOrEmpty(key))
throw new ArgumentNullException("key");
var device = dbContext.Devices.Find(id);
var device = Database.Devices.Find(id);
if (device != null)
{
switch (key.ToLower())
{
case pDeviceProfileId:
Authorization.Require(Claims.Device.Properties.DeviceProfile);
UpdateDeviceProfileId(device, value);
break;
case pDeviceBatchId:
Authorization.Require(Claims.Device.Properties.DeviceBatch);
UpdateDeviceBatchId(device, value);
break;
case pAssetNumber:
Authorization.Require(Claims.Device.Properties.AssetNumber);
UpdateAssetNumber(device, value);
break;
case pAssignedUserId:
Authorization.Require(Claims.Device.Actions.AssignUser);
UpdateAssignedUserId(device, value);
break;
case pLocation:
Authorization.Require(Claims.Device.Properties.Location);
UpdateLocation(device, value);
break;
case pAllowUnauthenticatedEnrol:
Authorization.Require(Claims.Device.Actions.AllowUnauthenticatedEnrol);
UpdateAllowUnauthenticatedEnrol(device, value);
break;
default:
@@ -76,30 +83,43 @@ namespace Disco.Web.Areas.API.Controllers
}
#region Update Shortcut Methods
[DiscoAuthorize(Claims.Device.Properties.DeviceProfile)]
public virtual ActionResult UpdateDeviceProfileId(string id, string DeviceProfileId = null, bool redirect = false)
{
return Update(id, pDeviceProfileId, DeviceProfileId, redirect);
}
[DiscoAuthorize(Claims.Device.Properties.DeviceBatch)]
public virtual ActionResult UpdateDeviceBatchId(string id, string DeviceBatchId = null, bool redirect = false)
{
return Update(id, pDeviceBatchId, DeviceBatchId, redirect);
}
[DiscoAuthorize(Claims.Device.Properties.AssetNumber)]
public virtual ActionResult UpdateAssetNumber(string id, string AssetNumber = null, bool redirect = false)
{
return Update(id, pAssetNumber, AssetNumber, redirect);
}
[DiscoAuthorize(Claims.Device.Properties.Location)]
public virtual ActionResult UpdateLocation(string id, string Location = null, bool redirect = false)
{
return Update(id, pLocation, Location, redirect);
}
[DiscoAuthorize(Claims.Device.Actions.AssignUser)]
public virtual ActionResult UpdateAssignedUserId(string id, string AssignedUserId = null, bool redirect = false)
{
return Update(id, pAssignedUserId, AssignedUserId, redirect);
}
[DiscoAuthorize(Claims.Device.Actions.AllowUnauthenticatedEnrol)]
public virtual ActionResult UpdateAllowUnauthenticatedEnrol(string id, string AllowUnauthenticatedEnrol = null, bool redirect = false)
{
return Update(id, pAllowUnauthenticatedEnrol, AllowUnauthenticatedEnrol, redirect);
}
#endregion
#region Update Properties
@@ -110,7 +130,7 @@ namespace Disco.Web.Areas.API.Controllers
int pId;
if (int.TryParse(DeviceProfileId, out pId))
{
var p = dbContext.DeviceProfiles.Find(pId);
var p = Database.DeviceProfiles.Find(pId);
if (p != null)
{
device.DeviceProfileId = p.Id;
@@ -124,7 +144,7 @@ namespace Disco.Web.Areas.API.Controllers
adMachineAccount.SetDescription(device);
}
dbContext.SaveChanges();
Database.SaveChanges();
return;
}
}
@@ -138,13 +158,13 @@ namespace Disco.Web.Areas.API.Controllers
int bId;
if (int.TryParse(DeviceBatchId, out bId))
{
var b = dbContext.DeviceBatches.Find(bId);
var b = Database.DeviceBatches.Find(bId);
if (b != null)
{
device.DeviceBatchId = b.Id;
device.DeviceBatch = b;
dbContext.SaveChanges();
Database.SaveChanges();
return;
}
}
@@ -155,7 +175,7 @@ namespace Disco.Web.Areas.API.Controllers
device.DeviceBatchId = null;
device.DeviceBatch = null;
dbContext.SaveChanges();
Database.SaveChanges();
return;
}
throw new Exception("Invalid Device Batch Id");
@@ -166,7 +186,7 @@ namespace Disco.Web.Areas.API.Controllers
device.AssetNumber = null;
else
device.AssetNumber = AssetNumber.Trim();
dbContext.SaveChanges();
Database.SaveChanges();
}
private void UpdateLocation(Disco.Models.Repository.Device device, string Location)
{
@@ -174,27 +194,24 @@ namespace Disco.Web.Areas.API.Controllers
device.Location = null;
else
device.Location = Location.Trim();
dbContext.SaveChanges();
Database.SaveChanges();
}
private void UpdateAssignedUserId(Disco.Models.Repository.Device device, string UserId)
{
var daus = dbContext.DeviceUserAssignments.Where(m => m.DeviceSerialNumber == device.SerialNumber && m.UnassignedDate == null);
var daus = Database.DeviceUserAssignments.Where(m => m.DeviceSerialNumber == device.SerialNumber && m.UnassignedDate == null);
Disco.Models.Repository.User u = null;
if (!string.IsNullOrEmpty(UserId))
{
// Changed 2012-12-13 G# - Stop error when assigning user - Force Refresh
// http://www.discoict.com.au/forum/support/2012/11/error-when-assigning-multiple-devices-to-single-user.aspx
//u = BI.UserBI.UserCache.GetUser(UserId, dbContext);
u = BI.UserBI.UserCache.GetUser(UserId, dbContext, true);
// End Changed 2012-12-13 G#
UserService.GetUser(UserId, Database, true);
if (u == null)
{
throw new Exception("Invalid Username");
}
}
device.AssignDevice(dbContext, u);
dbContext.SaveChanges();
device.AssignDevice(Database, u);
Database.SaveChanges();
}
private void UpdateAllowUnauthenticatedEnrol(Disco.Models.Repository.Device device, string AllowUnauthenticatedEnrol)
{
@@ -207,23 +224,25 @@ namespace Disco.Web.Areas.API.Controllers
if (device.AllowUnauthenticatedEnrol != bAllowUnauthenticatedEnrol)
{
device.AllowUnauthenticatedEnrol = bAllowUnauthenticatedEnrol;
dbContext.SaveChanges();
Database.SaveChanges();
}
}
#endregion
#region Device Actions
[DiscoAuthorize(Claims.Device.Actions.Decommission)]
public virtual ActionResult Decommission(string id, int Reason, bool redirect)
{
var d = dbContext.Devices.Find(id);
dbContext.Configuration.LazyLoadingEnabled = true;
var d = Database.Devices.Find(id);
Database.Configuration.LazyLoadingEnabled = true;
if (d != null)
{
if (d.CanDecommission())
{
d.OnDecommission((Disco.Models.Repository.Device.DecommissionReasons)Reason);
dbContext.SaveChanges();
Database.SaveChanges();
if (redirect)
return RedirectToAction(MVC.Device.Show(id));
else
@@ -236,17 +255,19 @@ namespace Disco.Web.Areas.API.Controllers
}
return Json("Invalid Device Serial Number", JsonRequestBehavior.AllowGet);
}
[DiscoAuthorize(Claims.Device.Actions.Recommission)]
public virtual ActionResult Recommission(string id, bool redirect)
{
var d = dbContext.Devices.Find(id);
dbContext.Configuration.LazyLoadingEnabled = true;
var d = Database.Devices.Find(id);
Database.Configuration.LazyLoadingEnabled = true;
if (d != null)
{
if (d.CanRecommission())
{
d.OnRecommission();
dbContext.SaveChanges();
Database.SaveChanges();
if (redirect)
return RedirectToAction(MVC.Device.Show(id));
else
@@ -259,17 +280,19 @@ namespace Disco.Web.Areas.API.Controllers
}
return Json("Invalid Device Serial Number", JsonRequestBehavior.AllowGet);
}
[DiscoAuthorize(Claims.Device.Actions.Delete)]
public virtual ActionResult Delete(string id, bool redirect)
{
var j = dbContext.Devices.Find(id);
dbContext.Configuration.LazyLoadingEnabled = true;
var j = Database.Devices.Find(id);
Database.Configuration.LazyLoadingEnabled = true;
if (j != null)
{
if (j.CanDelete())
{
j.OnDelete(dbContext);
j.OnDelete(Database);
dbContext.SaveChanges();
Database.SaveChanges();
if (redirect)
return RedirectToAction(MVC.Device.Index());
else
@@ -282,26 +305,28 @@ namespace Disco.Web.Areas.API.Controllers
}
return Json("Invalid Device Serial Number", JsonRequestBehavior.AllowGet);
}
#endregion
[DiscoAuthorize(Claims.Device.Actions.GenerateDocuments)]
public virtual ActionResult GeneratePdf(string id, string DocumentTemplateId)
{
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException("id");
if (string.IsNullOrEmpty(DocumentTemplateId))
throw new ArgumentNullException("AttachmentTypeId");
var device = dbContext.Devices.Find(id);
var device = Database.Devices.Find(id);
if (device != null)
{
var documentTemplate = dbContext.DocumentTemplates.Find(DocumentTemplateId);
var documentTemplate = Database.DocumentTemplates.Find(DocumentTemplateId);
if (documentTemplate != null)
{
var timeStamp = DateTime.Now;
Stream pdf;
using (var generationState = Disco.Models.BI.DocumentTemplates.DocumentState.DefaultState()){
pdf = documentTemplate.GeneratePdf(dbContext, device, DiscoApplication.CurrentUser, timeStamp, generationState);
pdf = documentTemplate.GeneratePdf(Database, device, UserService.CurrentUser, timeStamp, generationState);
}
dbContext.SaveChanges();
Database.SaveChanges();
return File(pdf, "application/pdf", string.Format("{0}_{1}_{2:yyyyMMdd-HHmmss}.pdf", documentTemplate.Id, device.SerialNumber, timeStamp));
}
else
@@ -315,16 +340,17 @@ namespace Disco.Web.Areas.API.Controllers
}
}
[DiscoAuthorize(Claims.Device.Show)]
public virtual ActionResult LastNetworkLogonDate(string id)
{
var device = dbContext.Devices.Find(id);
var device = Database.Devices.Find(id);
if (device == null)
{
return HttpNotFound("Invalid Device Serial Number");
}
if (device.UpdateLastNetworkLogonDate())
dbContext.SaveChanges();
Database.SaveChanges();
var result = new
{
@@ -337,13 +363,14 @@ namespace Disco.Web.Areas.API.Controllers
}
#region Device Attachements
[OutputCache(Location = System.Web.UI.OutputCacheLocation.Client, Duration = 172800)]
[DiscoAuthorize(Claims.Device.ShowAttachments), OutputCache(Location = System.Web.UI.OutputCacheLocation.Client, Duration = 172800)]
public virtual ActionResult AttachmentDownload(int id)
{
var da = dbContext.DeviceAttachments.Find(id);
var da = Database.DeviceAttachments.Find(id);
if (da != null)
{
var filePath = da.RepositoryFilename(dbContext);
var filePath = da.RepositoryFilename(Database);
if (System.IO.File.Exists(filePath))
{
return File(filePath, da.MimeType, da.Filename);
@@ -355,13 +382,14 @@ namespace Disco.Web.Areas.API.Controllers
}
return HttpNotFound("Invalid Attachment Number");
}
[OutputCache(Location = System.Web.UI.OutputCacheLocation.Client, Duration = 172800)]
[DiscoAuthorize(Claims.Device.ShowAttachments), OutputCache(Location = System.Web.UI.OutputCacheLocation.Client, Duration = 172800)]
public virtual ActionResult AttachmentThumbnail(int id)
{
var da = dbContext.DeviceAttachments.Find(id);
var da = Database.DeviceAttachments.Find(id);
if (da != null)
{
var thumbPath = da.RepositoryThumbnailFilename(dbContext);
var thumbPath = da.RepositoryThumbnailFilename(Database);
if (System.IO.File.Exists(thumbPath))
{
if (thumbPath.EndsWith(".png", StringComparison.InvariantCultureIgnoreCase))
@@ -374,9 +402,11 @@ namespace Disco.Web.Areas.API.Controllers
}
return HttpNotFound("Invalid Attachment Number");
}
[DiscoAuthorize(Claims.Device.Actions.AddAttachments)]
public virtual ActionResult AttachmentUpload(string id, string Comments)
{
var d = dbContext.Devices.Find(id);
var d = Database.Devices.Find(id);
if (d != null)
{
if (Request.Files.Count > 0)
@@ -391,18 +421,18 @@ namespace Disco.Web.Areas.API.Controllers
var da = new Disco.Models.Repository.DeviceAttachment()
{
DeviceSerialNumber = d.SerialNumber,
TechUserId = DiscoApplication.CurrentUser.Id,
TechUserId = UserService.CurrentUserId,
Filename = file.FileName,
MimeType = contentType,
Timestamp = DateTime.Now,
Comments = Comments
};
dbContext.DeviceAttachments.Add(da);
dbContext.SaveChanges();
Database.DeviceAttachments.Add(da);
Database.SaveChanges();
da.SaveAttachment(dbContext, file.InputStream);
da.SaveAttachment(Database, file.InputStream);
da.GenerateThumbnail(dbContext);
da.GenerateThumbnail(Database);
return Json(da.Id, JsonRequestBehavior.AllowGet);
}
@@ -411,9 +441,11 @@ namespace Disco.Web.Areas.API.Controllers
}
throw new Exception("Invalid Device Serial Number");
}
[DiscoAuthorize(Claims.Device.ShowAttachments)]
public virtual ActionResult Attachment(int id)
{
var da = dbContext.DeviceAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault();
var da = Database.DeviceAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault();
if (da != null)
{
@@ -427,9 +459,11 @@ namespace Disco.Web.Areas.API.Controllers
}
return Json(new Models.Attachment.AttachmentModel() { Result = "Invalid Attachment Number" }, JsonRequestBehavior.AllowGet);
}
[DiscoAuthorize(Claims.Device.ShowAttachments)]
public virtual ActionResult Attachments(string id)
{
var d = dbContext.Devices.Include("DeviceAttachments.TechUser").Where(m => m.SerialNumber == id).FirstOrDefault();
var d = Database.Devices.Include("DeviceAttachments.TechUser").Where(m => m.SerialNumber == id).FirstOrDefault();
if (d != null)
{
var m = new Models.Attachment.AttachmentsModel()
@@ -442,22 +476,21 @@ namespace Disco.Web.Areas.API.Controllers
}
return Json(new Models.Attachment.AttachmentsModel() { Result = "Invalid Device Serial Number" }, JsonRequestBehavior.AllowGet);
}
[DiscoAuthorizeAny(Claims.Job.Actions.RemoveAnyAttachments, Claims.Job.Actions.RemoveOwnAttachments)]
public virtual ActionResult AttachmentRemove(int id)
{
var da = dbContext.DeviceAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault();
var da = Database.DeviceAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault();
if (da != null)
{
// 2012-02-17 G# Remove - 'Delete Own Comments' policy
//if (da.TechUserId == DiscoApplication.CurrentUser.Id)
//{
da.OnDelete(dbContext);
dbContext.SaveChanges();
if (da.TechUserId.Equals(CurrentUser.Id, StringComparison.InvariantCultureIgnoreCase))
Authorization.RequireAny(Claims.Device.Actions.RemoveAnyAttachments, Claims.Device.Actions.RemoveOwnAttachments);
else
Authorization.Require(Claims.Device.Actions.RemoveAnyAttachments);
da.OnDelete(Database);
Database.SaveChanges();
return Json("OK", JsonRequestBehavior.AllowGet);
//}
//else
//{
// return Json("You can only delete your own attachments.", JsonRequestBehavior.AllowGet);
//}
}
return Json("Invalid Attachment Number", JsonRequestBehavior.AllowGet);
}
@@ -465,6 +498,8 @@ namespace Disco.Web.Areas.API.Controllers
#endregion
#region Importing / Exporting
[DiscoAuthorize(Claims.Device.Actions.Import)]
public virtual ActionResult ImportParse(HttpPostedFileBase ImportFile)
{
if (ImportFile == null || ImportFile.ContentLength == 0)
@@ -481,6 +516,7 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(status.SessionId));
}
[DiscoAuthorize(Claims.Device.Actions.Import)]
public virtual ActionResult ImportProcess(string ParseTaskSessionKey)
{
if (string.IsNullOrWhiteSpace(ParseTaskSessionKey))
@@ -493,10 +529,11 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(status.SessionId));
}
[DiscoAuthorize(Claims.Device.Actions.Export)]
public virtual ActionResult ExportAllDevices()
{
// Non-Decommissioned Devices
var devices = dbContext.Devices.Where(d => !d.DecommissionedDate.HasValue);
var devices = Database.Devices.Where(d => !d.DecommissionedDate.HasValue);
var export = BI.DeviceBI.Importing.Export.GenerateExport(devices);
@@ -504,13 +541,14 @@ namespace Disco.Web.Areas.API.Controllers
return File(export, "text/csv", filename);
}
#endregion
[DiscoAuthorize(Claims.DiscoAdminAccount)]
public virtual ActionResult MigrateDeviceMacAddressesFromLog()
{
var taskStatus = Disco.BI.DeviceBI.Migration.LogMacAddressImporting.ScheduleImmediately();
return RedirectToAction(MVC.Config.Logging.TaskStatus(taskStatus.SessionId));
}
}
}
@@ -1,32 +1,36 @@
using System;
using Disco.BI.Extensions;
using Disco.Models.Repository;
using Disco.Services.Authorization;
using Disco.Services.Plugins;
using Disco.Services.Plugins.Features.WarrantyProvider;
using Disco.Services.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Disco.BI;
using Disco.BI.Extensions;
using Disco.Models.Repository;
using Disco.Services.Plugins;
using Disco.Services.Plugins.Features.WarrantyProvider;
namespace Disco.Web.Areas.API.Controllers
{
public partial class DeviceModelController : dbAdminController
public partial class DeviceModelController : AuthorizedDatabaseController
{
const string pDescription = "description";
const string pDefaultPurchaseDate = "defaultpurchasedate";
const string pDefaultWarrantyProvider = "defaultwarrantyprovider";
[DiscoAuthorize(Claims.Config.DeviceModel.Configure)]
public virtual ActionResult Update(int id, string key, string value = null, bool redirect = false)
{
Authorization.Require(Claims.Config.DeviceModel.Configure);
try
{
if (id < 0)
throw new ArgumentOutOfRangeException("id");
if (string.IsNullOrEmpty(key))
throw new ArgumentNullException("key");
var deviceModel = dbContext.DeviceModels.Find(id);
var deviceModel = Database.DeviceModels.Find(id);
if (deviceModel != null)
{
switch (key.ToLower())
@@ -63,18 +67,25 @@ namespace Disco.Web.Areas.API.Controllers
}
#region Update Shortcut Methods
[DiscoAuthorize(Claims.Config.DeviceModel.Configure)]
public virtual ActionResult UpdateDescription(int id, string Description = null, bool redirect = false)
{
return Update(id, pDescription, Description, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceModel.Configure)]
public virtual ActionResult UpdateDefaultPurchaseDate(int id, string DefaultPurchaseDate = null, bool redirect = false)
{
return Update(id, pDefaultPurchaseDate, DefaultPurchaseDate, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceModel.Configure)]
public virtual ActionResult UpdateDefaultWarrantyProvider(int id, string DefaultWarrantyProvider = null, bool redirect = false)
{
return Update(id, pDefaultWarrantyProvider, DefaultWarrantyProvider, redirect);
}
#endregion
#region Update Properties
@@ -84,7 +95,7 @@ namespace Disco.Web.Areas.API.Controllers
deviceModel.Description = null;
else
deviceModel.Description = Description;
dbContext.SaveChanges();
Database.SaveChanges();
}
private void UpdateDefaultPurchaseDate(Disco.Models.Repository.DeviceModel deviceModel, string DefaultPurchaseDate)
{
@@ -104,7 +115,7 @@ namespace Disco.Web.Areas.API.Controllers
throw new Exception("Invalid Date Format");
}
}
dbContext.SaveChanges();
Database.SaveChanges();
}
private void UpdateDefaultWarrantyProvider(Disco.Models.Repository.DeviceModel deviceModel, string DefaultWarrantyProvider)
{
@@ -118,7 +129,7 @@ namespace Disco.Web.Areas.API.Controllers
var WarrantyProvider = Plugins.GetPluginFeature(DefaultWarrantyProvider, typeof(WarrantyProviderFeature));
deviceModel.DefaultWarrantyProvider = WarrantyProvider.Id;
}
dbContext.SaveChanges();
Database.SaveChanges();
}
#endregion
@@ -128,7 +139,7 @@ namespace Disco.Web.Areas.API.Controllers
{
if (id.HasValue)
{
var m = dbContext.DeviceModels.Find(id.Value);
var m = Database.DeviceModels.Find(id.Value);
if (m != null)
{
// Try From DataStore
@@ -156,17 +167,18 @@ namespace Disco.Web.Areas.API.Controllers
}
return File(Links.ClientSource.Style.Images.DeviceTypes.Unknown_png, "image/png");
}
[HttpPost]
[DiscoAuthorize(Claims.Config.DeviceModel.Configure), HttpPost]
public virtual ActionResult Image(int id, bool redirect, HttpPostedFileBase Image)
{
if (Image != null && Image.ContentLength > 0)
{
var dm = dbContext.DeviceModels.Find(id);
var dm = Database.DeviceModels.Find(id);
if (dm != null)
{
if (dm.ImageImport(Image.InputStream))
{
dbContext.SaveChanges();
Database.SaveChanges();
if (redirect)
return RedirectToAction(MVC.Config.DeviceModel.Index(dm.Id));
else
@@ -194,15 +206,16 @@ namespace Disco.Web.Areas.API.Controllers
#region Actions
[DiscoAuthorize(Claims.Config.DeviceModel.Delete)]
public virtual ActionResult Delete(int id, Nullable<bool> redirect = false)
{
try
{
var dm = dbContext.DeviceModels.Find(id);
var dm = Database.DeviceModels.Find(id);
if (dm != null)
{
dm.Delete(dbContext);
dbContext.SaveChanges();
dm.Delete(Database);
Database.SaveChanges();
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Config.DeviceModel.Index(null));
else
@@ -223,9 +236,10 @@ namespace Disco.Web.Areas.API.Controllers
#region Device Model Components
[DiscoAuthorize(Claims.Config.DeviceModel.Show)]
public virtual ActionResult Component(int id)
{
var dc = dbContext.DeviceComponents.Include("JobSubTypes").Where(i => i.Id == id).FirstOrDefault();
var dc = Database.DeviceComponents.Include("JobSubTypes").Where(i => i.Id == id).FirstOrDefault();
if (dc != null)
{
return Json(new Models.DeviceModel.ComponentModel { Result = "OK", Component = Models.DeviceModel._ComponentModel.FromDeviceComponent(dc) }, JsonRequestBehavior.AllowGet);
@@ -233,12 +247,13 @@ namespace Disco.Web.Areas.API.Controllers
return Json(new Models.DeviceModel.ComponentModel { Result = "Invalid Device Component Id" }, JsonRequestBehavior.AllowGet);
}
[DiscoAuthorize(Claims.Config.DeviceModel.ConfigureComponents)]
public virtual ActionResult ComponentAdd(int? id, string Description, string Cost)
{
DeviceModel dm = null;
if (id.HasValue)
{
dm = dbContext.DeviceModels.Find(id.Value);
dm = Database.DeviceModels.Find(id.Value);
if (dm == null)
{
return Json(new Models.DeviceModel.ComponentModel { Result = "Invalid Device Model Id" }, JsonRequestBehavior.AllowGet);
@@ -263,36 +278,40 @@ namespace Disco.Web.Areas.API.Controllers
}
dc.JobSubTypes = new List<JobSubType>();
dbContext.DeviceComponents.Add(dc);
dbContext.SaveChanges();
Database.DeviceComponents.Add(dc);
Database.SaveChanges();
return Json(new Models.DeviceModel.ComponentModel { Result = "OK", Component = Models.DeviceModel._ComponentModel.FromDeviceComponent(dc) }, JsonRequestBehavior.AllowGet);
}
[DiscoAuthorize(Claims.Config.DeviceModel.ConfigureComponents)]
public virtual ActionResult ComponentUpdateJobSubTypes(int id, List<string> JobSubTypes)
{
var dc = dbContext.DeviceComponents.Include("JobSubTypes").Where(i => i.Id == id).FirstOrDefault();
var dc = Database.DeviceComponents.Include("JobSubTypes").Where(i => i.Id == id).FirstOrDefault();
if (dc != null)
{
dc.JobSubTypes.Clear();
if (JobSubTypes != null)
{
var jsts = dbContext.JobSubTypes.Where(jst => JobSubTypes.Contains(jst.JobTypeId + "_" + jst.Id));
var jsts = Database.JobSubTypes.Where(jst => JobSubTypes.Contains(jst.JobTypeId + "_" + jst.Id));
foreach (var jst in jsts)
{
dc.JobSubTypes.Add(jst);
}
}
dbContext.SaveChanges();
Database.SaveChanges();
return Json(new Models.DeviceModel.ComponentModel { Result = "OK", Component = Models.DeviceModel._ComponentModel.FromDeviceComponent(dc) }, JsonRequestBehavior.AllowGet);
}
return Json(new Models.DeviceModel.ComponentModel { Result = "Invalid Device Component Id" }, JsonRequestBehavior.AllowGet);
}
[DiscoAuthorize(Claims.Config.DeviceModel.ConfigureComponents)]
public virtual ActionResult ComponentUpdate(int id, string Description, string Cost)
{
var dc = dbContext.DeviceComponents.Include("JobSubTypes").Where(i => i.Id == id).FirstOrDefault();
var dc = Database.DeviceComponents.Include("JobSubTypes").Where(i => i.Id == id).FirstOrDefault();
if (dc != null)
{
decimal cost = 0;
@@ -306,20 +325,22 @@ namespace Disco.Web.Areas.API.Controllers
dc.Description = Description;
dc.Cost = cost;
dbContext.SaveChanges();
Database.SaveChanges();
return Json(new Models.DeviceModel.ComponentModel { Result = "OK", Component = Models.DeviceModel._ComponentModel.FromDeviceComponent(dc) }, JsonRequestBehavior.AllowGet);
}
return Json(new Models.DeviceModel.ComponentModel { Result = "Invalid Device Component Id" }, JsonRequestBehavior.AllowGet);
}
[DiscoAuthorize(Claims.Config.DeviceModel.ConfigureComponents)]
public virtual ActionResult ComponentRemove(int id)
{
var dc = dbContext.DeviceComponents.Include("JobSubTypes").Where(c => c.Id == id).FirstOrDefault();
var dc = Database.DeviceComponents.Include("JobSubTypes").Where(c => c.Id == id).FirstOrDefault();
if (dc != null)
{
dc.JobSubTypes.Clear();
dbContext.DeviceComponents.Remove(dc);
dbContext.SaveChanges();
Database.DeviceComponents.Remove(dc);
Database.SaveChanges();
return Json("OK", JsonRequestBehavior.AllowGet);
}
return Json("Invalid Device Component Id", JsonRequestBehavior.AllowGet);
@@ -327,21 +348,23 @@ namespace Disco.Web.Areas.API.Controllers
#endregion
#region Index
[DiscoAuthorize(Claims.Config.DeviceModel.Show)]
public virtual ActionResult Index()
{
var deviceModels = dbContext.DeviceModels.ToArray().Select(dm => Models.DeviceModel._DeviceModel.FromDeviceModel(dm)).ToArray();
var deviceModels = Database.DeviceModels.ToArray().Select(dm => Models.DeviceModel._DeviceModel.FromDeviceModel(dm)).ToArray();
return Json(deviceModels, JsonRequestBehavior.AllowGet);
}
#endregion
#region Exporting
[DiscoAuthorizeAll(Claims.Config.DeviceModel.Show, Claims.Device.Actions.Export)]
public virtual ActionResult ExportDevices(int id)
{
DeviceModel dm = dbContext.DeviceModels.Find(id);
DeviceModel dm = Database.DeviceModels.Find(id);
if (dm == null)
throw new ArgumentNullException("id", "Invalid Device Model Id");
var devices = dbContext.Devices.Where(d => !d.DecommissionedDate.HasValue && d.DeviceModelId == dm.Id);
var devices = Database.Devices.Where(d => !d.DecommissionedDate.HasValue && d.DeviceModelId == dm.Id);
var export = BI.DeviceBI.Importing.Export.GenerateExport(devices);
@@ -1,16 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Disco.BI;
using Disco.BI.Extensions;
using Disco.Data.Configuration.Modules;
using Disco.BI.Extensions;
using Disco.Models.Repository;
using Disco.Services.Authorization;
using Disco.Services.Web;
using System;
using System.Linq;
using System.Web.Mvc;
namespace Disco.Web.Areas.API.Controllers
{
public partial class DeviceProfileController : dbAdminController
public partial class DeviceProfileController : AuthorizedDatabaseController
{
const string pDescription = "description";
@@ -25,15 +23,18 @@ namespace Disco.Web.Areas.API.Controllers
const string pEnforceOrganisationalUnit = "enforceorganisationalunit";
const string pProvisionADAccount = "provisionadaccount";
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
public virtual ActionResult Update(int id, string key, string value = null, Nullable<bool> redirect = null)
{
Authorization.Require(Claims.Config.DeviceProfile.Configure);
try
{
if (id < 0)
throw new ArgumentOutOfRangeException("id");
if (string.IsNullOrEmpty(key))
throw new ArgumentNullException("key");
var deviceProfile = dbContext.DeviceProfiles.Find(id);
var deviceProfile = Database.DeviceProfiles.Find(id);
if (deviceProfile != null)
{
switch (key.ToLower())
@@ -60,6 +61,7 @@ namespace Disco.Web.Areas.API.Controllers
UpdateDefaultOrganisationAddress(deviceProfile, value);
break;
case pComputerNameTemplate:
Authorization.Require(Claims.Config.DeviceProfile.ConfigureComputerNameTemplate);
UpdateComputerNameTemplate(deviceProfile, value);
break;
case pEnforceComputerNameConvention:
@@ -92,54 +94,75 @@ namespace Disco.Web.Areas.API.Controllers
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet);
}
}
#region Update Shortcut Methods
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
public virtual ActionResult UpdateDescription(int id, string Description = null, Nullable<bool> redirect = null)
{
return Update(id, pDescription, Description, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
public virtual ActionResult UpdateName(int id, string ProfileName = null, Nullable<bool> redirect = null)
{
return Update(id, pName, ProfileName, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
public virtual ActionResult UpdateShortName(int id, string ShortName = null, Nullable<bool> redirect = null)
{
return Update(id, pShortName, ShortName, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
public virtual ActionResult UpdateDistributionType(int id, string DistributionType = null, Nullable<bool> redirect = null)
{
return Update(id, pDistributionType, DistributionType, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
public virtual ActionResult UpdateCertificateProviderId(int id, string CertificateProviderId = null, Nullable<bool> redirect = null)
{
return Update(id, pCertificateProviderId, CertificateProviderId, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
public virtual ActionResult UpdateOrganisationalUnit(int id, string OrganisationalUnit = null, Nullable<bool> redirect = null)
{
return Update(id, pOrganisationalUnit, OrganisationalUnit, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
public virtual ActionResult UpdateDefaultOrganisationAddress(int id, string DefaultOrganisationAddress = null, Nullable<bool> redirect = null)
{
return Update(id, pDefaultOrganisationAddress, DefaultOrganisationAddress, redirect);
}
[DiscoAuthorizeAll(Claims.Config.DeviceProfile.Configure, Claims.Config.DeviceProfile.ConfigureComputerNameTemplate)]
public virtual ActionResult UpdateComputerNameTemplate(int id, string ComputerNameTemplate = null, Nullable<bool> redirect = null)
{
return Update(id, pComputerNameTemplate, ComputerNameTemplate, redirect);
}
// Added 2012-06-14 G#
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
public virtual ActionResult UpdateEnforceComputerNameConvention(int id, string EnforceComputerNameConvention = null, Nullable<bool> redirect = null)
{
return Update(id, pEnforceComputerNameConvention, EnforceComputerNameConvention, redirect);
}
// Added 2012-06-14 G#
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
public virtual ActionResult UpdateEnforceOrganisationalUnit(int id, string EnforceOrganisationalUnit = null, Nullable<bool> redirect = null)
{
return Update(id, pEnforceOrganisationalUnit, EnforceOrganisationalUnit, redirect);
}
// Added 2012-06-28 G#
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
public virtual ActionResult UpdateProvisionADAccount(int id, string ProvisionADAccount = null, Nullable<bool> redirect = null)
{
return Update(id, pProvisionADAccount, ProvisionADAccount, redirect);
}
#endregion
#region Update Properties
@@ -149,7 +172,7 @@ namespace Disco.Web.Areas.API.Controllers
deviceProfile.Description = null;
else
deviceProfile.Description = Description;
dbContext.SaveChanges();
Database.SaveChanges();
}
private void UpdateName(Disco.Models.Repository.DeviceProfile deviceProfile, string Name)
@@ -158,7 +181,7 @@ namespace Disco.Web.Areas.API.Controllers
throw new Exception("Profile name cannot be empty");
else
deviceProfile.Name = Name;
dbContext.SaveChanges();
Database.SaveChanges();
}
private void UpdateShortName(Disco.Models.Repository.DeviceProfile deviceProfile, string ShortName)
@@ -167,7 +190,7 @@ namespace Disco.Web.Areas.API.Controllers
throw new Exception("Profile short name cannot be empty");
else
deviceProfile.ShortName = ShortName;
dbContext.SaveChanges();
Database.SaveChanges();
}
private void UpdateDistributionType(Disco.Models.Repository.DeviceProfile deviceProfile, string DistributionType)
@@ -175,10 +198,8 @@ namespace Disco.Web.Areas.API.Controllers
int iDt;
if (int.TryParse(DistributionType, out iDt))
{
// Removed 2012-06-14 G# - Properties moved to DeviceProfile model & DB Migrated in DBv3.
//deviceProfile.Configuration(dbContext).DistributionType = (DeviceProfileConfiguration.DeviceProfileDistributionTypes)iDt;
deviceProfile.DistributionType = (Disco.Models.Repository.DeviceProfile.DistributionTypes)iDt;
dbContext.SaveChanges();
Database.SaveChanges();
return;
}
throw new Exception("Invalid Distribution Type Number");
@@ -199,28 +220,29 @@ namespace Disco.Web.Areas.API.Controllers
else
deviceProfile.CertificateProviderId = featureManifest.Id;
}
dbContext.SaveChanges();
Database.SaveChanges();
}
private void UpdateOrganisationalUnit(Disco.Models.Repository.DeviceProfile deviceProfile, string OrganisationalUnit)
{
if (string.IsNullOrWhiteSpace(OrganisationalUnit))
OrganisationalUnit = null;
// Removed 2012-06-14 G# - Properties moved to DeviceProfile model & DB Migrated in DBv3.
//deviceProfile.Configuration(dbContext).OrganisationalUnit = OrganisationalUnit;
deviceProfile.OrganisationalUnit = OrganisationalUnit;
dbContext.SaveChanges();
Database.SaveChanges();
}
private void UpdateComputerNameTemplate(Disco.Models.Repository.DeviceProfile deviceProfile, string ComputerNameTemplate)
{
Authorization.Require(Claims.Config.DeviceProfile.ConfigureComputerNameTemplate);
if (string.IsNullOrWhiteSpace(ComputerNameTemplate))
throw new Exception("ComputerNameTemplate is Required");
// Removed 2012-06-14 G# - Properties moved to DeviceProfile model & DB Migrated in DBv3.
//deviceProfile.Configuration(dbContext).ComputerNameTemplate = ComputerNameTemplate;
deviceProfile.ComputerNameTemplate = ComputerNameTemplate;
dbContext.SaveChanges();
Database.SaveChanges();
deviceProfile.ComputerNameInvalidateCache();
}
@@ -237,7 +259,7 @@ namespace Disco.Web.Areas.API.Controllers
int daoId;
if (int.TryParse(DefaultOrganisationAddress, out daoId))
{
var oa = dbContext.DiscoConfiguration.OrganisationAddresses.GetAddress(daoId);
var oa = Database.DiscoConfiguration.OrganisationAddresses.GetAddress(daoId);
if (oa != null)
{
deviceProfile.DefaultOrganisationAddress = oa.Id;
@@ -254,10 +276,9 @@ namespace Disco.Web.Areas.API.Controllers
}
dbContext.SaveChanges();
Database.SaveChanges();
}
// Added 2012-06-14 G#
private void UpdateEnforceComputerNameConvention(Disco.Models.Repository.DeviceProfile deviceProfile, string EnforceComputerNameConvention)
{
bool bValue;
@@ -265,12 +286,12 @@ namespace Disco.Web.Areas.API.Controllers
{
deviceProfile.EnforceComputerNameConvention = bValue;
dbContext.SaveChanges();
Database.SaveChanges();
return;
}
throw new Exception("Invalid Boolean Value");
}
// Added 2012-06-14 G#
private void UpdateEnforceOrganisationalUnit(Disco.Models.Repository.DeviceProfile deviceProfile, string EnforceOrganisationalUnit)
{
bool bValue;
@@ -278,12 +299,12 @@ namespace Disco.Web.Areas.API.Controllers
{
deviceProfile.EnforceOrganisationalUnit = bValue;
dbContext.SaveChanges();
Database.SaveChanges();
return;
}
throw new Exception("Invalid Boolean Value");
}
// Added 2012-06-28 G#
private void UpdateProvisionADAccount(Disco.Models.Repository.DeviceProfile deviceProfile, string ProvisionADAccount)
{
bool bValue;
@@ -291,13 +312,14 @@ namespace Disco.Web.Areas.API.Controllers
{
deviceProfile.ProvisionADAccount = bValue;
dbContext.SaveChanges();
Database.SaveChanges();
return;
}
throw new Exception("Invalid Boolean Value");
}
#endregion
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
public virtual ActionResult OrganisationalUnits()
{
var OUs = BI.Interop.ActiveDirectory.ActiveDirectory.GetOrganisationalUnitStructure();
@@ -306,15 +328,16 @@ namespace Disco.Web.Areas.API.Controllers
#region Actions
[DiscoAuthorize(Claims.Config.DeviceProfile.Delete)]
public virtual ActionResult Delete(int id, Nullable<bool> redirect = false)
{
try
{
var dp = dbContext.DeviceProfiles.Find(id);
var dp = Database.DeviceProfiles.Find(id);
if (dp != null)
{
dp.Delete(dbContext);
dbContext.SaveChanges();
dp.Delete(Database);
Database.SaveChanges();
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Config.DeviceProfile.Index(null));
else
@@ -334,15 +357,17 @@ namespace Disco.Web.Areas.API.Controllers
#endregion
#region Defaults
[DiscoAuthorize(Claims.Config.DeviceProfile.ConfigureDefaults)]
public virtual ActionResult Default(int id, Nullable<bool> redirect = null)
{
try
{
var dp = dbContext.DeviceProfiles.Find(id);
var dp = Database.DeviceProfiles.Find(id);
if (dp != null)
{
dbContext.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId = dp.Id;
dbContext.SaveChanges();
Database.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId = dp.Id;
Database.SaveChanges();
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Config.DeviceProfile.Index(id));
else
@@ -358,6 +383,8 @@ namespace Disco.Web.Areas.API.Controllers
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet);
}
}
[DiscoAuthorize(Claims.Config.DeviceProfile.ConfigureDefaults)]
public virtual ActionResult DefaultAddDeviceOffline(int id, Nullable<bool> redirect = false)
{
try
@@ -365,7 +392,7 @@ namespace Disco.Web.Areas.API.Controllers
int defaultValue = 0;
if (id > 0)
{
var dp = dbContext.DeviceProfiles.Find(id);
var dp = Database.DeviceProfiles.Find(id);
if (dp != null)
{
defaultValue = dp.Id;
@@ -375,8 +402,8 @@ namespace Disco.Web.Areas.API.Controllers
throw new Exception("Invalid Device Profile Number");
}
}
dbContext.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId = defaultValue;
dbContext.SaveChanges();
Database.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId = defaultValue;
Database.SaveChanges();
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Config.DeviceProfile.Index(id));
else
@@ -390,16 +417,18 @@ namespace Disco.Web.Areas.API.Controllers
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet);
}
}
#endregion
#region Exporting
[DiscoAuthorizeAll(Claims.Config.DeviceProfile.Show, Claims.Device.Actions.Export)]
public virtual ActionResult ExportDevices(int id)
{
DeviceProfile dp = dbContext.DeviceProfiles.Find(id);
DeviceProfile dp = Database.DeviceProfiles.Find(id);
if (dp == null)
throw new ArgumentNullException("id", "Invalid Device Profile Id");
var devices = dbContext.Devices.Where(d => !d.DecommissionedDate.HasValue && d.DeviceProfileId == dp.Id);
var devices = Database.Devices.Where(d => !d.DecommissionedDate.HasValue && d.DeviceProfileId == dp.Id);
var export = BI.DeviceBI.Importing.Export.GenerateExport(devices);
@@ -1,15 +1,18 @@
using System;
using Disco.BI;
using Disco.BI.Extensions;
using Disco.Models.Repository;
using Disco.Services.Authorization;
using Disco.Services.Users;
using Disco.Services.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Disco.BI;
using Disco.BI.Extensions;
using Disco.Models.Repository;
namespace Disco.Web.Areas.API.Controllers
{
public partial class DocumentTemplateController : dbAdminController
public partial class DocumentTemplateController : AuthorizedDatabaseController
{
const string pDescription = "description";
@@ -17,6 +20,7 @@ namespace Disco.Web.Areas.API.Controllers
const string pFilterExpression = "filterexpression";
const string pFlattenForm = "flattenform";
[DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)]
public virtual ActionResult Update(string id, string key, string value = null, bool redirect = false)
{
try
@@ -25,7 +29,7 @@ namespace Disco.Web.Areas.API.Controllers
throw new ArgumentNullException("id");
if (string.IsNullOrEmpty(key))
throw new ArgumentNullException("key");
var documentTemplate = dbContext.DocumentTemplates.Find(id);
var documentTemplate = Database.DocumentTemplates.Find(id);
if (documentTemplate != null)
{
switch (key.ToLower())
@@ -37,6 +41,7 @@ namespace Disco.Web.Areas.API.Controllers
UpdateScope(documentTemplate, value);
break;
case pFilterExpression:
Authorization.Require(Claims.Config.DocumentTemplate.ConfigureFilterExpression);
UpdateFilterExpression(documentTemplate, value);
break;
case pFlattenForm:
@@ -64,16 +69,16 @@ namespace Disco.Web.Areas.API.Controllers
}
}
[HttpGet]
[DiscoAuthorize(Claims.Config.DocumentTemplate.Upload), HttpGet]
public virtual ActionResult Template(string id)
{
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException("id");
var documentTemplate = dbContext.DocumentTemplates.Find(id);
var documentTemplate = Database.DocumentTemplates.Find(id);
if (documentTemplate == null)
throw new ArgumentException("Invalid Document Template Id", "id");
var filename = documentTemplate.RepositoryFilename(dbContext);
var filename = documentTemplate.RepositoryFilename(Database);
if (System.IO.File.Exists(filename))
{
return File(filename, DocumentTemplate.PdfMimeType, string.Format("{0}.pdf", documentTemplate.Id));
@@ -83,18 +88,19 @@ namespace Disco.Web.Areas.API.Controllers
throw new InvalidOperationException("Template not found");
}
}
[HttpPost]
[DiscoAuthorizeAll(Claims.Config.DocumentTemplate.Upload, Claims.Config.DocumentTemplate.Configure), HttpPost]
public virtual ActionResult Template(string id, bool redirect, HttpPostedFileBase Template)
{
try
{
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException("id");
var documentTemplate = dbContext.DocumentTemplates.Find(id);
var documentTemplate = Database.DocumentTemplates.Find(id);
if (documentTemplate == null)
throw new ArgumentException("Invalid Document Template Id", "id");
documentTemplate.SavePdfTemplate(dbContext, Template.InputStream);
documentTemplate.SavePdfTemplate(Database, Template.InputStream);
if (redirect)
return RedirectToAction(MVC.Config.DocumentTemplate.Index(documentTemplate.Id));
@@ -111,29 +117,34 @@ namespace Disco.Web.Areas.API.Controllers
}
#region Update Shortcut Methods
[DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)]
public virtual ActionResult UpdateDescription(string id, string Description = null, bool redirect = false)
{
return Update(id, pDescription, Description, redirect);
}
[DiscoAuthorizeAll(Claims.Config.DocumentTemplate.Configure, Claims.Config.DocumentTemplate.ConfigureFilterExpression)]
public virtual ActionResult UpdateFilterExpression(string id, string FilterExpression = null, bool redirect = false)
{
return Update(id, pFilterExpression, FilterExpression, redirect);
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)]
public virtual ActionResult UpdateFlattenForm(string id, string FlattenForm = null, bool redirect = false)
{
return Update(id, pFlattenForm, FlattenForm, redirect);
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)]
public virtual ActionResult UpdateScope(string id, string Scope = null, bool redirect = false)
{
return Update(id, pScope, Scope, redirect);
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)]
public virtual ActionResult UpdateSubTypes(string id, List<string> SubTypes = null)
{
try
{
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException("id");
var documentTemplate = dbContext.DocumentTemplates.Find(id);
var documentTemplate = Database.DocumentTemplates.Find(id);
UpdateSubTypes(documentTemplate, SubTypes);
@@ -153,7 +164,7 @@ namespace Disco.Web.Areas.API.Controllers
if (!string.IsNullOrWhiteSpace(Description))
{
documentTemplate.Description = Description.Trim();
dbContext.SaveChanges();
Database.SaveChanges();
return;
}
throw new Exception("Invalid Description");
@@ -164,7 +175,7 @@ namespace Disco.Web.Areas.API.Controllers
{
if (Disco.Models.Repository.DocumentTemplate.DocumentTemplateScopes.ToList().Contains(Scope))
{
dbContext.Configuration.LazyLoadingEnabled = true;
Database.Configuration.LazyLoadingEnabled = true;
documentTemplate.Scope = Scope;
@@ -175,7 +186,7 @@ namespace Disco.Web.Areas.API.Controllers
documentTemplate.JobSubTypes.Remove(st);
}
dbContext.SaveChanges();
Database.SaveChanges();
return;
}
}
@@ -194,7 +205,7 @@ namespace Disco.Web.Areas.API.Controllers
// Invalidate Cache
documentTemplate.FilterExpressionInvalidateCache();
dbContext.SaveChanges();
Database.SaveChanges();
}
private void UpdateFlattenForm(Disco.Models.Repository.DocumentTemplate documentTemplate, string FlattenForm)
{
@@ -211,11 +222,11 @@ namespace Disco.Web.Areas.API.Controllers
throw new Exception("Invalid Boolean Format");
}
dbContext.SaveChanges();
Database.SaveChanges();
}
private void UpdateSubTypes(Disco.Models.Repository.DocumentTemplate documentTemplate, List<string> SubTypes)
{
dbContext.Configuration.LazyLoadingEnabled = true;
Database.Configuration.LazyLoadingEnabled = true;
// Remove All Existing
if (documentTemplate.JobSubTypes != null)
@@ -232,35 +243,21 @@ namespace Disco.Web.Areas.API.Controllers
{
var typeId = stId.Substring(0, stId.IndexOf("_"));
var subTypeId = stId.Substring(stId.IndexOf("_") + 1);
var subType = dbContext.JobSubTypes.FirstOrDefault(jst => jst.JobTypeId == typeId && jst.Id == subTypeId);
var subType = Database.JobSubTypes.FirstOrDefault(jst => jst.JobTypeId == typeId && jst.Id == subTypeId);
subTypes.Add(subType);
}
documentTemplate.JobSubTypes = subTypes;
}
dbContext.SaveChanges();
Database.SaveChanges();
}
#endregion
#region Actions
[OutputCache(NoStore = true, Duration = 0)]
[DiscoAuthorize(Claims.Config.DocumentTemplate.UndetectedPages), OutputCache(NoStore = true, Duration = 0)]
public virtual ActionResult ImporterThumbnail(string SessionId, int PageNumber)
{
// Load from Cache
//var cacheKey = string.Format("Disco.BI.DocumentImporter-{0}-{1}", SessionId, PageNumber);
//var cacheValue = HttpContext.Cache.Get(cacheKey);
//if (cacheValue != null)
//{
// var cacheFile = cacheValue as byte[];
// if (cacheFile != null)
// {
// return File(cacheFile, "image/png");
// }
//}
var dataStoreSessionPagesCacheLocation = DataStore.CreateLocation(dbContext, "Cache\\DocumentDropBox_SessionPages");
var dataStoreSessionPagesCacheLocation = DataStore.CreateLocation(Database, "Cache\\DocumentDropBox_SessionPages");
var filename = System.IO.Path.Combine(dataStoreSessionPagesCacheLocation, string.Format("{0}-{1}", SessionId, PageNumber));
if (System.IO.File.Exists(filename))
return File(filename, "image/png");
@@ -268,9 +265,10 @@ namespace Disco.Web.Areas.API.Controllers
return File("~/ClientSource/Style/Images/Status/fileBroken256.png", "image/png");
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.UndetectedPages)]
public virtual ActionResult ImporterUndetectedFiles()
{
var undetectedLocation = DataStore.CreateLocation(dbContext, "DocumentDropBox_Unassigned");
var undetectedLocation = DataStore.CreateLocation(Database, "DocumentDropBox_Unassigned");
var undetectedDirectory = new System.IO.DirectoryInfo(undetectedLocation);
var m = undetectedDirectory.GetFiles("*.pdf").Select(f => new Models.DocumentTemplate.ImporterUndetectedFilesModel()
{
@@ -281,6 +279,8 @@ namespace Disco.Web.Areas.API.Controllers
return Json(m);
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.UndetectedPages)]
public virtual ActionResult ImporterUndetectedDataIdLookup(string id, string term, int limitCount = 20)
{
if (!string.IsNullOrEmpty(id) && !string.IsNullOrWhiteSpace(term))
@@ -306,7 +306,7 @@ namespace Disco.Web.Areas.API.Controllers
}
else
{
var documentTemplate = dbContext.DocumentTemplates.Find(id);
var documentTemplate = Database.DocumentTemplates.Find(id);
if (documentTemplate != null)
searchScope = documentTemplate.Scope;
else
@@ -318,13 +318,13 @@ namespace Disco.Web.Areas.API.Controllers
switch (searchScope)
{
case DocumentTemplate.DocumentTemplateScopes.Device:
results = BI.DeviceBI.Searching.Search(dbContext, term, limitCount).Select(sr => Models.DocumentTemplate.ImporterUndetectedDataIdLookupModel.FromSearchResultItem(sr)).ToArray();
results = BI.DeviceBI.Searching.Search(Database, term, limitCount).Select(sr => Models.DocumentTemplate.ImporterUndetectedDataIdLookupModel.FromSearchResultItem(sr)).ToArray();
break;
case DocumentTemplate.DocumentTemplateScopes.Job:
results = BI.JobBI.Searching.Search(dbContext, term, limitCount, false).Items.Select(sr => Models.DocumentTemplate.ImporterUndetectedDataIdLookupModel.FromSearchResultItem(sr)).ToArray();
results = BI.JobBI.Searching.Search(Database, term, limitCount, false).Items.Select(sr => Models.DocumentTemplate.ImporterUndetectedDataIdLookupModel.FromSearchResultItem(sr)).ToArray();
break;
case DocumentTemplate.DocumentTemplateScopes.User:
results = BI.UserBI.Searching.Search(dbContext, term, limitCount).Select(sr => Models.DocumentTemplate.ImporterUndetectedDataIdLookupModel.FromSearchResultItem(sr)).ToArray();
results = BI.UserBI.Searching.Search(Database, term, limitCount).Select(sr => Models.DocumentTemplate.ImporterUndetectedDataIdLookupModel.FromSearchResultItem(sr)).ToArray();
break;
default:
results = null;
@@ -337,11 +337,13 @@ namespace Disco.Web.Areas.API.Controllers
}
return Json(null, JsonRequestBehavior.AllowGet);
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.UndetectedPages)]
public virtual ActionResult ImporterUndetectedFile(string id, Nullable<bool> Source, Nullable<bool> Thumbnail)
{
if (!string.IsNullOrEmpty(id))
{
var undetectedLocation = DataStore.CreateLocation(dbContext, "DocumentDropBox_Unassigned");
var undetectedLocation = DataStore.CreateLocation(Database, "DocumentDropBox_Unassigned");
if (Source.HasValue && Source.Value)
{
var filename = System.IO.Path.Combine(undetectedLocation, string.Concat(id, ".pdf"));
@@ -372,11 +374,13 @@ namespace Disco.Web.Areas.API.Controllers
}
return HttpNotFound();
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.UndetectedPages)]
public virtual ActionResult ImporterUndetectedAssign(string id, string DocumentTemplateId, string DataId)
{
var undetectedLocation = DataStore.CreateLocation(dbContext, "DocumentDropBox_Unassigned");
var undetectedLocation = DataStore.CreateLocation(Database, "DocumentDropBox_Unassigned");
var filename = System.IO.Path.Combine(undetectedLocation, string.Concat(id, ".pdf"));
if (BI.Interop.Pdf.PdfImporter.ProcessPdfAttachment(filename, dbContext, DocumentTemplateId, DataId, DiscoApplication.CurrentUser.Id, DateTime.Now))
if (BI.Interop.Pdf.PdfImporter.ProcessPdfAttachment(filename, Database, DocumentTemplateId, DataId, UserService.CurrentUserId, DateTime.Now))
{
// Delete File
System.IO.File.Delete(filename);
@@ -396,9 +400,11 @@ namespace Disco.Web.Areas.API.Controllers
return Json("Unable to Import File with the supplied parameters");
}
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.UndetectedPages)]
public virtual ActionResult ImporterUndetectedDelete(string id)
{
var undetectedLocation = DataStore.CreateLocation(dbContext, "DocumentDropBox_Unassigned");
var undetectedLocation = DataStore.CreateLocation(Database, "DocumentDropBox_Unassigned");
var filename = System.IO.Path.Combine(undetectedLocation, string.Concat(id, ".pdf"));
if (System.IO.File.Exists(filename))
{
@@ -421,32 +427,49 @@ namespace Disco.Web.Areas.API.Controllers
}
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.BulkGenerate)]
public virtual ActionResult BulkGenerate(string id, string DataIds = null)
{
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException("id");
if (string.IsNullOrEmpty(DataIds))
throw new ArgumentNullException("DataIds");
var documentTemplate = dbContext.DocumentTemplates.Find(id);
var documentTemplate = Database.DocumentTemplates.Find(id);
if (documentTemplate == null)
throw new ArgumentException("Invalid Document Template Id", "id");
switch (documentTemplate.Scope)
{
case DocumentTemplate.DocumentTemplateScopes.Device:
Authorization.Require(Claims.Device.Actions.GenerateDocuments);
break;
case DocumentTemplate.DocumentTemplateScopes.Job:
Authorization.Require(Claims.Job.Actions.GenerateDocuments);
break;
case DocumentTemplate.DocumentTemplateScopes.User:
Authorization.Require(Claims.User.Actions.GenerateDocuments);
break;
default:
throw new InvalidOperationException("Unknown DocumentType Scope");
}
var dataIds = DataIds.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
var timeStamp = DateTime.Now;
var pdf = documentTemplate.GeneratePdfBulk(dbContext, DiscoApplication.CurrentUser, timeStamp, dataIds);
var pdf = documentTemplate.GeneratePdfBulk(Database, UserService.CurrentUser, timeStamp, dataIds);
return File(pdf, "application/pdf", string.Format("{0}_Bulk_{1:yyyyMMdd-HHmmss}.pdf", documentTemplate.Id, timeStamp));
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.Delete)]
public virtual ActionResult Delete(string id, Nullable<bool> redirect = false)
{
try
{
var at = dbContext.DocumentTemplates.Include("JobSubTypes").FirstOrDefault(a => a.Id == id);
var at = Database.DocumentTemplates.Include("JobSubTypes").FirstOrDefault(a => a.Id == id);
if (at != null)
{
at.Delete(dbContext);
dbContext.SaveChanges();
at.Delete(Database);
Database.SaveChanges();
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Config.DocumentTemplate.Index(null));
else
@@ -1,12 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Disco.Services.Authorization;
using Disco.Services.Web;
using System.Web.Mvc;
namespace Disco.Web.Areas.API.Controllers
{
public partial class ExpressionsController : dbAdminController
[DiscoAuthorize(Claims.DiscoAdminAccount)]
public partial class ExpressionsController : AuthorizedDatabaseController
{
public virtual ActionResult ValidateExpression(string Expression)
{
File diff suppressed because it is too large Load Diff
@@ -1,22 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Disco.BI.Extensions;
using Disco.Services.Authorization;
using Disco.Services.Logging;
using Disco.Services.Tasks;
using Disco.Services.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
namespace Disco.Web.Areas.API.Controllers
{
public partial class LoggingController : dbAdminController
public partial class LoggingController : AuthorizedDatabaseController
{
[DiscoAuthorize(Claims.Config.Logging.Show)]
public virtual ActionResult Modules()
{
var m = LogContext.LogModules.Values.Select(lm => Models.Logs.LogModuleModel.FromLogModule(lm)).ToList();
return Json(m, JsonRequestBehavior.AllowGet);
}
[DiscoAuthorize(Claims.Config.Logging.Show)]
public virtual ActionResult RetrieveEvents(string Format, DateTime? Start = null, DateTime? End = null, int? ModuleId = null, List<int> EventTypeIds = null, int? Take = null)
{
var logRetriever = new ReadLogContext()
@@ -27,7 +30,7 @@ namespace Disco.Web.Areas.API.Controllers
EventTypes = EventTypeIds,
Take = Take
};
var results = logRetriever.Query(dbContext);
var results = logRetriever.Query(Database);
switch (Format.ToLower())
{
@@ -46,6 +49,7 @@ namespace Disco.Web.Areas.API.Controllers
}
}
public virtual ActionResult ScheduledTaskStatus(string id)
{
if (string.IsNullOrEmpty(id))
@@ -1,16 +1,18 @@
using System;
using System.Collections.Generic;
using Disco.Services.Authorization;
using Disco.Services.Plugins;
using Disco.Services.Plugins.CommunityInterop;
using Disco.Services.Web;
using System;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Disco.Services.Plugins;
using Disco.Services.Plugins.CommunityInterop;
namespace Disco.Web.Areas.API.Controllers
{
public partial class PluginController : dbAdminController
public partial class PluginController : AuthorizedDatabaseController
{
[DiscoAuthorize(Claims.Config.Plugin.Install)]
public virtual ActionResult UpdateLibraryCatalogue()
{
var status = PluginLibraryUpdateTask.ScheduleNow();
@@ -20,6 +22,7 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(status.SessionId));
}
[DiscoAuthorize(Claims.Config.Plugin.Install)]
public virtual ActionResult UpdateAll()
{
var status = UpdatePluginTask.UpdateAllPlugins();
@@ -27,6 +30,7 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(status.SessionId));
}
[DiscoAuthorize(Claims.Config.Plugin.Install)]
public virtual ActionResult Update(string PluginId)
{
if (string.IsNullOrEmpty(PluginId))
@@ -37,6 +41,7 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(status.SessionId));
}
[DiscoAuthorizeAll(Claims.Config.Plugin.Install, Claims.Config.Plugin.InstallLocal)]
public virtual ActionResult UpdateLocal(string PluginId, HttpPostedFileBase Plugin)
{
if (string.IsNullOrEmpty(PluginId))
@@ -45,10 +50,10 @@ namespace Disco.Web.Areas.API.Controllers
if (Plugin == null || Plugin.ContentLength <= 0 || string.IsNullOrWhiteSpace(Plugin.FileName))
throw new ArgumentException("A discoPlugin file must be uploaded", "Plugin");
var tempPluginLocation = Path.Combine(dbContext.DiscoConfiguration.PluginPackagesLocation, Path.GetFileName(Plugin.FileName));
var tempPluginLocation = Path.Combine(Database.DiscoConfiguration.PluginPackagesLocation, Path.GetFileName(Plugin.FileName));
if (!Directory.Exists(dbContext.DiscoConfiguration.PluginPackagesLocation))
Directory.CreateDirectory(dbContext.DiscoConfiguration.PluginPackagesLocation);
if (!Directory.Exists(Database.DiscoConfiguration.PluginPackagesLocation))
Directory.CreateDirectory(Database.DiscoConfiguration.PluginPackagesLocation);
if (System.IO.File.Exists(tempPluginLocation))
System.IO.File.Delete(tempPluginLocation);
@@ -60,6 +65,7 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(status.SessionId));
}
[DiscoAuthorize(Claims.Config.Plugin.Uninstall)]
public virtual ActionResult Uninstall(string id, bool UninstallData)
{
if (string.IsNullOrEmpty(id))
@@ -72,12 +78,13 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(status.SessionId));
}
[DiscoAuthorize(Claims.Config.Plugin.Install)]
public virtual ActionResult Install(string PluginId)
{
if (string.IsNullOrEmpty(PluginId))
throw new ArgumentNullException("PluginId", "A PluginId must be supplied");
var catalogue = Plugins.LoadCatalogue(dbContext);
var catalogue = Plugins.LoadCatalogue(Database);
var plugin = catalogue.Plugins.FirstOrDefault(p => p.Id.Equals(PluginId));
if (plugin == null)
@@ -87,22 +94,23 @@ namespace Disco.Web.Areas.API.Controllers
if (Plugins.PluginInstalled(plugin.Id))
throw new InvalidOperationException("This plugin is already installed");
var tempPluginLocation = Path.Combine(dbContext.DiscoConfiguration.PluginPackagesLocation, string.Format("{0}.discoPlugin", plugin.Id));
var tempPluginLocation = Path.Combine(Database.DiscoConfiguration.PluginPackagesLocation, string.Format("{0}.discoPlugin", plugin.Id));
var status = InstallPluginTask.InstallPlugin(plugin.LatestDownloadUrl, tempPluginLocation, true);
return RedirectToAction(MVC.Config.Logging.TaskStatus(status.SessionId));
}
[DiscoAuthorizeAll(Claims.Config.Plugin.Install, Claims.Config.Plugin.InstallLocal)]
public virtual ActionResult InstallLocal(HttpPostedFileBase Plugin)
{
if (Plugin == null || Plugin.ContentLength <= 0 || string.IsNullOrWhiteSpace(Plugin.FileName))
throw new ArgumentException("A discoPlugin file must be uploaded", "Plugin");
var tempPluginLocation = Path.Combine(dbContext.DiscoConfiguration.PluginPackagesLocation, Path.GetFileName(Plugin.FileName));
var tempPluginLocation = Path.Combine(Database.DiscoConfiguration.PluginPackagesLocation, Path.GetFileName(Plugin.FileName));
if (!Directory.Exists(dbContext.DiscoConfiguration.PluginPackagesLocation))
Directory.CreateDirectory(dbContext.DiscoConfiguration.PluginPackagesLocation);
if (!Directory.Exists(Database.DiscoConfiguration.PluginPackagesLocation))
Directory.CreateDirectory(Database.DiscoConfiguration.PluginPackagesLocation);
if (System.IO.File.Exists(tempPluginLocation))
System.IO.File.Delete(tempPluginLocation);
@@ -1,22 +1,20 @@
using System;
using System.Collections.Generic;
using Disco.BI.Extensions;
using Disco.BI.Interop.ActiveDirectory;
using Disco.Services.Authorization;
using Disco.Services.Web;
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Disco.BI;
using Disco.BI.Extensions;
using System.IO;
using System.Drawing;
using System.Text;
using Disco.Services.Tasks;
using Disco.BI.Interop.ActiveDirectory;
using Disco.Models.Repository;
namespace Disco.Web.Areas.API.Controllers
{
public partial class SystemController : dbAdminController
public partial class SystemController : AuthorizedDatabaseController
{
[DiscoAuthorize(Claims.Config.System.Show)]
public virtual ActionResult UpdateLastNetworkLogonDates()
{
var taskStatus = ActiveDirectoryUpdateLastNetworkLogonDateJob.ScheduleImmediately();
@@ -24,44 +22,46 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(taskStatus.SessionId));
}
[DiscoAuthorize(Claims.DiscoAdminAccount)]
public virtual ActionResult UpdateAttachmentThumbnails()
{
// Device Attachments
var das = dbContext.DeviceAttachments.Where(da => da.MimeType == "application/pdf");
var das = Database.DeviceAttachments.Where(da => da.MimeType == "application/pdf");
foreach (var da in das)
{
var fileName = da.RepositoryThumbnailFilename(dbContext);
var fileName = da.RepositoryThumbnailFilename(Database);
if (!System.IO.File.Exists(fileName))
{
da.GenerateThumbnail(dbContext);
da.GenerateThumbnail(Database);
}
}
// User Attachments
var uas = dbContext.UserAttachments.Where(ua => ua.MimeType == "application/pdf");
var uas = Database.UserAttachments.Where(ua => ua.MimeType == "application/pdf");
foreach (var ua in uas)
{
var fileName = ua.RepositoryThumbnailFilename(dbContext);
var fileName = ua.RepositoryThumbnailFilename(Database);
if (!System.IO.File.Exists(fileName))
{
ua.GenerateThumbnail(dbContext);
ua.GenerateThumbnail(Database);
}
}
// Job Attachments
var jas = dbContext.JobAttachments.Where(ja => ja.MimeType == "application/pdf");
var jas = Database.JobAttachments.Where(ja => ja.MimeType == "application/pdf");
foreach (var ja in jas)
{
var fileName = ja.RepositoryThumbnailFilename(dbContext);
var fileName = ja.RepositoryThumbnailFilename(Database);
if (!System.IO.File.Exists(fileName))
{
ja.GenerateThumbnail(dbContext);
ja.GenerateThumbnail(Database);
}
}
return Content("Done", "text/text");
}
[DiscoAuthorize(Claims.Config.System.Show)]
public virtual ActionResult UpdateCheck()
{
var ts = Disco.BI.Interop.Community.UpdateCheckTask.ScheduleNow();
@@ -72,16 +72,17 @@ namespace Disco.Web.Areas.API.Controllers
#region Organisation
#region Organisation Name
[DiscoAuthorize(Claims.Config.Organisation.ConfigureName)]
public virtual ActionResult UpdateOrganisationName(string OrganisationName, bool redirect = false)
{
if (string.IsNullOrWhiteSpace(OrganisationName))
dbContext.DiscoConfiguration.OrganisationName = null;
Database.DiscoConfiguration.OrganisationName = null;
else
dbContext.DiscoConfiguration.OrganisationName = OrganisationName;
Database.DiscoConfiguration.OrganisationName = OrganisationName;
dbContext.SaveChanges();
Database.SaveChanges();
DiscoApplication.OrganisationName = dbContext.DiscoConfiguration.OrganisationName;
DiscoApplication.OrganisationName = Database.DiscoConfiguration.OrganisationName;
if (redirect)
return RedirectToAction(MVC.Config.Organisation.Index());
@@ -99,7 +100,7 @@ namespace Disco.Web.Areas.API.Controllers
if (Height < 1)
throw new ArgumentOutOfRangeException("Height");
using (Stream logoStream = dbContext.DiscoConfiguration.OrganisationLogo)
using (Stream logoStream = Database.DiscoConfiguration.OrganisationLogo)
{
using (Image logoBitmap = Bitmap.FromStream(logoStream))
{
@@ -107,12 +108,12 @@ namespace Disco.Web.Areas.API.Controllers
}
}
}
[HttpPost]
[DiscoAuthorize(Claims.Config.Organisation.ConfigureLogo), HttpPost]
public virtual ActionResult OrganisationLogo(bool redirect, HttpPostedFileBase Image, bool? ResetLogo = null)
{
if (ResetLogo.HasValue && ResetLogo.Value)
{
dbContext.DiscoConfiguration.OrganisationLogo = null;
Database.DiscoConfiguration.OrganisationLogo = null;
if (redirect)
return RedirectToAction(MVC.Config.Organisation.Index());
@@ -124,7 +125,7 @@ namespace Disco.Web.Areas.API.Controllers
{
if (Image.ContentType.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase))
{
dbContext.DiscoConfiguration.OrganisationLogo = Image.InputStream;
Database.DiscoConfiguration.OrganisationLogo = Image.InputStream;
if (redirect)
return RedirectToAction(MVC.Config.Organisation.Index());
@@ -147,7 +148,7 @@ namespace Disco.Web.Areas.API.Controllers
#endregion
#region Organisation Addresses
[DiscoAuthorize(Claims.Config.Organisation.ConfigureAddresses)]
public virtual ActionResult UpdateOrganisationAddress(Disco.Models.BI.Config.OrganisationAddress organisationAddress, bool redirect = false)
{
if (organisationAddress == null)
@@ -156,8 +157,8 @@ namespace Disco.Web.Areas.API.Controllers
}
if (ModelState.IsValid)
{
dbContext.DiscoConfiguration.OrganisationAddresses.SetAddress(organisationAddress);
dbContext.SaveChanges();
Database.DiscoConfiguration.OrganisationAddresses.SetAddress(organisationAddress);
Database.SaveChanges();
if (redirect)
return RedirectToAction(MVC.Config.Organisation.Index());
else
@@ -183,10 +184,11 @@ namespace Disco.Web.Areas.API.Controllers
return Json(em.ToString(), JsonRequestBehavior.AllowGet);
}
}
[DiscoAuthorize(Claims.Config.Organisation.ConfigureAddresses)]
public virtual ActionResult DeleteOrganisationAddress(int Id, bool redirect = false)
{
dbContext.DiscoConfiguration.OrganisationAddresses.RemoveAddress(Id);
dbContext.SaveChanges();
Database.DiscoConfiguration.OrganisationAddresses.RemoveAddress(Id);
Database.SaveChanges();
if (redirect)
return RedirectToAction(MVC.Config.Organisation.Index());
@@ -198,13 +200,14 @@ namespace Disco.Web.Areas.API.Controllers
#region MultiSiteMode
[DiscoAuthorize(Claims.Config.Organisation.ConfigureMultiSiteMode)]
public virtual ActionResult UpdateMultiSiteMode(bool MultiSiteMode, bool redirect = false)
{
dbContext.DiscoConfiguration.MultiSiteMode = MultiSiteMode;
Database.DiscoConfiguration.MultiSiteMode = MultiSiteMode;
dbContext.SaveChanges();
Database.SaveChanges();
DiscoApplication.MultiSiteMode = dbContext.DiscoConfiguration.MultiSiteMode;
DiscoApplication.MultiSiteMode = Database.DiscoConfiguration.MultiSiteMode;
if (redirect)
return RedirectToAction(MVC.Config.Organisation.Index());
@@ -1,29 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Disco.BI;
using Disco.BI.Extensions;
using Disco.BI.Extensions;
using Disco.Services.Authorization;
using Disco.Services.Users;
using Disco.Services.Web;
using System;
using System.IO;
using System.Linq;
using System.Web.Mvc;
namespace Disco.Web.Areas.API.Controllers
{
public partial class UserController : dbAdminController
public partial class UserController : AuthorizedDatabaseController
{
[DiscoAuthorize(Claims.User.Search)]
public virtual ActionResult UpstreamUsers(string term)
{
return Json(BI.UserBI.Searching.SearchUpstream(term), JsonRequestBehavior.AllowGet);
}
#region User Attachements
[DiscoAuthorize(Claims.User.ShowAttachments)]
[OutputCache(Location = System.Web.UI.OutputCacheLocation.Client, Duration = 172800)]
public virtual ActionResult AttachmentDownload(int id)
{
var ua = dbContext.UserAttachments.Find(id);
var ua = Database.UserAttachments.Find(id);
if (ua != null)
{
var filePath = ua.RepositoryFilename(dbContext);
var filePath = ua.RepositoryFilename(Database);
if (System.IO.File.Exists(filePath))
{
return File(filePath, ua.MimeType, ua.Filename);
@@ -35,13 +38,15 @@ namespace Disco.Web.Areas.API.Controllers
}
return HttpNotFound("Invalid Attachment Number");
}
[DiscoAuthorize(Claims.User.ShowAttachments)]
[OutputCache(Location = System.Web.UI.OutputCacheLocation.Client, Duration = 172800)]
public virtual ActionResult AttachmentThumbnail(int id)
{
var ua = dbContext.UserAttachments.Find(id);
var ua = Database.UserAttachments.Find(id);
if (ua != null)
{
var thumbPath = ua.RepositoryThumbnailFilename(dbContext);
var thumbPath = ua.RepositoryThumbnailFilename(Database);
if (System.IO.File.Exists(thumbPath))
{
if (thumbPath.EndsWith(".png", StringComparison.InvariantCultureIgnoreCase))
@@ -54,9 +59,11 @@ namespace Disco.Web.Areas.API.Controllers
}
return HttpNotFound("Invalid Attachment Number");
}
[DiscoAuthorize(Claims.User.Actions.AddAttachments)]
public virtual ActionResult AttachmentUpload(string id, string Comments)
{
var u = dbContext.Users.Find(id);
var u = Database.Users.Find(id);
if (u != null)
{
if (Request.Files.Count > 0)
@@ -71,18 +78,18 @@ namespace Disco.Web.Areas.API.Controllers
var ua = new Disco.Models.Repository.UserAttachment()
{
UserId = u.Id,
TechUserId = DiscoApplication.CurrentUser.Id,
TechUserId = UserService.CurrentUserId,
Filename = file.FileName,
MimeType = contentType,
Timestamp = DateTime.Now,
Comments = Comments
};
dbContext.UserAttachments.Add(ua);
dbContext.SaveChanges();
Database.UserAttachments.Add(ua);
Database.SaveChanges();
ua.SaveAttachment(dbContext, file.InputStream);
ua.SaveAttachment(Database, file.InputStream);
ua.GenerateThumbnail(dbContext);
ua.GenerateThumbnail(Database);
return Json(ua.Id, JsonRequestBehavior.AllowGet);
}
@@ -91,9 +98,11 @@ namespace Disco.Web.Areas.API.Controllers
}
throw new Exception("Invalid User Id");
}
[DiscoAuthorize(Claims.User.ShowAttachments)]
public virtual ActionResult Attachment(int id)
{
var ua = dbContext.UserAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault();
var ua = Database.UserAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault();
if (ua != null)
{
@@ -107,9 +116,11 @@ namespace Disco.Web.Areas.API.Controllers
}
return Json(new Models.Attachment.AttachmentModel() { Result = "Invalid Attachment Number" }, JsonRequestBehavior.AllowGet);
}
[DiscoAuthorize(Claims.User.ShowAttachments)]
public virtual ActionResult Attachments(string id)
{
var u = dbContext.Users.Include("UserAttachments.TechUser").Where(m => m.Id == id).FirstOrDefault();
var u = Database.Users.Include("UserAttachments.TechUser").Where(m => m.Id == id).FirstOrDefault();
if (u != null)
{
var m = new Models.Attachment.AttachmentsModel()
@@ -122,47 +133,47 @@ namespace Disco.Web.Areas.API.Controllers
}
return Json(new Models.Attachment.AttachmentsModel() { Result = "Invalid User Id" }, JsonRequestBehavior.AllowGet);
}
[DiscoAuthorizeAny(Claims.User.Actions.RemoveAnyAttachments, Claims.User.Actions.RemoveOwnAttachments)]
public virtual ActionResult AttachmentRemove(int id)
{
var ua = dbContext.UserAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault();
var ua = Database.UserAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault();
if (ua != null)
{
// 2012-02-17 G# Remove - 'Delete Own Comments' policy
//if (ua.TechUserId == DiscoApplication.CurrentUser.Id)
//{
ua.OnDelete(dbContext);
dbContext.SaveChanges();
if (ua.TechUserId.Equals(CurrentUser.Id, StringComparison.InvariantCultureIgnoreCase))
Authorization.RequireAny(Claims.User.Actions.RemoveAnyAttachments, Claims.User.Actions.RemoveOwnAttachments);
else
Authorization.Require(Claims.User.Actions.RemoveAnyAttachments);
ua.OnDelete(Database);
Database.SaveChanges();
return Json("OK", JsonRequestBehavior.AllowGet);
//}
//else
//{
// return Json("You can only delete your own attachments.", JsonRequestBehavior.AllowGet);
//}
}
return Json("Invalid Attachment Number", JsonRequestBehavior.AllowGet);
}
#endregion
[DiscoAuthorize(Claims.User.Actions.GenerateDocuments)]
public virtual ActionResult GeneratePdf(string id, string DocumentTemplateId)
{
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException("id");
if (string.IsNullOrEmpty(DocumentTemplateId))
throw new ArgumentNullException("AttachmentTypeId");
var user = dbContext.Users.Find(id);
var user = Database.Users.Find(id);
if (user != null)
{
var documentTemplate = dbContext.DocumentTemplates.Find(DocumentTemplateId);
var documentTemplate = Database.DocumentTemplates.Find(DocumentTemplateId);
if (documentTemplate != null)
{
var timeStamp = DateTime.Now;
Stream pdf;
using (var generationState = Disco.Models.BI.DocumentTemplates.DocumentState.DefaultState())
{
pdf = documentTemplate.GeneratePdf(dbContext, user, DiscoApplication.CurrentUser, timeStamp, generationState);
pdf = documentTemplate.GeneratePdf(Database, user, UserService.CurrentUser, timeStamp, generationState);
}
dbContext.SaveChanges();
Database.SaveChanges();
return File(pdf, "application/pdf", string.Format("{0}_{1}_{2:yyyyMMdd-HHmmss}.pdf", documentTemplate.Id, user.Id, timeStamp));
}
else