Add controller from frontend

This commit is contained in:
Martijn Scheepers
2023-09-27 09:34:20 +02:00
parent fa43864985
commit 224614b5d1
55 changed files with 5997 additions and 815 deletions

View File

@@ -21,6 +21,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Aperio_Control_Centre.ACSDa
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Aperio_Control_Centre.LeafletBlazor", "Aperio_Control_Centre.LeafletBlazor\Aperio_Control_Centre.LeafletBlazor.csproj", "{6F7BB4AC-DF6B-4318-913D-0EEAFC931641}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aperio_Control_Centre.Export", "Aperio_Control_Centre.Export\Aperio_Control_Centre.Export.csproj", "{96CDC7AE-E4DE-4C57-8E85-A0A6840CAFA4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aperio_Control_Centre.Export.UnitTest", "Aperio_Control_Centre.Export.UnitTest\Aperio_Control_Centre.Export.UnitTest.csproj", "{A20E97F7-8AB2-4A9A-A8A8-9902134BB223}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -101,6 +105,22 @@ Global
{6F7BB4AC-DF6B-4318-913D-0EEAFC931641}.Release|Any CPU.Build.0 = Release|Any CPU
{6F7BB4AC-DF6B-4318-913D-0EEAFC931641}.Release|x64.ActiveCfg = Release|Any CPU
{6F7BB4AC-DF6B-4318-913D-0EEAFC931641}.Release|x64.Build.0 = Release|Any CPU
{96CDC7AE-E4DE-4C57-8E85-A0A6840CAFA4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{96CDC7AE-E4DE-4C57-8E85-A0A6840CAFA4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{96CDC7AE-E4DE-4C57-8E85-A0A6840CAFA4}.Debug|x64.ActiveCfg = Debug|Any CPU
{96CDC7AE-E4DE-4C57-8E85-A0A6840CAFA4}.Debug|x64.Build.0 = Debug|Any CPU
{96CDC7AE-E4DE-4C57-8E85-A0A6840CAFA4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{96CDC7AE-E4DE-4C57-8E85-A0A6840CAFA4}.Release|Any CPU.Build.0 = Release|Any CPU
{96CDC7AE-E4DE-4C57-8E85-A0A6840CAFA4}.Release|x64.ActiveCfg = Release|Any CPU
{96CDC7AE-E4DE-4C57-8E85-A0A6840CAFA4}.Release|x64.Build.0 = Release|Any CPU
{A20E97F7-8AB2-4A9A-A8A8-9902134BB223}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A20E97F7-8AB2-4A9A-A8A8-9902134BB223}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A20E97F7-8AB2-4A9A-A8A8-9902134BB223}.Debug|x64.ActiveCfg = Debug|Any CPU
{A20E97F7-8AB2-4A9A-A8A8-9902134BB223}.Debug|x64.Build.0 = Debug|Any CPU
{A20E97F7-8AB2-4A9A-A8A8-9902134BB223}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A20E97F7-8AB2-4A9A-A8A8-9902134BB223}.Release|Any CPU.Build.0 = Release|Any CPU
{A20E97F7-8AB2-4A9A-A8A8-9902134BB223}.Release|x64.ActiveCfg = Release|Any CPU
{A20E97F7-8AB2-4A9A-A8A8-9902134BB223}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@@ -106,7 +106,7 @@ namespace Aperio_Control_Centre.ACSDatabase.Models
//{
// get
// {
// using ACSDatabaseEntities db = new();
// using ACSDatabaseContext db = new();
// var groups = db.DeviceGroupJoins.Where(u => u.Device_Id == this.Id).Select(g => g.Groups);
// string groupString = "";

View File

@@ -336,7 +336,7 @@
// // get
// // {
// // throw new NotImplementedException();
// // //using ACSDatabaseEntities db = new();
// // //using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
// // //return db.Devices.Where(m => m.UnlockTimezoneId == this.Id && m.Active != ActiveStates.Deleted).Include(l => l.Locations).ToList();
// // }
// //}

View File

@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
<PackageReference Include="MSTest.TestAdapter" Version="3.0.4" />
<PackageReference Include="MSTest.TestFramework" Version="3.0.4" />
<PackageReference Include="coverlet.collector" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Aperio_Control_Centre.Export\Aperio_Control_Centre.Export.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1 @@
global using Microsoft.VisualStudio.TestTools.UnitTesting;

View File

@@ -0,0 +1,42 @@
using Aperio_Control_Centre.Export.Paxton;
using System.Text;
namespace Aperio_Control_Centre.Export.Test.Paxton
{
[TestClass]
public class PaxtonAuthorizationModelTest
{
[TestMethod]
public void AuthorizationModel_ToCSV1()
{
//ict;JanWillem;;{'Cards':[{'Number':'19697050','Type':'0','Lost':'0'}]};;Huurder 02 Arbounie;{'AccessLevels':[{'Name':'Arbo Unie', 'Ordinal':'1'}]};;;;2023-jul-14;;;;;;;;;;;;;;;;1581
PaxtonAuthorizationModel auth = new PaxtonAuthorizationModel
{
Name = "Arbo Unie",
Ordinal = true
};
StringBuilder sb = new StringBuilder();
auth.ToCSV(ref sb);
Assert.AreEqual("{'Name':'Arbo Unie','Ordinal':'1'}", sb.ToString());
}
[TestMethod]
public void AuthorizationModel_ToCSV2()
{
PaxtonAuthorizationModel auth = new PaxtonAuthorizationModel
{
Name = "Arbo Unie",
Ordinal = false
};
StringBuilder sb = new StringBuilder();
auth.ToCSV(ref sb);
Assert.AreEqual("{'Name':'Arbo Unie','Ordinal':'0'}", sb.ToString());
}
}
}

View File

@@ -0,0 +1,56 @@
using Aperio_Control_Centre.Export.Paxton;
using System.Text;
namespace Aperio_Control_Centre.Export.Test.Paxton
{
[TestClass]
public class PaxtonCardModelTest
{
[TestMethod]
public void CardModel_ToCSV1()
{
//ict;JanWillem;;{'Cards':[{'Number':'19697050','Type':'0','Lost':'0'}]};;Huurder 02 Arbounie;{'AccessLevels':[{'Name':'Arbo Unie', 'Ordinal':'1'}]};;;;2023-jul-14;;;;;;;;;;;;;;;;1581
PaxtonCardModel card = new PaxtonCardModel
{
Number = "19697050",
Type = PaxtonCardTypes.Niet_gespecificeerd,
Lost = false
};
Assert.AreEqual("{'Number':'19697050','Type':'0','Lost':'0'}", card.ToCSV());
StringBuilder sb = new StringBuilder();
card.ToCSV(ref sb);
Assert.AreEqual("{'Number':'19697050','Type':'0','Lost':'0'}", sb.ToString());
}
[TestMethod]
public void CardModel_ToCSV2()
{
PaxtonCardModel card = new PaxtonCardModel
{
Number = "19697050",
Type = PaxtonCardTypes.Handsfree_kaart,
Lost = true
};
Assert.AreEqual("{'Number':'19697050','Type':'8','Lost':'1'}", card.ToCSV());
StringBuilder sb = new StringBuilder();
card.ToCSV(ref sb);
Assert.AreEqual("{'Number':'19697050','Type':'8','Lost':'1'}", sb.ToString());
}
[DataTestMethod]
[DataRow("90399DDE", "19695070")]
[DataRow("62CEFCA0", "57732256")]
//[DataRow("62CEFCA0", "37262968")]
public void CardModel_NumberFromHex(string hex, string dec)
{
Assert.AreEqual(dec, PaxtonCardModel.NumberFromHex(hex));
}
}
}

View File

@@ -0,0 +1,101 @@
using Aperio_Control_Centre.Export.Paxton;
using System.Text;
namespace Aperio_Control_Centre.Export.Test.Paxton
{
[TestClass]
public class PaxtonUserModelTest
{
[DataTestMethod]
[DataRow("Martijn Scheepers", "Martijn", "Scheepers")]
[DataRow("Billy van den broek", "Billy", "van den broek")]
[DataRow("Schoonmaak", "Schoonmaak", "")]
[DataRow("", "", "")]
public void UserModel_SplitUsername(string username, string firstname, string lastname)
{
Assert.AreEqual((firstname, lastname), PaxtonUserModel.SplitUsername(username));
}
[DataTestMethod]
[DataRow("1-1-2023", false, "1-1-2023")]
[DataRow("1-6-2022", true, "1-1-0001")]
public void UserModel_CalculateExpiryDate(string lastChanged, bool active, string result)
{
DateTime dateInput = DateTime.Parse(lastChanged);
DateTime dateResult = DateTime.Parse(result);
Assert.AreEqual(dateResult, PaxtonUserModel.CalculateExpiryDate(dateInput, active));
}
[TestMethod]
public void Usermodel_Cards_ToCSV()
{
//{'Cards':[{'Number':'57732256','Type':'3','Lost':'0'},{'Number':'37262968','Type':'0','Lost':'0'}]}
PaxtonUserModel user = new PaxtonUserModel();
user.Cards.Add(new PaxtonCardModel() { Number = "57732256", Type = PaxtonCardTypes.Tag, Lost = false });
user.Cards.Add(new PaxtonCardModel() { Number = "37262968", Type = PaxtonCardTypes.Niet_gespecificeerd, Lost = false });
StringBuilder sb = new StringBuilder();
user.CardsToCSV(ref sb);
Assert.AreEqual("{'Cards':[{'Number':'57732256','Type':'3','Lost':'0'},{'Number':'37262968','Type':'0','Lost':'0'}]}", sb.ToString());
}
[TestMethod]
public void Usermodel_Authorizations_ToCSV()
{
//{'AccessLevels':[{'Name':'Arbo Unie','Ordinal':'1'}]}
PaxtonUserModel user = new PaxtonUserModel();
user.AccessLevels.Add(new PaxtonAuthorizationModel() { Name = "Arbo Unie", Ordinal = true });
StringBuilder sb = new StringBuilder();
user.AuthorizationsToCSV(ref sb);
Assert.AreEqual("{'AccessLevels':[{'Name':'Arbo Unie','Ordinal':'1'}]}", sb.ToString());
}
[TestMethod]
public void Usermodel_JW_ToCSV()
{
//ict;JanWillem;;{'Cards':[{'Number':'19697050','Type':'0','Lost':'0'}]};;Huurder 02 Arbounie;{'AccessLevels':[{'Name':'Arbo Unie','Ordinal':'1'}]};;;;2023-jul-14;;;;;;;;;;;;;;;;1581
PaxtonUserModel user = new PaxtonUserModel
{
Surname = "ict",
Firstname = "JanWillem",
Department = "Huurder 02 Arbounie",
ActiveDate = DateTime.Parse("2023-jul-14"),
UserId = 1581
};
user.Cards.Add(new PaxtonCardModel() { Number = "19697050", Type = PaxtonCardTypes.Niet_gespecificeerd, Lost = false });
user.AccessLevels.Add(new PaxtonAuthorizationModel() { Name = "Arbo Unie", Ordinal = true });
StringBuilder sb = new StringBuilder();
user.ToCSV(ref sb);
Assert.AreEqual("ict;JanWillem;;{'Cards':[{'Number':'19697050','Type':'0','Lost':'0'}]};;Huurder 02 Arbounie;{'AccessLevels':[{'Name':'Arbo Unie','Ordinal':'1'}]};;;;14-jul-2023;;;;;;;;;;;;;;;;1581", sb.ToString());
}
[TestMethod]
public void Usermodel_HK_ToCSV()
{
//Kuijpers;Hannelore;;{'Cards':[{'Number':'57732256','Type':'3','Lost':'0'},{'Number':'37262968','Type':'0','Lost':'0'}]};;Huurder 02 Arbounie;{'AccessLevels':[{'Name':'Arbo Unie','Ordinal':'1'}]};;;;2023-jul-14;;;;;;;;;;;;;;;;1583
PaxtonUserModel user = new PaxtonUserModel
{
Surname = "Kuijpers",
Firstname = "Hannelore",
Department = "Huurder 02 Arbounie",
ActiveDate = DateTime.Parse("2023-jul-14"),
UserId = 1583
};
user.Cards.Add(new PaxtonCardModel() { Number = "57732256", Type = PaxtonCardTypes.Tag, Lost = false });
user.Cards.Add(new PaxtonCardModel() { Number = "37262968", Type = PaxtonCardTypes.Niet_gespecificeerd, Lost = false });
user.AccessLevels.Add(new PaxtonAuthorizationModel() { Name = "Arbo Unie", Ordinal = true });
StringBuilder sb = new StringBuilder();
user.ToCSV(ref sb);
Assert.AreEqual("Kuijpers;Hannelore;;{'Cards':[{'Number':'57732256','Type':'3','Lost':'0'},{'Number':'37262968','Type':'0','Lost':'0'}]};;Huurder 02 Arbounie;{'AccessLevels':[{'Name':'Arbo Unie','Ordinal':'1'}]};;;;14-jul-2023;;;;;;;;;;;;;;;;1583", sb.ToString());
}
}
}

View File

@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,4 @@
Achternaam;Voornaam;Tussenvoegsel;Kaartnummer;PIN;Afdeling;Autorisatie;Telefoon;Extensie;Mobiel;Activeringsdatum;Verval datum;Straatnaam;Huisnummer;Woonplaats;Land;Postcode;Telefoon privé;E-mail privé;Mobielnummer privé;E-mail;Geboortedatum;Datum in dienst;Personeelsnummer;Aantekeningen;Functie;Gebruikers ID
;;;;;;;;;;;;;;;;;;;;;;;;;;
ict;JanWillem;;{'Cards':[{'Number':'19697050','Type':'0','Lost':'0'}]};;Huurder 02 Arbounie;{'AccessLevels':[{'Name':'Arbo Unie', 'Ordinal':'1'}]};;;;2023-jul-14;;;;;;;;;;;;;;;;1581
Kuijpers;Hannelore;;{'Cards':[{'Number':'57732256','Type':'3','Lost':'0'},{'Number':'37262968','Type':'0','Lost':'0'}]};;Huurder 02 Arbounie;{'AccessLevels':[{'Name':'Arbo Unie', 'Ordinal':'1'}]};;;;2023-jul-14;;;;;;;;;;;;;;;;1583
1 Achternaam Voornaam Tussenvoegsel Kaartnummer PIN Afdeling Autorisatie Telefoon Extensie Mobiel Activeringsdatum Verval datum Straatnaam Huisnummer Woonplaats Land Postcode Telefoon privé E-mail privé Mobielnummer privé E-mail Geboortedatum Datum in dienst Personeelsnummer Aantekeningen Functie Gebruikers ID
2
3 ict JanWillem {'Cards':[{'Number':'19697050','Type':'0','Lost':'0'}]} Huurder 02 Arbounie {'AccessLevels':[{'Name':'Arbo Unie', 'Ordinal':'1'}]} 2023-jul-14 1581
4 Kuijpers Hannelore {'Cards':[{'Number':'57732256','Type':'3','Lost':'0'},{'Number':'37262968','Type':'0','Lost':'0'}]} Huurder 02 Arbounie {'AccessLevels':[{'Name':'Arbo Unie', 'Ordinal':'1'}]} 2023-jul-14 1583

View File

@@ -0,0 +1,22 @@
namespace Aperio_Control_Centre.Export
{
internal static class Extensions
{
public static IEnumerable<(bool, T)> Enumerate<T>(this IEnumerable<T> input)
{
int i = 1;
foreach (var item in input)
{
if (i == input.Count())
{
yield return (true, item);
}
else
{
yield return (false, item);
}
i++;
}
}
}
}

View File

@@ -0,0 +1,28 @@
using System.Text;
namespace Aperio_Control_Centre.Export.Paxton
{
public class PaxtonAuthorizationModel
{
public string Name { get; set; }
public bool Ordinal { get; set; }
public void ToCSV(ref StringBuilder sb)
{
//{'Name':'Arbo Unie','Ordinal':'1'}
sb.Append("{'Name':'");
sb.Append(Name);
sb.Append("','Ordinal':'");
if (Ordinal)
{
sb.Append("1");
}
else
{
sb.Append("0");
}
sb.Append("'}");
}
}
}

View File

@@ -0,0 +1,64 @@
using System.Text;
namespace Aperio_Control_Centre.Export.Paxton
{
public class PaxtonCardModel
{
public string Number { get; set; }
public PaxtonCardTypes Type { get; set; }
public bool Lost { get; set; }
public string ToCSV()
{
//{'Number':'19697050','Type':'0','Lost':'0'}
StringBuilder sb = new StringBuilder();
sb.Append("{'Number':'");
sb.Append(Number);
sb.Append("','Type':'");
sb.Append((int)Type);
sb.Append("','Lost':'");
if (Lost)
{
sb.Append("1");
}
else
{
sb.Append("0");
}
sb.Append("'}");
return sb.ToString();
}
public void ToCSV(ref StringBuilder sb)
{
//{'Number':'19697050','Type':'0','Lost':'0'}
sb.Append("{'Number':'");
sb.Append(Number);
sb.Append("','Type':'");
sb.Append((int)Type);
sb.Append("','Lost':'");
if (Lost)
{
sb.Append("1");
}
else
{
sb.Append("0");
}
sb.Append("'}");
}
public static string NumberFromHex(string hex)
{
if (hex.Length == 8)
{
string val = UInt32.Parse(hex, System.Globalization.NumberStyles.HexNumber).ToString();
return val.Substring(val.Length - 8);
}
return string.Empty;
}
}
}

View File

@@ -0,0 +1,17 @@
namespace Aperio_Control_Centre.Export.Paxton
{
public enum PaxtonCardTypes
{
Niet_gespecificeerd = 0,
Proximity_Clamshell = 1,
Proximity_ISOkaart = 2,
Tag = 3,
Handsfree_tag = 4,
Horloge_tag = 5,
Proximity_ISOkaart_geen_magneetstrip =6,
Kenteken = 7,
Handsfree_kaart = 8,
Vingerafdruk = 9,
Telefoonnummer = 10,
}
}

View File

@@ -0,0 +1,21 @@
using System.Diagnostics;
using System.Text;
namespace Aperio_Control_Centre.Export.Paxton
{
public class PaxtonExport
{
public static string CreateExport(List<PaxtonUserModel> users)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("Achternaam;Voornaam;Tussenvoegsel;Kaartnummer;PIN;Afdeling;Autorisatie;Telefoon;Extensie;Mobiel;Activeringsdatum;Verval datum;Straatnaam;Huisnummer;Woonplaats;Land;Postcode;Telefoon privé;E-mail privé;Mobielnummer privé;E-mail;Geboortedatum;Datum in dienst;Personeelsnummer;Aantekeningen;Functie;Gebruikers ID");
foreach (var user in users)
{
user.ToCSV(ref sb);
sb.Append(Environment.NewLine);
}
Debug.WriteLine(sb.ToString());
return sb.ToString();
}
}
}

View File

@@ -0,0 +1,205 @@
using System.Text;
namespace Aperio_Control_Centre.Export.Paxton
{
public class PaxtonUserModel
{
//Required - Text up to 50 characters
public string Surname { get; set; }
//Required - Text up to 50 characters
public string Firstname { get; set; }
//Tekst tot 50 karakters
public string Middlename { get; set; }
//Nummer 1 tot 99999999
public List<PaxtonCardModel> Cards { get; set; } = new List<PaxtonCardModel>();
//Nummer 1 tot 9999
public int PIN { get; set; }
//Tekst tot 50 karakters
public string Department { get; set; }
//Tekst tot 50 karakters
public List<PaxtonAuthorizationModel> AccessLevels { get; set; } = new List<PaxtonAuthorizationModel>();
//Tekst tot 30 karakters
public string Telephone { get; set; }
//Tekst tot 10 karakters
public string Extension { get; set; }
//Tekst tot 30 karakters
public string Mobile { get; set; }
//Datum in de standaard taal formaat, in Nederland is dit DD-MM-JJJJ
public DateTime ActiveDate { get; set; }
//Datum in de standaard taal formaat, in Nederland is dit DD-MM-JJJJ
public DateTime ExpiryDate { get; set; }
//Tekst tot 100 karakters
public string Street { get; set; }
//Tekst tot 100 karakters
public string Nr { get; set; }
//Tekst tot 50 karakters
public string Town { get; set; }
//Tekst tot 50 karakters
public string Country { get; set; }
//Tekst tot 50 karakters
public string Postcode { get; set; }
//Tekst tot 50 karakters
public string HomeTelephone { get; set; }
//Tekst tot 50 karakters
public string HomeEmail { get; set; }
//Tekst tot 50 karakters
public string HomeMobile { get; set; }
//Tekst tot 50 karakters
public string Email { get; set; }
//Tekst tot 50 karakters
public string DateOfBirth { get; set; }
//Tekst tot 50 karakters
public string DateOfEmploment { get; set; }
//Tekst tot 50 karakters
public string PersonnelNumber { get; set; }
//Tekst tot 4096 karakters
public string Notes { get; set; }
//Tekst tot 50 karakters
public string Functie { get; set; }
//Nummer 1 tot 999999
public int UserId { get; set; }
public static (string firstname, string lastname) SplitUsername(string username)
{
if (username.Contains(" "))
{
return (username.Substring(0, username.IndexOf(" ")), username.Substring(username.IndexOf(" ") + 1));
}
return (username, string.Empty);
}
public static DateTime CalculateExpiryDate(DateTime lastChanged, bool active)
{
if (active)
{
return DateTime.MinValue;
}
return lastChanged;
}
public void CardsToCSV(ref StringBuilder sb)
{
//{'Cards':[{'Number':'57732256','Type':'3','Lost':'0'},{'Number':'37262968','Type':'0','Lost':'0'}]}
sb.Append("{'Cards':[");
foreach (var (end, card) in Cards.Enumerate())
{
card.ToCSV(ref sb);
if (!end)
{
sb.Append(",");
}
}
sb.Append("]}");
}
public void AuthorizationsToCSV(ref StringBuilder sb)
{
//{'AccessLevels':[{'Name':'Arbo Unie','Ordinal':'1'}]}
sb.Append("{'AccessLevels':[");
foreach (var (end, auth) in AccessLevels.Enumerate())
{
auth.ToCSV(ref sb);
if (!end)
{
sb.Append(",");
}
}
sb.Append("]}");
}
public void ToCSV(ref StringBuilder sb)
{
//ict;JanWillem;;{'Cards':[{'Number':'19697050','Type':'0','Lost':'0'}]};;Huurder 02 Arbounie;{'AccessLevels':[{'Name':'Arbo Unie', 'Ordinal':'1'}]};;;;2023-jul-14;;;;;;;;;;;;;;;;1581
sb.Append(Surname);
sb.Append(";");
sb.Append(Firstname);
sb.Append(";");
sb.Append(Middlename);
sb.Append(";");
CardsToCSV(ref sb);
sb.Append(";");
if (PIN != 0)
{
sb.Append(PIN);
}
sb.Append(";");
sb.Append(Department);
sb.Append(";");
AuthorizationsToCSV(ref sb);
sb.Append(";");
sb.Append(Telephone);
sb.Append(";");
sb.Append(Extension);
sb.Append(";");
sb.Append(Mobile);
sb.Append(";");
if (ActiveDate.Ticks != 0)
{
sb.Append(ActiveDate.ToString("d-MMM-yyyy"));
}
sb.Append(";");
if (ExpiryDate.Ticks != 0)
{
sb.Append(ExpiryDate.ToString("d-MMM-yyyy"));
}
sb.Append(";");
sb.Append(Street);
sb.Append(";");
sb.Append(Nr);
sb.Append(";");
sb.Append(Town);
sb.Append(";");
sb.Append(Country);
sb.Append(";");
sb.Append(Postcode);
sb.Append(";");
sb.Append(HomeTelephone);
sb.Append(";");
sb.Append(HomeEmail);
sb.Append(";");
sb.Append(HomeMobile);
sb.Append(";");
sb.Append(Email);
sb.Append(";");
sb.Append(DateOfBirth);
sb.Append(";");
sb.Append(DateOfEmploment);
sb.Append(";");
sb.Append(PersonnelNumber);
sb.Append(";");
sb.Append(Notes);
sb.Append(";");
sb.Append(Functie);
sb.Append(";");
sb.Append(UserId);
}
}
}

View File

@@ -41,6 +41,7 @@
<ItemGroup>
<ProjectReference Include="..\Aperio_Control_Centre.Aadp\Aperio_Control_Centre.Aadp.csproj" />
<ProjectReference Include="..\Aperio_Control_Centre.ACSDatabase\Aperio_Control_Centre.ACSDatabase.csproj" />
<ProjectReference Include="..\Aperio_Control_Centre.Export\Aperio_Control_Centre.Export.csproj" />
<ProjectReference Include="..\Aperio_Control_Centre.LeafletBlazor\Aperio_Control_Centre.LeafletBlazor.csproj" />
</ItemGroup>

View File

@@ -1,151 +1,151 @@
using Aperio_Control_Centre.ACSDatabase;
using Aperio_Control_Centre.ACSDatabase.Models;
using Aperio_Control_Centre.ACSDatabase.Types;
using Aperio_Control_Centre.Frontend.Helpers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data;
//using Aperio_Control_Centre.ACSDatabase;
//using Aperio_Control_Centre.ACSDatabase.Models;
//using Aperio_Control_Centre.ACSDatabase.Types;
//using Aperio_Control_Centre.Frontend.Helpers;
//using Microsoft.AspNetCore.Authorization;
//using Microsoft.AspNetCore.Mvc;
//using Microsoft.EntityFrameworkCore;
//using System.Data;
namespace Aperio_Control_Centre.Frontend.Controllers
{
public class DepartmentsController : Controller
{
private readonly IDbContextFactory<ACSDatabaseContext> _contextFactory;
//namespace Aperio_Control_Centre.Frontend.Controllers
//{
// public class DepartmentsController : Controller
// {
// private readonly IDbContextFactory<ACSDatabaseContext> _contextFactory;
public DepartmentsController(IDbContextFactory<ACSDatabaseContext> dbContextFactory)
{
_contextFactory = dbContextFactory;
}
// public DepartmentsController(IDbContextFactory<ACSDatabaseContext> dbContextFactory)
// {
// _contextFactory = dbContextFactory;
// }
// GET: Departments
[HttpGet]
[Authorize(Roles = "Administrator")]
public async Task<ActionResult> Index(string sortOrder)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
IQueryable<Department> departmentlist = db.Departments
.Where(i => i.Active != ActiveStates.Deleted)
.AsNoTracking();
// // GET: Departments
// [HttpGet]
// [Authorize(Roles = "Administrator")]
// public async Task<ActionResult> Index(string sortOrder)
// {
// using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
// IQueryable<Department> departmentlist = db.Departments
// .Where(i => i.Active != ActiveStates.Deleted)
// .AsNoTracking();
Cookies.SetRedirectCookie(Response.Cookies, "Departments", "Index");
return View(await Sorting.SortDepartmentList(sortOrder, departmentlist).ToListAsync());
}
// Cookies.SetRedirectCookie(Response.Cookies, "Departments", "Index");
// return View(await Sorting.SortDepartmentList(sortOrder, departmentlist).ToListAsync());
// }
// GET: Departments/Create
[HttpGet]
[Authorize(Roles = "Administrator")]
public ActionResult Create()
{
return View();
}
// // GET: Departments/Create
// [HttpGet]
// [Authorize(Roles = "Administrator")]
// public ActionResult Create()
// {
// return View();
// }
// POST: Departments/Create
[HttpPost]
[Authorize(Roles = "Administrator")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Department departments)
{
if (ModelState.IsValid)
{
if (departments == null)
{
throw new ArgumentNullException(nameof(departments), "Create Departments, departments is null ");
}
// // POST: Departments/Create
// [HttpPost]
// [Authorize(Roles = "Administrator")]
// [ValidateAntiForgeryToken]
// public async Task<ActionResult> Create(Department departments)
// {
// if (ModelState.IsValid)
// {
// if (departments == null)
// {
// throw new ArgumentNullException(nameof(departments), "Create Departments, departments is null ");
// }
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
departments.LastChanged = DateTime.Now;
departments.Active = ActiveStates.Active;
db.Departments.Add(departments);
AcsLogging.Add(User.Identity, "Afdeling " + departments.Name + " aangemaakt", LogTypes.System, db);
await db.SaveChangesAsync();
// using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
// departments.LastChanged = DateTime.Now;
// departments.Active = ActiveStates.Active;
// db.Departments.Add(departments);
// AcsLogging.Add(User.Identity, "Afdeling " + departments.Name + " aangemaakt", LogTypes.System, db);
// await db.SaveChangesAsync();
return Helpers.Cookies.RedirectToCookie(Request.Cookies);
}
return View(departments);
}
// return Helpers.Cookies.RedirectToCookie(Request.Cookies);
// }
// return View(departments);
// }
// GET: Departments/Edit/5
[HttpGet]
[Authorize(Roles = "Administrator")]
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return BadRequest();
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Department departments = await db.Departments.FindAsync(id);
if (departments == null)
{
return NotFound();
}
return View(departments);
}
// // GET: Departments/Edit/5
// [HttpGet]
// [Authorize(Roles = "Administrator")]
// public async Task<ActionResult> Edit(int? id)
// {
// if (id == null)
// {
// return BadRequest();
// }
// using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
// Department departments = await db.Departments.FindAsync(id);
// if (departments == null)
// {
// return NotFound();
// }
// return View(departments);
// }
// POST: Departments/Edit/5
[HttpPost]
[Authorize(Roles = "Administrator")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(Department departments)
{
if (ModelState.IsValid)
{
if (departments == null)
{
throw new ArgumentNullException(nameof(departments), "Edit Departments, departments is null ");
}
// // POST: Departments/Edit/5
// [HttpPost]
// [Authorize(Roles = "Administrator")]
// [ValidateAntiForgeryToken]
// public async Task<ActionResult> Edit(Department departments)
// {
// if (ModelState.IsValid)
// {
// if (departments == null)
// {
// throw new ArgumentNullException(nameof(departments), "Edit Departments, departments is null ");
// }
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
// using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
departments.LastChanged = DateTime.Now;
departments.Active = ActiveStates.Active;
db.Entry(departments).State = EntityState.Modified;
AcsLogging.Add(User.Identity, "Afdeling " + departments.Name + " bewerkt", LogTypes.System, db);
await db.SaveChangesAsync();
// departments.LastChanged = DateTime.Now;
// departments.Active = ActiveStates.Active;
// db.Entry(departments).State = EntityState.Modified;
// AcsLogging.Add(User.Identity, "Afdeling " + departments.Name + " bewerkt", LogTypes.System, db);
// await db.SaveChangesAsync();
return Cookies.RedirectToCookie(Request.Cookies);
}
return View(departments);
}
// return Cookies.RedirectToCookie(Request.Cookies);
// }
// return View(departments);
// }
// GET: Departments/Delete/5
[HttpGet]
[Authorize(Roles = "Administrator")]
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return BadRequest();
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Department departments = await db.Departments.FindAsync(id);
if (departments == null)
{
return NotFound();
}
return View(departments);
}
// // GET: Departments/Delete/5
// [HttpGet]
// [Authorize(Roles = "Administrator")]
// public async Task<ActionResult> Delete(int? id)
// {
// if (id == null)
// {
// return BadRequest();
// }
// using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
// Department departments = await db.Departments.FindAsync(id);
// if (departments == null)
// {
// return NotFound();
// }
// return View(departments);
// }
// POST: Departments/Delete/5
[HttpPost, ActionName("Delete")]
[Authorize(Roles = "Administrator")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
if (ModelState.IsValid)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
// // POST: Departments/Delete/5
// [HttpPost, ActionName("Delete")]
// [Authorize(Roles = "Administrator")]
// [ValidateAntiForgeryToken]
// public async Task<ActionResult> DeleteConfirmed(int id)
// {
// if (ModelState.IsValid)
// {
// using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Department departments = db.Departments.Find(id);
departments.Active = ActiveStates.Deleted;
db.Entry(departments).State = EntityState.Modified;
AcsLogging.Add(User.Identity, "Afdeling " + departments.Name + " verwijderd", LogTypes.System, db);
await db.SaveChangesAsync();
// Department departments = db.Departments.Find(id);
// departments.Active = ActiveStates.Deleted;
// db.Entry(departments).State = EntityState.Modified;
// AcsLogging.Add(User.Identity, "Afdeling " + departments.Name + " verwijderd", LogTypes.System, db);
// await db.SaveChangesAsync();
return Helpers.Cookies.RedirectToCookie(Request.Cookies);
}
return View();
}
}
}
// return Helpers.Cookies.RedirectToCookie(Request.Cookies);
// }
// return View();
// }
// }
//}

View File

@@ -1,266 +1,266 @@
using Aperio_Control_Centre.ACSDatabase;
using Aperio_Control_Centre.ACSDatabase.Models;
using Aperio_Control_Centre.ACSDatabase.Types;
using Aperio_Control_Centre.Frontend.Helpers;
using Aperio_Control_Centre.Frontend.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data;
using System.Globalization;
using System.Net;
using System.Text.Json;
//using Aperio_Control_Centre.ACSDatabase;
//using Aperio_Control_Centre.ACSDatabase.Models;
//using Aperio_Control_Centre.ACSDatabase.Types;
//using Aperio_Control_Centre.Frontend.Helpers;
//using Aperio_Control_Centre.Frontend.Models;
//using Microsoft.AspNetCore.Authorization;
//using Microsoft.AspNetCore.Mvc;
//using Microsoft.EntityFrameworkCore;
//using System.Data;
//using System.Globalization;
//using System.Net;
//using System.Text.Json;
namespace Aperio_Control_Centre.Frontend.Controllers
{
public class LocationsController : Controller
{
private readonly IDbContextFactory<ACSDatabaseContext> _contextFactory;
//namespace Aperio_Control_Centre.Frontend.Controllers
//{
// public class LocationsController : Controller
// {
// private readonly IDbContextFactory<ACSDatabaseContext> _contextFactory;
public LocationsController(IDbContextFactory<ACSDatabaseContext> dbContextFactory)
{
_contextFactory = dbContextFactory;
}
// public LocationsController(IDbContextFactory<ACSDatabaseContext> dbContextFactory)
// {
// _contextFactory = dbContextFactory;
// }
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public JsonResult Lookup(string Zipcode, string Number)
{
if (Int32.TryParse(new String(Number.Where(Char.IsDigit).ToArray()), out int nr) == false)
{
return Json(new { error = "gebruiker correct huisnummer" });
}
// [HttpGet]
// [Authorize(Roles = "Administrator, DeviceAdmin")]
// public JsonResult Lookup(string Zipcode, string Number)
// {
// if (Int32.TryParse(new String(Number.Where(Char.IsDigit).ToArray()), out int nr) == false)
// {
// return Json(new { error = "gebruiker correct huisnummer" });
// }
string letter = new(Number.Where(Char.IsLetter).ToArray());
// string letter = new(Number.Where(Char.IsLetter).ToArray());
int letterIdx = 0;
if (letter.Length == 1)
{
letterIdx = ((int)char.ToUpper(letter[0])) - 64;
}
if (Zipcode == null)
{
return Json(new { error = "Geen postcode opgegeven" });
}
if (Zipcode.Length > 0)
{
try
{
//https://api.pdok.nl/bzk/locatieserver/search/v3_1/free
// int letterIdx = 0;
// if (letter.Length == 1)
// {
// letterIdx = ((int)char.ToUpper(letter[0])) - 64;
// }
// if (Zipcode == null)
// {
// return Json(new { error = "Geen postcode opgegeven" });
// }
// if (Zipcode.Length > 0)
// {
// try
// {
// //https://api.pdok.nl/bzk/locatieserver/search/v3_1/free
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(new Uri("https://api.pdok.nl/bzk/locatieserver/search/v3_1/free?fq=postcode:" + Zipcode + "&fq=huisnummer:" + nr));
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "GET";
httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
// HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(new Uri("https://api.pdok.nl/bzk/locatieserver/search/v3_1/free?fq=postcode:" + Zipcode + "&fq=huisnummer:" + nr));
// httpWebRequest.ContentType = "application/json; charset=utf-8";
// httpWebRequest.Method = "GET";
// httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
GeoDataRootObject result;
using (StreamReader sr = new(httpWebRequest.GetResponse().GetResponseStream()))
{
result = JsonSerializer.Deserialize<GeoDataRootObject>(sr.ReadToEnd());
}
// GeoDataRootObject result;
// using (StreamReader sr = new(httpWebRequest.GetResponse().GetResponseStream()))
// {
// result = JsonSerializer.Deserialize<GeoDataRootObject>(sr.ReadToEnd());
// }
if (result == null)
{
return Json(new { error = "Deserialize error in response" });
}
// if (result == null)
// {
// return Json(new { error = "Deserialize error in response" });
// }
if (result.Response.NumFound == 1)
{
// ETRS:89 projectie
// WKT string
// "POINT(5.39109 51.49700212)"
// if (result.Response.NumFound == 1)
// {
// // ETRS:89 projectie
// // WKT string
// // "POINT(5.39109 51.49700212)"
//set comma to point
CultureInfo customCulture = (CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
customCulture.NumberFormat.NumberDecimalSeparator = ".";
System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
// //set comma to point
// CultureInfo customCulture = (CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
// customCulture.NumberFormat.NumberDecimalSeparator = ".";
// System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
//DbGeometry point = DbGeometry.FromText(result.Response.Docs.FirstOrDefault().Centroide_ll);
// //DbGeometry point = DbGeometry.FromText(result.Response.Docs.FirstOrDefault().Centroide_ll);
return Json(new
{
//longitude = point.XCoordinate,
//latitude = point.YCoordinate,
// return Json(new
// {
// //longitude = point.XCoordinate,
// //latitude = point.YCoordinate,
Street = result.Response.Docs.FirstOrDefault().StraatNaam,
City = result.Response.Docs.FirstOrDefault().GemeenteNaam,
Province = result.Response.Docs.FirstOrDefault().ProvincieNaam,
Country = "Nederland",
});
}
else
{
return Json(new { error = result.Response.NumFound + " addressen gevonden met deze postcode" });
}
}
catch (Exception e)
{
return Json(new { error = e.Message });
}
}
return Json(new { error = "Geen postcode opgegeven" });
}
// Street = result.Response.Docs.FirstOrDefault().StraatNaam,
// City = result.Response.Docs.FirstOrDefault().GemeenteNaam,
// Province = result.Response.Docs.FirstOrDefault().ProvincieNaam,
// Country = "Nederland",
// });
// }
// else
// {
// return Json(new { error = result.Response.NumFound + " addressen gevonden met deze postcode" });
// }
// }
// catch (Exception e)
// {
// return Json(new { error = e.Message });
// }
// }
// return Json(new { error = "Geen postcode opgegeven" });
// }
// GET: Locations
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin, Viewer")]
public async Task<ActionResult> Index(string sortOrder)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
IQueryable<Location> locationlist = db.Locations
.Where(i => i.Active != ActiveStates.Deleted)
.Include(d => d.Devices)
.AsNoTracking();
// // GET: Locations
// [HttpGet]
// [Authorize(Roles = "Administrator, DeviceAdmin, Viewer")]
// public async Task<ActionResult> Index(string sortOrder)
// {
// using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
// IQueryable<Location> locationlist = db.Locations
// .Where(i => i.Active != ActiveStates.Deleted)
// .Include(d => d.Devices)
// .AsNoTracking();
Cookies.SetRedirectCookie(Response.Cookies, "Locations", "Index");
return View(await Sorting.SortLocationsList(sortOrder, locationlist).ToListAsync());
}
// Cookies.SetRedirectCookie(Response.Cookies, "Locations", "Index");
// return View(await Sorting.SortLocationsList(sortOrder, locationlist).ToListAsync());
// }
//--------------------- View Locations ----------------------------------------------
// GET: Locations/View/5
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public async Task<ActionResult> View(string sortOrder, int? locationId)
{
if (locationId == null)
{
return BadRequest();
}
// //--------------------- View Locations ----------------------------------------------
// // GET: Locations/View/5
// [HttpGet]
// [Authorize(Roles = "Administrator, DeviceAdmin")]
// public async Task<ActionResult> View(string sortOrder, int? locationId)
// {
// if (locationId == null)
// {
// return BadRequest();
// }
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
LocationViewModel locationView = new()
{
Location = await db.Locations.FindAsync(locationId)
};
// using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
// LocationViewModel locationView = new()
// {
// Location = await db.Locations.FindAsync(locationId)
// };
if (locationView.Location == null)
{
return NotFound();
}
locationView.Devices = await Sorting.SortDeviceList(sortOrder, db.Devices.Where(u => u.LocationId == locationView.Location.Id && u.Active != ActiveStates.Deleted)).ToListAsync();
// if (locationView.Location == null)
// {
// return NotFound();
// }
// locationView.Devices = await Sorting.SortDeviceList(sortOrder, db.Devices.Where(u => u.LocationId == locationView.Location.Id && u.Active != ActiveStates.Deleted)).ToListAsync();
return View(locationView);
}
// return View(locationView);
// }
// GET: Locations/Create
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public ActionResult Create()
{
return View(new Location());
}
// // GET: Locations/Create
// [HttpGet]
// [Authorize(Roles = "Administrator, DeviceAdmin")]
// public ActionResult Create()
// {
// return View(new Location());
// }
// POST: Locations/Create
[HttpPost]
[Authorize(Roles = "Administrator, DeviceAdmin")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Location location)
{
if (ModelState.IsValid)
{
if (location == null)
{
throw new ArgumentNullException(nameof(location), "Create Location, location is null.");
}
// // POST: Locations/Create
// [HttpPost]
// [Authorize(Roles = "Administrator, DeviceAdmin")]
// [ValidateAntiForgeryToken]
// public async Task<ActionResult> Create(Location location)
// {
// if (ModelState.IsValid)
// {
// if (location == null)
// {
// throw new ArgumentNullException(nameof(location), "Create Location, location is null.");
// }
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
location.LastChanged = DateTime.Now;
location.Active = ActiveStates.Active;
db.Locations.Add(location);
AcsLogging.Add(User.Identity, "Locatie " + location.AddressString + " aangemaakt", LogTypes.System, db);
await db.SaveChangesAsync();
// using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
// location.LastChanged = DateTime.Now;
// location.Active = ActiveStates.Active;
// db.Locations.Add(location);
// AcsLogging.Add(User.Identity, "Locatie " + location.AddressString + " aangemaakt", LogTypes.System, db);
// await db.SaveChangesAsync();
return Helpers.Cookies.RedirectToCookie(Request.Cookies);
}
return View(location);
}
// return Helpers.Cookies.RedirectToCookie(Request.Cookies);
// }
// return View(location);
// }
// GET: Locations/Edit/5
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return BadRequest();
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Location locations = await db.Locations.FindAsync(id);
if (locations == null)
{
return NotFound();
}
// // GET: Locations/Edit/5
// [HttpGet]
// [Authorize(Roles = "Administrator, DeviceAdmin")]
// public async Task<ActionResult> Edit(int? id)
// {
// if (id == null)
// {
// return BadRequest();
// }
// using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
// Location locations = await db.Locations.FindAsync(id);
// if (locations == null)
// {
// return NotFound();
// }
return View(locations);
}
// return View(locations);
// }
// POST: Locations/Edit/5
[HttpPost]
[Authorize(Roles = "Administrator, DeviceAdmin")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(Location location)
{
if (ModelState.IsValid)
{
if (location == null)
{
throw new ArgumentNullException(nameof(location), "Create Location, location is null.");
}
// // POST: Locations/Edit/5
// [HttpPost]
// [Authorize(Roles = "Administrator, DeviceAdmin")]
// [ValidateAntiForgeryToken]
// public async Task<ActionResult> Edit(Location location)
// {
// if (ModelState.IsValid)
// {
// if (location == null)
// {
// throw new ArgumentNullException(nameof(location), "Create Location, location is null.");
// }
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
location.LastChanged = DateTime.Now;
location.Active = ActiveStates.Active;
db.Entry(location).State = EntityState.Modified;
AcsLogging.Add(User.Identity, "Locatie " + location.AddressString + " bewerkt", LogTypes.System, db);
await db.SaveChangesAsync();
// using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
// location.LastChanged = DateTime.Now;
// location.Active = ActiveStates.Active;
// db.Entry(location).State = EntityState.Modified;
// AcsLogging.Add(User.Identity, "Locatie " + location.AddressString + " bewerkt", LogTypes.System, db);
// await db.SaveChangesAsync();
return Cookies.RedirectToCookie(Request.Cookies);
}
return View(location);
}
// return Cookies.RedirectToCookie(Request.Cookies);
// }
// return View(location);
// }
// GET: Locations/Delete/5
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return BadRequest();
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Location locations = await db.Locations.FindAsync(id);
// // GET: Locations/Delete/5
// [HttpGet]
// [Authorize(Roles = "Administrator, DeviceAdmin")]
// public async Task<ActionResult> Delete(int? id)
// {
// if (id == null)
// {
// return BadRequest();
// }
// using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
// Location locations = await db.Locations.FindAsync(id);
if (locations == null)
{
return NotFound();
}
return View(locations);
}
// if (locations == null)
// {
// return NotFound();
// }
// return View(locations);
// }
// POST: Locations/Delete/5
[HttpPost, ActionName("Delete")]
[Authorize(Roles = "Administrator, DeviceAdmin")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Location location = db.Locations.Find(id);
// // POST: Locations/Delete/5
// [HttpPost, ActionName("Delete")]
// [Authorize(Roles = "Administrator, DeviceAdmin")]
// [ValidateAntiForgeryToken]
// public async Task<ActionResult> DeleteConfirmed(int id)
// {
// using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
// Location location = db.Locations.Find(id);
if (location == null)
{
return BadRequest();
}
// if (location == null)
// {
// return BadRequest();
// }
location.LastChanged = DateTime.Now;
location.Active = ActiveStates.Deleted;
db.Entry(location).State = EntityState.Modified;
AcsLogging.Add(User.Identity, "Locatie " + location.AddressString + " verwijderd", LogTypes.System, db);
await db.SaveChangesAsync();
// location.LastChanged = DateTime.Now;
// location.Active = ActiveStates.Deleted;
// db.Entry(location).State = EntityState.Modified;
// AcsLogging.Add(User.Identity, "Locatie " + location.AddressString + " verwijderd", LogTypes.System, db);
// await db.SaveChangesAsync();
return Cookies.RedirectToCookie(Request.Cookies);
}
}
}
// return Cookies.RedirectToCookie(Request.Cookies);
// }
// }
//}

View File

@@ -1,40 +1,40 @@
using Microsoft.AspNetCore.Identity;
using System.Text;
//using Microsoft.AspNetCore.Identity;
//using System.Text;
namespace Aperio_Control_Centre.Frontend.Helpers
{
public static class AccountHelpers
{
public static string ErrorsAsString(IEnumerable<IdentityError> errors)
{
StringBuilder sb = new();
foreach (var msg in errors)
{
sb.Append(msg.Code);
sb.Append(msg.Description);
sb.Append(Environment.NewLine);
}
return sb.ToString();
}
//namespace Aperio_Control_Centre.Frontend.Helpers
//{
// public static class AccountHelpers
// {
// public static string ErrorsAsString(IEnumerable<IdentityError> errors)
// {
// StringBuilder sb = new();
// foreach (var msg in errors)
// {
// sb.Append(msg.Code);
// sb.Append(msg.Description);
// sb.Append(Environment.NewLine);
// }
// return sb.ToString();
// }
//public static List<SelectListItem> GetRolesList(string id, ACCIdentityDbContext db)
//{
// return db.Roles.Select(x => new SelectListItem()
// {
// //Selected = x.Users.Where(u => u.UserId == id).Any(),
// Text = x.Name,
// Value = x.Name
// }).ToList();
//}
// //public static List<SelectListItem> GetRolesList(string id, ACCIdentityDbContext db)
// //{
// // return db.Roles.Select(x => new SelectListItem()
// // {
// // //Selected = x.Users.Where(u => u.UserId == id).Any(),
// // Text = x.Name,
// // Value = x.Name
// // }).ToList();
// //}
//public static Task<List<SelectListItem>> GetRolesListAsync(string id, ACCIdentityDbContext db)
//{
// return db.Roles.Select(x => new SelectListItem()
// {
// //Selected = x.Users.Where(u => u.UserId == id).Any(),
// Text = x.Name,
// Value = x.Name
// }).ToListAsync();
//}
}
}
// //public static Task<List<SelectListItem>> GetRolesListAsync(string id, ACCIdentityDbContext db)
// //{
// // return db.Roles.Select(x => new SelectListItem()
// // {
// // //Selected = x.Users.Where(u => u.UserId == id).Any(),
// // Text = x.Name,
// // Value = x.Name
// // }).ToListAsync();
// //}
// }
//}

View File

@@ -1,65 +1,65 @@
using Aperio_Control_Centre.ACSDatabase;
using Aperio_Control_Centre.ACSDatabase.Models;
using Microsoft.EntityFrameworkCore;
//using Aperio_Control_Centre.ACSDatabase;
//using Aperio_Control_Centre.ACSDatabase.Models;
//using Microsoft.EntityFrameworkCore;
namespace Aperio_Control_Centre.Frontend.Helpers
{
public static class ConfigurationHelper
{
public static Boolean UseDordrecht
{
get
{
return true;
//namespace Aperio_Control_Centre.Frontend.Helpers
//{
// public static class ConfigurationHelper
// {
// public static Boolean UseDordrecht
// {
// get
// {
// return true;
//System.Configuration.Assemblies.
// //System.Configuration.Assemblies.
//var used = System.Configuration.ConfigurationManager.AppSettings["useDordrecht"];
//if (used == null)
//{
// return false;
//}
//return Convert.ToBoolean(used);
// //var used = System.Configuration.ConfigurationManager.AppSettings["useDordrecht"];
// //if (used == null)
// //{
// // return false;
// //}
// //return Convert.ToBoolean(used);
//var used = System.Configuration.ConfigurationManager.AppSettings["useDordrecht"];
//if (used == null)
//{
// return false;
//}
//return Convert.ToBoolean(used);
}
}
// //var used = System.Configuration.ConfigurationManager.AppSettings["useDordrecht"];
// //if (used == null)
// //{
// // return false;
// //}
// //return Convert.ToBoolean(used);
// }
// }
public static Boolean UseErasmus
{
get
{
return true;
// public static Boolean UseErasmus
// {
// get
// {
// return true;
//var used = System.Configuration.ConfigurationManager.AppSettings["useErasmus"];
//if (used == null)
//{
// return false;
//}
//return Convert.ToBoolean(used);
}
}
// //var used = System.Configuration.ConfigurationManager.AppSettings["useErasmus"];
// //if (used == null)
// //{
// // return false;
// //}
// //return Convert.ToBoolean(used);
// }
// }
public static async Task<DateTime> ErasmusEpocDate(ACSDatabaseContext db)
{
GlobalSetting epoc = await db.GlobalSettings.Where(n => n.Name == "Erasmus Epoc Date").SingleOrDefaultAsync();
if (epoc == null)
{
epoc = new GlobalSetting
{
Name = "Erasmus Epoc Date",
Value = DateTime.Now.ToString("dd-MM-yyyy")
};
db.GlobalSettings.Add(epoc);
await db.SaveChangesAsync();
}
return DateTime.Parse(epoc.Value);
}
}
}
// public static async Task<DateTime> ErasmusEpocDate(ACSDatabaseContext db)
// {
// GlobalSetting epoc = await db.GlobalSettings.Where(n => n.Name == "Erasmus Epoc Date").SingleOrDefaultAsync();
// if (epoc == null)
// {
// epoc = new GlobalSetting
// {
// Name = "Erasmus Epoc Date",
// Value = DateTime.Now.ToString("dd-MM-yyyy")
// };
// db.GlobalSettings.Add(epoc);
// await db.SaveChangesAsync();
// }
// return DateTime.Parse(epoc.Value);
// }
// }
//}

View File

@@ -1,76 +1,76 @@
using Microsoft.AspNetCore.Mvc;
//using Microsoft.AspNetCore.Mvc;
namespace Aperio_Control_Centre.Frontend.Helpers
{
public static class Cookies
{
public static void SetRedirectCookie(IResponseCookies cookies, String controller, String action)
{
if (cookies == null)
{
throw new ArgumentNullException(nameof(cookies), "SetRedirectCookie, cookies is null");
}
//namespace Aperio_Control_Centre.Frontend.Helpers
//{
// public static class Cookies
// {
// public static void SetRedirectCookie(IResponseCookies cookies, String controller, String action)
// {
// if (cookies == null)
// {
// throw new ArgumentNullException(nameof(cookies), "SetRedirectCookie, cookies is null");
// }
cookies.Append("Controller", controller);
// cookies.Append("Controller", controller);
//responseBase.Cookies["Controller"].Value = controller;
//responseBase.Cookies["Controller"].Secure = true;
//responseBase.Cookies["Controller"].SameSite = SameSiteMode.Strict;
// //responseBase.Cookies["Controller"].Value = controller;
// //responseBase.Cookies["Controller"].Secure = true;
// //responseBase.Cookies["Controller"].SameSite = SameSiteMode.Strict;
cookies.Append("Action", action);
// cookies.Append("Action", action);
//responseBase.Cookies["Action"].Value = action;
//responseBase.Cookies["Action"].Secure = true;
//responseBase.Cookies["Action"].SameSite = SameSiteMode.Strict;
}
// //responseBase.Cookies["Action"].Value = action;
// //responseBase.Cookies["Action"].Secure = true;
// //responseBase.Cookies["Action"].SameSite = SameSiteMode.Strict;
// }
public static void SetSortorderCookie(IResponseCookies cookies, String page, String order)
{
if (cookies == null)
{
throw new ArgumentNullException(nameof(cookies), "SetSortorderCookie, cookies is null");
}
// public static void SetSortorderCookie(IResponseCookies cookies, String page, String order)
// {
// if (cookies == null)
// {
// throw new ArgumentNullException(nameof(cookies), "SetSortorderCookie, cookies is null");
// }
cookies.Append(page, order);
// cookies.Append(page, order);
//responseBase.Cookies[page].Value = order;
//responseBase.Cookies[page].Secure = true;
//responseBase.Cookies[page].SameSite = SameSiteMode.Strict;
}
// //responseBase.Cookies[page].Value = order;
// //responseBase.Cookies[page].Secure = true;
// //responseBase.Cookies[page].SameSite = SameSiteMode.Strict;
// }
public static RedirectToRouteResult RedirectToCookie(IRequestCookieCollection cookies)
{
if (cookies == null)
{
throw new ArgumentNullException(nameof(cookies), "RedirectToCookie, cookies is null");
}
// public static RedirectToRouteResult RedirectToCookie(IRequestCookieCollection cookies)
// {
// if (cookies == null)
// {
// throw new ArgumentNullException(nameof(cookies), "RedirectToCookie, cookies is null");
// }
if (!cookies.ContainsKey("Action") || !cookies.ContainsKey("Controller"))
{
return new RedirectToRouteResult(new RouteValueDictionary(new { action = "Index", controller = "Home" }));
}
//if (cookies.AllKeys.Contains("Action") == false || cookies.AllKeys.Contains("Controller") == false)
//{
// return new RedirectToRouteResult(new RouteValueDictionary(new { action = "Index", controller = "Home" }));
//}
return new RedirectToRouteResult(new RouteValueDictionary(new { action = cookies["Action"], controller = cookies["Controller"] }));
}
// if (!cookies.ContainsKey("Action") || !cookies.ContainsKey("Controller"))
// {
// return new RedirectToRouteResult(new RouteValueDictionary(new { action = "Index", controller = "Home" }));
// }
// //if (cookies.AllKeys.Contains("Action") == false || cookies.AllKeys.Contains("Controller") == false)
// //{
// // return new RedirectToRouteResult(new RouteValueDictionary(new { action = "Index", controller = "Home" }));
// //}
// return new RedirectToRouteResult(new RouteValueDictionary(new { action = cookies["Action"], controller = cookies["Controller"] }));
// }
public static void SetPageListSizeCookie(IResponseCookies cookies, int pagesize)
{
if (cookies == null)
{
throw new ArgumentNullException(nameof(cookies), "SetSortorderCookie, cookies is null");
}
cookies.Append("pageSize", pagesize.ToString());
// public static void SetPageListSizeCookie(IResponseCookies cookies, int pagesize)
// {
// if (cookies == null)
// {
// throw new ArgumentNullException(nameof(cookies), "SetSortorderCookie, cookies is null");
// }
// cookies.Append("pageSize", pagesize.ToString());
//responseBase.Cookies["pageSize"].Value = pagesize.ToString();
//responseBase.Cookies["pageSize"].Secure = true;
//responseBase.Cookies["pageSize"].SameSite = SameSiteMode.Strict;
// //responseBase.Cookies["pageSize"].Value = pagesize.ToString();
// //responseBase.Cookies["pageSize"].Secure = true;
// //responseBase.Cookies["pageSize"].SameSite = SameSiteMode.Strict;
}
}
}
// }
// }
//}

View File

@@ -1,21 +1,21 @@
using System.ComponentModel.DataAnnotations;
using System.Reflection;
//using System.ComponentModel.DataAnnotations;
//using System.Reflection;
namespace Aperio_Control_Centre.Frontend
{
public static class EnumHelper
{
public static string GetDisplayName(this Enum enumValue)
{
if (enumValue == null)
{
throw new ArgumentNullException(nameof(enumValue), "GetDisplayName EnumHelper, enumValue is null.");
}
//namespace Aperio_Control_Centre.Frontend
//{
// public static class EnumHelper
// {
// public static string GetDisplayName(this Enum enumValue)
// {
// if (enumValue == null)
// {
// throw new ArgumentNullException(nameof(enumValue), "GetDisplayName EnumHelper, enumValue is null.");
// }
return enumValue.GetType().GetMember(enumValue.ToString())
.First()
.GetCustomAttribute<DisplayAttribute>()
.Name;
}
}
}
// return enumValue.GetType().GetMember(enumValue.ToString())
// .First()
// .GetCustomAttribute<DisplayAttribute>()
// .Name;
// }
// }
//}

View File

@@ -1,95 +1,95 @@
using Aperio_Control_Centre.ACSDatabase;
using Aperio_Control_Centre.ACSDatabase.Models;
using Aperio_Control_Centre.ACSDatabase.Types;
using Microsoft.EntityFrameworkCore;
using System.Security.Principal;
//using Aperio_Control_Centre.ACSDatabase;
//using Aperio_Control_Centre.ACSDatabase.Models;
//using Aperio_Control_Centre.ACSDatabase.Types;
//using Microsoft.EntityFrameworkCore;
//using System.Security.Principal;
namespace Aperio_Control_Centre.Frontend.Helpers
{
public static class AcsLogging
{
public static void Add(IIdentity identity, String msg, LogTypes logType, ACSDatabaseContext db)
{
if (identity == null)
{
throw new ArgumentNullException(nameof(identity), "Logging.Add() - identity is null");
}
//namespace Aperio_Control_Centre.Frontend.Helpers
//{
// public static class AcsLogging
// {
// public static void Add(IIdentity identity, String msg, LogTypes logType, ACSDatabaseContext db)
// {
// if (identity == null)
// {
// throw new ArgumentNullException(nameof(identity), "Logging.Add() - identity is null");
// }
Logging log = new()
{
Time = DateTime.Now,
UserName = identity.Name,
Message = msg,
LogType = logType
};
db.Loggings.Add(log);
}
// Logging log = new()
// {
// Time = DateTime.Now,
// UserName = identity.Name,
// Message = msg,
// LogType = logType
// };
// db.Loggings.Add(log);
// }
public static void Add(IIdentity identity, String msg, LogTypes logType, User user, ACSDatabaseContext db)
{
if (identity == null)
{
throw new ArgumentNullException(nameof(identity), "Logging.Add(user) - identity is null");
}
if (user == null)
{
throw new ArgumentNullException(nameof(user), "Logging.Add(user) - user is null");
}
// public static void Add(IIdentity identity, String msg, LogTypes logType, User user, ACSDatabaseContext db)
// {
// if (identity == null)
// {
// throw new ArgumentNullException(nameof(identity), "Logging.Add(user) - identity is null");
// }
// if (user == null)
// {
// throw new ArgumentNullException(nameof(user), "Logging.Add(user) - user is null");
// }
Logging log = new()
{
Time = DateTime.Now,
UserName = identity.Name,
Message = msg,
LogType = logType,
CredentialString = user.CredentialString,
CredentialType = user.CredentialType,
UserId = user.Id
};
db.Loggings.Add(log);
}
// Logging log = new()
// {
// Time = DateTime.Now,
// UserName = identity.Name,
// Message = msg,
// LogType = logType,
// CredentialString = user.CredentialString,
// CredentialType = user.CredentialType,
// UserId = user.Id
// };
// db.Loggings.Add(log);
// }
public static void Add(IIdentity identity, String msg, LogTypes logType, Device device, ACSDatabaseContext db)
{
if (identity == null)
{
throw new ArgumentNullException(nameof(identity), "Logging.Add(device) - identity is null");
}
if (device == null)
{
throw new ArgumentNullException(nameof(device), "Logging.Add(device) - device is null");
}
// public static void Add(IIdentity identity, String msg, LogTypes logType, Device device, ACSDatabaseContext db)
// {
// if (identity == null)
// {
// throw new ArgumentNullException(nameof(identity), "Logging.Add(device) - identity is null");
// }
// if (device == null)
// {
// throw new ArgumentNullException(nameof(device), "Logging.Add(device) - device is null");
// }
Logging log = new()
{
Time = DateTime.Now,
UserName = identity.Name,
Message = msg,
LogType = logType,
DeviceId = device.Id
};
db.Loggings.Add(log);
}
// Logging log = new()
// {
// Time = DateTime.Now,
// UserName = identity.Name,
// Message = msg,
// LogType = logType,
// DeviceId = device.Id
// };
// db.Loggings.Add(log);
// }
public static Task<List<Logging>> LastUserLoggings(User user, int count, ACSDatabaseContext db)
{
return db.Loggings
.Where(l => l.UserId == user.Id)
.OrderByDescending(t => t.Time)
.Take(count)
.Include(d => d.Device)
.Include(d => d.Device.Location)
.ToListAsync();
}
// public static Task<List<Logging>> LastUserLoggings(User user, int count, ACSDatabaseContext db)
// {
// return db.Loggings
// .Where(l => l.UserId == user.Id)
// .OrderByDescending(t => t.Time)
// .Take(count)
// .Include(d => d.Device)
// .Include(d => d.Device.Location)
// .ToListAsync();
// }
public static Task<List<Logging>> LastDeviceLoggings(Device device, int count, ACSDatabaseContext db)
{
return db.Loggings
.Where(l => l.DeviceId == device.Id)
.OrderByDescending(t => t.Time)
.Take(count)
.Include(d => d.User)
.ToListAsync();
}
}
}
// public static Task<List<Logging>> LastDeviceLoggings(Device device, int count, ACSDatabaseContext db)
// {
// return db.Loggings
// .Where(l => l.DeviceId == device.Id)
// .OrderByDescending(t => t.Time)
// .Take(count)
// .Include(d => d.User)
// .ToListAsync();
// }
// }
//}

View File

@@ -1,138 +1,138 @@
using Aperio_Control_Centre.ACSDatabase.Models;
using Aperio_Control_Centre.ACSDatabase.Types;
//using Aperio_Control_Centre.ACSDatabase.Models;
//using Aperio_Control_Centre.ACSDatabase.Types;
namespace Aperio_Control_Centre.Frontend.Helpers
{
public static class Sorting
{
public static IQueryable<Device> SortDeviceList(string sortOrder, IQueryable<Device> devicelist)
{
if (sortOrder != null)
{
devicelist = sortOrder switch
{
"devid_asc" => devicelist.OrderBy(s => s.DeviceId),
"devid_desc" => devicelist.OrderByDescending(s => s.DeviceId),
"name_asc" => devicelist.OrderBy(s => s.Name),
"name_desc" => devicelist.OrderByDescending(s => s.Name),
"loc_asc" => devicelist.Where(l => l.LocationId != null).OrderBy(s => s.Location.ShortAddressString).Concat(devicelist.Where(l => l.LocationId == null)),
"loc_desc" => devicelist.Where(l => l.LocationId != null).OrderByDescending(s => s.Location.ShortAddressString).Concat(devicelist.Where(l => l.LocationId == null)),
"hubid_asc" => devicelist.OrderBy(s => s.HubId),
"hubid_desc" => devicelist.OrderByDescending(s => s.HubId),
"ipaddress_asc" => devicelist.OrderBy(s => s.Ipaddress),
"ipaddress_desc" => devicelist.OrderByDescending(s => s.Ipaddress),
"batt_asc" => devicelist.OrderBy(s => s.BatteryState),
"batt_desc" => devicelist.OrderByDescending(s => s.BatteryState),
"conn_asc" => devicelist.OrderBy(s => s.ConnectionState),
"conn_desc" => devicelist.OrderByDescending(s => s.ConnectionState),
"status_asc" => devicelist.OrderBy(s => s.DoorState),
"status_desc" => devicelist.OrderByDescending(s => s.DoorState),
_ => devicelist.OrderBy(s => s.Id),
};
}
return devicelist;
}
//namespace Aperio_Control_Centre.Frontend.Helpers
//{
// public static class Sorting
// {
// public static IQueryable<Device> SortDeviceList(string sortOrder, IQueryable<Device> devicelist)
// {
// if (sortOrder != null)
// {
// devicelist = sortOrder switch
// {
// "devid_asc" => devicelist.OrderBy(s => s.DeviceId),
// "devid_desc" => devicelist.OrderByDescending(s => s.DeviceId),
// "name_asc" => devicelist.OrderBy(s => s.Name),
// "name_desc" => devicelist.OrderByDescending(s => s.Name),
// "loc_asc" => devicelist.Where(l => l.LocationId != null).OrderBy(s => s.Location.ShortAddressString).Concat(devicelist.Where(l => l.LocationId == null)),
// "loc_desc" => devicelist.Where(l => l.LocationId != null).OrderByDescending(s => s.Location.ShortAddressString).Concat(devicelist.Where(l => l.LocationId == null)),
// "hubid_asc" => devicelist.OrderBy(s => s.HubId),
// "hubid_desc" => devicelist.OrderByDescending(s => s.HubId),
// "ipaddress_asc" => devicelist.OrderBy(s => s.Ipaddress),
// "ipaddress_desc" => devicelist.OrderByDescending(s => s.Ipaddress),
// "batt_asc" => devicelist.OrderBy(s => s.BatteryState),
// "batt_desc" => devicelist.OrderByDescending(s => s.BatteryState),
// "conn_asc" => devicelist.OrderBy(s => s.ConnectionState),
// "conn_desc" => devicelist.OrderByDescending(s => s.ConnectionState),
// "status_asc" => devicelist.OrderBy(s => s.DoorState),
// "status_desc" => devicelist.OrderByDescending(s => s.DoorState),
// _ => devicelist.OrderBy(s => s.Id),
// };
// }
// return devicelist;
// }
public static List<Device> SortDeviceList(string sortOrder, List<Device> devicelist)
{
if (sortOrder != null)
{
devicelist = sortOrder switch
{
"devid_asc" => devicelist.OrderBy(s => s.DeviceId).ToList(),
"devid_desc" => devicelist.OrderByDescending(s => s.DeviceId).ToList(),
"name_asc" => devicelist.OrderBy(s => s.Name).ToList(),
"name_desc" => devicelist.OrderByDescending(s => s.Name).ToList(),
"loc_asc" => devicelist.Where(l => l.LocationId != null).OrderBy(s => s.Location.ShortAddressString).Concat(devicelist.Where(l => l.LocationId == null)).ToList(),
"loc_desc" => devicelist.Where(l => l.LocationId != null).OrderByDescending(s => s.Location.ShortAddressString).Concat(devicelist.Where(l => l.LocationId == null)).ToList(),
"hubid_asc" => devicelist.OrderBy(s => s.HubId).ToList(),
"hubid_desc" => devicelist.OrderByDescending(s => s.HubId).ToList(),
"ipaddress_asc" => devicelist.OrderBy(s => s.Ipaddress).ToList(),
"ipaddress_desc" => devicelist.OrderByDescending(s => s.Ipaddress).ToList(),
"batt_asc" => devicelist.OrderBy(s => s.BatteryState).ToList(),
"batt_desc" => devicelist.OrderByDescending(s => s.BatteryState).ToList(),
"conn_asc" => devicelist.OrderBy(s => s.ConnectionState).ToList(),
"conn_desc" => devicelist.OrderByDescending(s => s.ConnectionState).ToList(),
"status_asc" => devicelist.OrderBy(s => s.DoorState).ToList(),
"status_desc" => devicelist.OrderByDescending(s => s.DoorState).ToList(),
_ => devicelist.OrderBy(s => s.Id).ToList(),
};
}
return devicelist;
}
// public static List<Device> SortDeviceList(string sortOrder, List<Device> devicelist)
// {
// if (sortOrder != null)
// {
// devicelist = sortOrder switch
// {
// "devid_asc" => devicelist.OrderBy(s => s.DeviceId).ToList(),
// "devid_desc" => devicelist.OrderByDescending(s => s.DeviceId).ToList(),
// "name_asc" => devicelist.OrderBy(s => s.Name).ToList(),
// "name_desc" => devicelist.OrderByDescending(s => s.Name).ToList(),
// "loc_asc" => devicelist.Where(l => l.LocationId != null).OrderBy(s => s.Location.ShortAddressString).Concat(devicelist.Where(l => l.LocationId == null)).ToList(),
// "loc_desc" => devicelist.Where(l => l.LocationId != null).OrderByDescending(s => s.Location.ShortAddressString).Concat(devicelist.Where(l => l.LocationId == null)).ToList(),
// "hubid_asc" => devicelist.OrderBy(s => s.HubId).ToList(),
// "hubid_desc" => devicelist.OrderByDescending(s => s.HubId).ToList(),
// "ipaddress_asc" => devicelist.OrderBy(s => s.Ipaddress).ToList(),
// "ipaddress_desc" => devicelist.OrderByDescending(s => s.Ipaddress).ToList(),
// "batt_asc" => devicelist.OrderBy(s => s.BatteryState).ToList(),
// "batt_desc" => devicelist.OrderByDescending(s => s.BatteryState).ToList(),
// "conn_asc" => devicelist.OrderBy(s => s.ConnectionState).ToList(),
// "conn_desc" => devicelist.OrderByDescending(s => s.ConnectionState).ToList(),
// "status_asc" => devicelist.OrderBy(s => s.DoorState).ToList(),
// "status_desc" => devicelist.OrderByDescending(s => s.DoorState).ToList(),
// _ => devicelist.OrderBy(s => s.Id).ToList(),
// };
// }
// return devicelist;
// }
public static IQueryable<User> SortUserList(string sortOrder, IQueryable<User> userlist)
{
if (sortOrder != null)
{
userlist = sortOrder switch
{
"uid_asc" => userlist.OrderBy(s => s.CredentialString),
"uid_desc" => userlist.OrderByDescending(s => s.CredentialString),
"pass_asc" => userlist.OrderBy(s => s.PassNumber),
"pass_desc" => userlist.OrderByDescending(s => s.PassNumber),
"name_asc" => userlist.OrderBy(s => s.Name),
"name_desc" => userlist.OrderByDescending(s => s.Name),
"group_asc" => userlist.Where(s => s.GroupId != null).OrderBy(s => s.Group.Name).Concat(userlist.Where(g => g.GroupId == null)),
"group_desc" => userlist.Where(s => s.GroupId != null).OrderByDescending(s => s.Group.Name).Concat(userlist.Where(g => g.Group == null)),
"department_asc" => userlist.Where(s => s.DepartmentId != null).OrderBy(s => s.Department.Name).Concat(userlist.Where(g => g.DepartmentId == null)),
"department_desc" => userlist.Where(s => s.DepartmentId != null).OrderByDescending(s => s.Department.Name).Concat(userlist.Where(g => g.DepartmentId == null)),
"credtype_asc" => userlist.OrderBy(s => s.CredentialType),
"credtype_desc" => userlist.OrderByDescending(s => s.CredentialType),
"changed_asc" => userlist.OrderBy(s => s.LastChanged),
"changed_desc" => userlist.OrderByDescending(s => s.LastChanged),
"created_asc" => userlist.OrderBy(s => s.Created),
"created_desc" => userlist.OrderByDescending(s => s.Created),
"subline_asc" => userlist.OrderBy(s => s.SubLine),
"subline_desc" => userlist.OrderByDescending(s => s.SubLine),
"dordrecht_asc" => userlist.OrderBy(s => s.Dordrecht),
"dordrecht_desc" => userlist.OrderByDescending(s => s.Dordrecht),
_ => userlist.OrderBy(s => s.Id),
};
}
return userlist;
}
// public static IQueryable<User> SortUserList(string sortOrder, IQueryable<User> userlist)
// {
// if (sortOrder != null)
// {
// userlist = sortOrder switch
// {
// "uid_asc" => userlist.OrderBy(s => s.CredentialString),
// "uid_desc" => userlist.OrderByDescending(s => s.CredentialString),
// "pass_asc" => userlist.OrderBy(s => s.PassNumber),
// "pass_desc" => userlist.OrderByDescending(s => s.PassNumber),
// "name_asc" => userlist.OrderBy(s => s.Name),
// "name_desc" => userlist.OrderByDescending(s => s.Name),
// "group_asc" => userlist.Where(s => s.GroupId != null).OrderBy(s => s.Group.Name).Concat(userlist.Where(g => g.GroupId == null)),
// "group_desc" => userlist.Where(s => s.GroupId != null).OrderByDescending(s => s.Group.Name).Concat(userlist.Where(g => g.Group == null)),
// "department_asc" => userlist.Where(s => s.DepartmentId != null).OrderBy(s => s.Department.Name).Concat(userlist.Where(g => g.DepartmentId == null)),
// "department_desc" => userlist.Where(s => s.DepartmentId != null).OrderByDescending(s => s.Department.Name).Concat(userlist.Where(g => g.DepartmentId == null)),
// "credtype_asc" => userlist.OrderBy(s => s.CredentialType),
// "credtype_desc" => userlist.OrderByDescending(s => s.CredentialType),
// "changed_asc" => userlist.OrderBy(s => s.LastChanged),
// "changed_desc" => userlist.OrderByDescending(s => s.LastChanged),
// "created_asc" => userlist.OrderBy(s => s.Created),
// "created_desc" => userlist.OrderByDescending(s => s.Created),
// "subline_asc" => userlist.OrderBy(s => s.SubLine),
// "subline_desc" => userlist.OrderByDescending(s => s.SubLine),
// "dordrecht_asc" => userlist.OrderBy(s => s.Dordrecht),
// "dordrecht_desc" => userlist.OrderByDescending(s => s.Dordrecht),
// _ => userlist.OrderBy(s => s.Id),
// };
// }
// return userlist;
// }
public static IQueryable<Department> SortDepartmentList(string sortOrder, IQueryable<Department> departmentlist)
{
if (sortOrder != null)
{
departmentlist = sortOrder switch
{
"name_asc" => departmentlist.OrderBy(s => s.Name),
"name_desc" => departmentlist.OrderByDescending(s => s.Name),
"info_asc" => departmentlist.OrderBy(s => s.Info),
"info_desc" => departmentlist.OrderByDescending(s => s.Info),
_ => departmentlist.OrderBy(s => s.Id),
};
}
return departmentlist;
}
// public static IQueryable<Department> SortDepartmentList(string sortOrder, IQueryable<Department> departmentlist)
// {
// if (sortOrder != null)
// {
// departmentlist = sortOrder switch
// {
// "name_asc" => departmentlist.OrderBy(s => s.Name),
// "name_desc" => departmentlist.OrderByDescending(s => s.Name),
// "info_asc" => departmentlist.OrderBy(s => s.Info),
// "info_desc" => departmentlist.OrderByDescending(s => s.Info),
// _ => departmentlist.OrderBy(s => s.Id),
// };
// }
// return departmentlist;
// }
public static IQueryable<Location> SortLocationsList(string sortOrder, IQueryable<Location> locationlist)
{
if (sortOrder != null)
{
locationlist = sortOrder switch
{
"street_asc" => locationlist.OrderBy(s => s.Street),
"street_desc" => locationlist.OrderByDescending(s => s.Street),
"nr_asc" => locationlist.OrderBy(s => s.Nr),
"nr_desc" => locationlist.OrderByDescending(s => s.Nr),
"city_asc" => locationlist.OrderBy(s => s.City),
"city_desc" => locationlist.OrderByDescending(s => s.City),
"zipcode_asc" => locationlist.OrderBy(s => s.Zipcode),
"zipcode_desc" => locationlist.OrderByDescending(s => s.Zipcode),
"prov_asc" => locationlist.OrderBy(s => s.Province),
"prov_desc" => locationlist.OrderByDescending(s => s.Province),
"country_asc" => locationlist.OrderBy(s => s.Country),
"country_desc" => locationlist.OrderByDescending(s => s.Country),
"devcount_asc" => locationlist.OrderBy(s => s.Devices.Where(l => l.Active != ActiveStates.Deleted).Count()),
"devcount_desc" => locationlist.OrderByDescending(s => s.Devices.Where(l => l.Active != ActiveStates.Deleted).Count()),
_ => locationlist.OrderBy(s => s.Id),
};
}
return locationlist;
}
}
}
// public static IQueryable<Location> SortLocationsList(string sortOrder, IQueryable<Location> locationlist)
// {
// if (sortOrder != null)
// {
// locationlist = sortOrder switch
// {
// "street_asc" => locationlist.OrderBy(s => s.Street),
// "street_desc" => locationlist.OrderByDescending(s => s.Street),
// "nr_asc" => locationlist.OrderBy(s => s.Nr),
// "nr_desc" => locationlist.OrderByDescending(s => s.Nr),
// "city_asc" => locationlist.OrderBy(s => s.City),
// "city_desc" => locationlist.OrderByDescending(s => s.City),
// "zipcode_asc" => locationlist.OrderBy(s => s.Zipcode),
// "zipcode_desc" => locationlist.OrderByDescending(s => s.Zipcode),
// "prov_asc" => locationlist.OrderBy(s => s.Province),
// "prov_desc" => locationlist.OrderByDescending(s => s.Province),
// "country_asc" => locationlist.OrderBy(s => s.Country),
// "country_desc" => locationlist.OrderByDescending(s => s.Country),
// "devcount_asc" => locationlist.OrderBy(s => s.Devices.Where(l => l.Active != ActiveStates.Deleted).Count()),
// "devcount_desc" => locationlist.OrderByDescending(s => s.Devices.Where(l => l.Active != ActiveStates.Deleted).Count()),
// _ => locationlist.OrderBy(s => s.Id),
// };
// }
// return locationlist;
// }
// }
//}

View File

@@ -1,49 +1,49 @@
using System.Management;
//using System.Management;
namespace Aperio_Control_Centre.Frontend.Helpers
{
public static class SystemInformationHelper
{
public static string GetProcessorProperty(string property)
{
try
{
using ManagementObjectSearcher searcher = new($"SELECT {property} FROM Win32_Processor");
foreach (ManagementObject item in searcher.Get().Cast<ManagementObject>())
{
object obj = item[property];
switch (Type.GetTypeCode(obj.GetType()))
{
case TypeCode.String:
return (string)obj;
case TypeCode.UInt32:
return ((UInt32)obj).ToString();
}
}
return string.Empty;
}
catch (Exception)
{
return "Not found";
}
}
//namespace Aperio_Control_Centre.Frontend.Helpers
//{
// public static class SystemInformationHelper
// {
// public static string GetProcessorProperty(string property)
// {
// try
// {
// using ManagementObjectSearcher searcher = new($"SELECT {property} FROM Win32_Processor");
// foreach (ManagementObject item in searcher.Get().Cast<ManagementObject>())
// {
// object obj = item[property];
// switch (Type.GetTypeCode(obj.GetType()))
// {
// case TypeCode.String:
// return (string)obj;
// case TypeCode.UInt32:
// return ((UInt32)obj).ToString();
// }
// }
// return string.Empty;
// }
// catch (Exception)
// {
// return "Not found";
// }
// }
public static string GetMemoryProperty(string property)
{
try
{
UInt64 total = 0;
using ManagementObjectSearcher searcher = new($"SELECT {property} FROM Win32_OperatingSystem");
foreach (ManagementObject objects in searcher.Get().Cast<ManagementObject>())
{
total = (UInt64)objects[property];
}
return $"{total / 1024} MB";
}
catch (Exception)
{
return "Not found";
}
}
}
}
// public static string GetMemoryProperty(string property)
// {
// try
// {
// UInt64 total = 0;
// using ManagementObjectSearcher searcher = new($"SELECT {property} FROM Win32_OperatingSystem");
// foreach (ManagementObject objects in searcher.Get().Cast<ManagementObject>())
// {
// total = (UInt64)objects[property];
// }
// return $"{total / 1024} MB";
// }
// catch (Exception)
// {
// return "Not found";
// }
// }
// }
//}

View File

@@ -107,10 +107,10 @@
<li>@Html.ActionLink("Passen export", "ExportUsers", "Export")</li>
<li>@Html.ActionLink("Apparaten export", "ExportDevices", "Export")</li>
<li>@Html.ActionLink("Logging export", "ExportLogging", "Export")</li>
@if (Aperio_Control_Centre.Frontend.Helpers.ConfigurationHelper.UseDordrecht)
@* @if (Aperio_Control_Centre.Frontend.Helpers.ConfigurationHelper.UseDordrecht)
{
<li>@Html.ActionLink("Dordrecht export", "ExportDordrecht", "Export")</li>
}
} *@
</ul>
</li>
}

View File

@@ -62,7 +62,7 @@
@Html.DisplayFor(model => model.Group.Name)
</dd>
@if (Aperio_Control_Centre.Frontend.Helpers.ConfigurationHelper.UseDordrecht)
@* @if (Aperio_Control_Centre.Frontend.Helpers.ConfigurationHelper.UseDordrecht)
{
<dt>
@Html.DisplayNameFor(model => model.Dordrecht)
@@ -70,7 +70,7 @@
<dd>
@Html.CheckBox("Dordrecht", Model.Dordrecht ?? false, new { @disabled = "disabled" })
</dd>
}
} *@
<dt>
@Html.DisplayNameFor(model => model.Info)

View File

@@ -62,7 +62,7 @@
@Html.DisplayFor(model => model.Group.Name)
</dd>
@if (Aperio_Control_Centre.Frontend.Helpers.ConfigurationHelper.UseDordrecht)
@* @if (Aperio_Control_Centre.Frontend.Helpers.ConfigurationHelper.UseDordrecht)
{
<dt>
@Html.DisplayNameFor(model => model.Dordrecht)
@@ -70,7 +70,7 @@
<dd>
@Html.CheckBox("Dordrecht", Model.Dordrecht ?? false, new { @disabled = "disabled" })
</dd>
}
} *@
<dt>
@Html.DisplayNameFor(model => model.Info)

View File

@@ -62,7 +62,7 @@
@Html.DisplayFor(model => model.Group.Name)
</dd>
@if (Aperio_Control_Centre.Frontend.Helpers.ConfigurationHelper.UseDordrecht)
@* @if (Aperio_Control_Centre.Frontend.Helpers.ConfigurationHelper.UseDordrecht)
{
<dt>
@Html.DisplayNameFor(model => model.Dordrecht)
@@ -70,7 +70,7 @@
<dd>
@Html.CheckBox("Dordrecht", Model.Dordrecht ?? false, new { @disabled = "disabled" })
</dd>
}
} *@
<dt>
@Html.DisplayNameFor(model => model.Info)

View File

@@ -0,0 +1,147 @@
using Aperio_Control_Centre.ACSDatabase;
using Aperio_Control_Centre.ACSDatabase.Models;
using Aperio_Control_Centre.ACSDatabase.Types;
using Aperio_Control_Centre.Helpers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data;
using System.Net;
namespace Aperio_Control_Centre.Controllers
{
public class DepartmentsController(IDbContextFactory<ACSDatabaseContext> dbContextFactory) : Controller
{
private readonly IDbContextFactory<ACSDatabaseContext> _contextFactory = dbContextFactory;
// GET: Departments
[HttpGet]
[Authorize(Roles = "Administrator")]
public async Task<ActionResult> Index(string sortOrder)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
IQueryable<Department> departmentlist = db.Departments
.Where(i => i.Active != ActiveStates.Deleted)
.AsNoTracking();
Cookies.SetRedirectCookie(Response.Cookies, "Departments", "Index");
return View(await Sorting.SortDepartmentList(sortOrder, departmentlist).ToListAsync());
}
// GET: Departments/Create
[HttpGet]
[Authorize(Roles = "Administrator")]
public ActionResult Create()
{
return View();
}
// POST: Departments/Create
[HttpPost]
[Authorize(Roles = "Administrator")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Department departments)
{
if (ModelState.IsValid)
{
if (departments == null)
{
throw new ArgumentNullException(nameof(departments), "Create Departments, departments is null ");
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
departments.LastChanged = DateTime.Now;
departments.Active = ActiveStates.Active;
db.Departments.Add(departments);
AcsLogging.Add(User.Identity, "Afdeling " + departments.Name + " aangemaakt", LogTypes.System, db);
await db.SaveChangesAsync();
return Helpers.Cookies.RedirectToCookie(Request.Cookies);
}
return View(departments);
}
// GET: Departments/Edit/5
[HttpGet]
[Authorize(Roles = "Administrator")]
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return BadRequest();
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Department departments = await db.Departments.FindAsync(id);
if (departments == null)
{
return NotFound();
}
return View(departments);
}
// POST: Departments/Edit/5
[HttpPost]
[Authorize(Roles = "Administrator")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(Department departments)
{
if (ModelState.IsValid)
{
if (departments == null)
{
throw new ArgumentNullException(nameof(departments), "Edit Departments, departments is null ");
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
departments.LastChanged = DateTime.Now;
departments.Active = ActiveStates.Active;
db.Entry(departments).State = EntityState.Modified;
AcsLogging.Add(User.Identity, "Afdeling " + departments.Name + " bewerkt", LogTypes.System, db);
await db.SaveChangesAsync();
return Cookies.RedirectToCookie(Request.Cookies);
}
return View(departments);
}
// GET: Departments/Delete/5
[HttpGet]
[Authorize(Roles = "Administrator")]
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return BadRequest();
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Department departments = await db.Departments.FindAsync(id);
if (departments == null)
{
return NotFound();
}
return View(departments);
}
// POST: Departments/Delete/5
[HttpPost, ActionName("Delete")]
[Authorize(Roles = "Administrator")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
if (ModelState.IsValid)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Department departments = db.Departments.Find(id);
departments.Active = ActiveStates.Deleted;
db.Entry(departments).State = EntityState.Modified;
AcsLogging.Add(User.Identity, "Afdeling " + departments.Name + " verwijderd", LogTypes.System, db);
await db.SaveChangesAsync();
return Cookies.RedirectToCookie(Request.Cookies);
}
return View();
}
}
}

View File

@@ -0,0 +1,451 @@
using Aperio_Control_Centre.ACSDatabase;
using Aperio_Control_Centre.ACSDatabase.Models;
using Aperio_Control_Centre.ACSDatabase.Types;
using Aperio_Control_Centre.Helpers;
using Aperio_Control_Centre.Models;
using Aperio_Control_Centre.PagedList;
using Aperio_Control_Centre.PagedList.MVC;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data;
namespace Aperio_Control_Centre.Controllers
{
public class DeviceController(IDbContextFactory<ACSDatabaseContext> dbContextFactory) : Controller
{
private readonly IDbContextFactory<ACSDatabaseContext> _contextFactory = dbContextFactory;
// GET: /Device/
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin, Viewer")]
public async Task<ActionResult> Index(string sortOrder)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
var devicelist = await db.Devices
.Where(i => i.Active != ActiveStates.Deleted)
.Include(I => I.Location)
.Include(j => j.DeviceGroupJoins.Select(g => g.Group))
.ToListAsync();
foreach (var dev in devicelist)
{
if (dev.ProductClass == ProductClass.Gateway)
{
dev.GatewayDevicesList = await db.Devices
.Where(d => d.HubId == dev.DeviceId)
.Where(d => d.DeviceId != dev.DeviceId)
.Where(d => d.Active != ActiveStates.Deleted)
.ToListAsync();
}
else
{
dev.GroupsSelectList = SelectListHelpers.GroupsListItems(dev, db);
}
}
Cookies.SetRedirectCookie(Response.Cookies, "Device", "Index");
if (string.IsNullOrEmpty(sortOrder))
{
if (Request.Cookies.ContainsKey("DeviceSort") == true)
{
return View(Sorting.SortDeviceList(Request.Cookies["DeviceSort"], devicelist));
}
}
Cookies.SetSortorderCookie(Response.Cookies, "DeviceSort", sortOrder);
return View(Sorting.SortDeviceList(sortOrder, devicelist));
}
// ********************** Create ********************************
// GET: /Device/Create
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public async Task<ActionResult> Create()
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
return View(new Device
{
LocationSelection = SelectListHelpers.LocationSelectList(db),
TimezoneSelection = await SelectListHelpers.TimeZoneSelectList(db),
GroupsSelectList = SelectListHelpers.GroupsListItems(db),
});
}
// POST: /Device/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[Authorize(Roles = "Administrator, DeviceAdmin")]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Device device)
{
if (device == null)
{
throw new ArgumentNullException(nameof(device), "Create Device, device is null.");
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
if (ModelState.IsValid)
{
if (await db.Devices.Where(x => x.DeviceId == device.DeviceId).Where(a => a.Active != ActiveStates.Deleted).AnyAsync())
{
device.LocationSelection = SelectListHelpers.LocationSelectList(db);
device.TimezoneSelection = await SelectListHelpers.TimeZoneSelectList(db);
ModelState.AddModelError(string.Empty, "Het adres is al ingebruik.");
return View(device);
}
device.Active = ActiveStates.Inactive;
device.ConnectionState = ConnectionStates.Offline;
device.LastChanged = DateTime.Now;
db.Devices.Add(device);
AcsLogging.Add(User.Identity, $"Apparaat {device.Name} aangemaakt", LogTypes.Device, device, db);
foreach (var group in device.GroupsSelectList.Where(a => a.Selected == true))
{
//Debug.WriteLine($"group select ID = {group.ListItem.Text} - {group.ListItem.Value} - {group.ListItem.Selected}");
if (int.TryParse(group.Value, out int groupId))
{
//add to group
DeviceGroupJoin join = new()
{
DeviceId = device.Id,
GroupId = groupId
};
db.DeviceGroupJoins.Add(join);
AcsLogging.Add(User.Identity, $"Apparaat {device.Name} toegevoegd aan groep {group.Text}", LogTypes.Device, device, db);
}
}
await db.SaveChangesAsync();
return Cookies.RedirectToCookie(Request.Cookies);
}
device.LocationSelection = SelectListHelpers.LocationSelectList(db);
device.TimezoneSelection = await SelectListHelpers.TimeZoneSelectList(db);
ModelState.AddModelError(string.Empty, "Model invalid");
return View(device);
}
//******************* Edit *********************************************
// GET: /Device/Edit/5
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return BadRequest();
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Device device = await db.Devices
.Where(d => d.Id == id)
.Include(l => l.Location)
.Include(j => j.DeviceGroupJoins.Select(g => g.Group))
.SingleOrDefaultAsync();
if (device == null)
{
return NotFound();
}
if (device.Active == ActiveStates.Inactive)
{
ModelState.AddModelError(string.Empty, "Apparaat is niet actief");
}
if (device.Active == ActiveStates.Deleted)
{
ModelState.AddModelError(string.Empty, "Apparaat is verwijderd");
}
device.GroupsSelectList = SelectListHelpers.GroupsListItems(device, db);
device.LocationSelection = SelectListHelpers.LocationSelectList(db);
device.TimezoneSelection = await SelectListHelpers.TimeZoneSelectList(db);
device.LastLoggings = await AcsLogging.LastDeviceLoggings(device, 25, db);
return View(device);
}
// POST: /Device/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[Authorize(Roles = "Administrator, DeviceAdmin")]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(Device device)
{
//System.Diagnostics.Debug.WriteLine("modelstate " + ModelState.IsValid);
if (device == null)
{
throw new ArgumentNullException(nameof(device), "Edit device, device is null");
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
if (ModelState.IsValid)
{
if (await db.Devices.Where(x => x.DeviceId == device.DeviceId).Where(a => a.Active != ActiveStates.Deleted).Where(d => d.Id != device.Id).AnyAsync())
{
ModelState.AddModelError(string.Empty, "Apparaat adres is al ingebruik.");
device.LocationSelection = SelectListHelpers.LocationSelectList(db);
device.TimezoneSelection = await SelectListHelpers.TimeZoneSelectList(db);
device.LastLoggings = await AcsLogging.LastDeviceLoggings(device, 25, db);
return View(device);
}
Device doorrec = await db.Devices.FindAsync(device.Id);
doorrec.DeviceId = device.DeviceId;
doorrec.Name = device.Name;
doorrec.LocationId = device.LocationId;
doorrec.UnlockTimezoneId = device.UnlockTimezoneId;
doorrec.UnlockTime = device.UnlockTime;
doorrec.Info = device.Info;
doorrec.LastChanged = DateTime.Now;
AcsLogging.Add(User.Identity, $"Apparaat {doorrec.Name} bewerkt", LogTypes.Device, doorrec, db);
if (doorrec.ProductClass == ProductClass.Gateway)
{
var childdevices = await db.Devices.Where(d => d.HubId == doorrec.DeviceId && d.Active != ActiveStates.Deleted && d.ProductClass != ProductClass.Gateway).ToListAsync();
foreach (var item in childdevices)
{
if (item.LocationId != device.LocationId)
{
item.LocationId = device.LocationId;
item.LastChanged = DateTime.Now;
AcsLogging.Add(User.Identity, $"Apparaat {item.Name} locatie bewerkt", LogTypes.Device, item, db);
}
}
}
if (device.ProductClass != ProductClass.Gateway)
{
foreach (var group in device.GroupsSelectList)
{
//System.Diagnostics.Debug.WriteLine($"group select ID = {group.Text} - {group.Value} - {group.Selected}");
if (int.TryParse(group.Value, out int groupId))
{
var groupjoin = await db.DeviceGroupJoins.Where(d => d.DeviceId == device.Id).Where(g => g.GroupId == groupId).SingleOrDefaultAsync();
if (groupjoin != null && group.Selected == false)
{
//remove from group
db.DeviceGroupJoins.Remove(groupjoin);
AcsLogging.Add(User.Identity, $"Apparaat {device.Name} verwijderd uit groep {group.Text}", LogTypes.Device, device, db);
}
if (groupjoin == null && group.Selected == true)
{
//add to group
DeviceGroupJoin join = new()
{
DeviceId = device.Id,
GroupId = groupId
};
db.DeviceGroupJoins.Add(join);
AcsLogging.Add(User.Identity, $"Apparaat {device.Name} toegevoegd aan groep {group.Text}", LogTypes.Device, device, db);
}
}
}
}
await db.SaveChangesAsync();
return Cookies.RedirectToCookie(Request.Cookies);
}
device.LocationSelection = SelectListHelpers.LocationSelectList(db);
device.TimezoneSelection = await SelectListHelpers.TimeZoneSelectList(db);
device.LastLoggings = await AcsLogging.LastDeviceLoggings(device, 25, db);
ModelState.AddModelError(string.Empty, "Model invalid");
return View(device);
}
//***************** Delete ***************************************
// GET: /Device/Delete/5
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return BadRequest();
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Device device = await db.Devices
.Where(d => d.Id == id)
.Include(l => l.Location)
.Include(j => j.DeviceGroupJoins.Select(g => g.Group))
.SingleOrDefaultAsync();
if (device == null)
{
return NotFound();
}
device.GroupsSelectList = SelectListHelpers.GroupsListItems(device, db);
return View(device);
}
// POST: /Device/Delete/5
[Authorize(Roles = "Administrator, DeviceAdmin")]
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Device device = await db.Devices.FindAsync(id);
device.Active = ActiveStates.Deleted;
device.LastChanged = DateTime.Now;
AcsLogging.Add(User.Identity, $"Apparaat {device.Name} verwijderd", LogTypes.Device, device, db);
await db.SaveChangesAsync();
return Cookies.RedirectToCookie(Request.Cookies);
}
//********************** Block ***********************************
// GET: /Device/Block/5
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public async Task<ActionResult> Block(int? id)
{
if (id == null)
{
return BadRequest();
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Device device = await db.Devices
.AsNoTracking()
.Where(d => d.Id == id)
.Include(l => l.Location)
.Include(j => j.DeviceGroupJoins.Select(g => g.Group))
.SingleOrDefaultAsync();
device.GroupsSelectList = SelectListHelpers.GroupsListItems(device, db);
if (device == null)
{
return NotFound();
}
return View(device);
}
// POST: /Device/Block/5
[Authorize(Roles = "Administrator, DeviceAdmin")]
[HttpPost, ActionName("Block")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> BlockConfirmed(int id)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Device device = await db.Devices.FindAsync(id);
device.Active = ActiveStates.Inactive;
device.LastChanged = DateTime.Now;
//db.Entry(device).State = EntityState.Modified;
AcsLogging.Add(User.Identity, $"Apparaat {device.Name} geblokkeerd", LogTypes.Device, device, db);
await db.SaveChangesAsync();
return Cookies.RedirectToCookie(Request.Cookies);
}
//**************** Deblock ***********************************
// GET: /Device/Deblock/5
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public async Task<ActionResult> Deblock(int? id)
{
if (id == null)
{
return BadRequest();
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Device device = await db.Devices
.AsNoTracking()
.Where(d => d.Id == id)
.Include(l => l.Location)
.Include(j => j.DeviceGroupJoins.Select(g => g.Group))
.SingleOrDefaultAsync();
if (device == null)
{
return NotFound();
}
device.GroupsSelectList = SelectListHelpers.GroupsListItems(device, db);
return View(device);
}
// POST: /Device/Deblock/5
[Authorize(Roles = "Administrator, DeviceAdmin")]
[HttpPost, ActionName("Deblock")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeblockConfirmed(int id)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Device device = await db.Devices.FindAsync(id);
device.Active = ActiveStates.Active;
device.LastChanged = DateTime.Now;
//db.Entry(device).State = EntityState.Modified;
AcsLogging.Add(User.Identity, $"Apparaat {device.Name} geactiveerd", LogTypes.Device, device, db);
await db.SaveChangesAsync();
return Cookies.RedirectToCookie(Request.Cookies);
}
//---------------------------- Log -----------------------------------------
// GET: User Loggings
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public async Task<ActionResult> Log(int? id, int? page, int? pageSize, DateTime? startLogdate, DateTime? endLogdate)
{
if (id == null)
{
return BadRequest();
}
SelectedLog loggings = new();
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
loggings.SelectedDevice = await db.Devices.FindAsync(id);
if (loggings.SelectedDevice == null)
{
return NotFound();
}
Cookies.SetRedirectCookie(Response.Cookies, "Device", $"Log/{id}");
loggings.PagedLoggings.Page = PageListHelper.GetPage(page);
loggings.PagedLoggings.PageSize = PageListHelper.GetPageSize(pageSize, Request);
Cookies.SetPageListSizeCookie(Response.Cookies, loggings.PagedLoggings.PageSize);
loggings.PagedLoggings.StartLogdate = await PageListHelper.GetStartDate(startLogdate, db);
loggings.PagedLoggings.EndLogdate = PageListHelper.GetEndDate(endLogdate);
loggings.PagedLoggings.Loggings = await db.Loggings
.Where(d => d.Time >= loggings.PagedLoggings.StartLogdate)
.Where(d => d.Time <= loggings.PagedLoggings.EndLogdate)
.Where(d => d.DeviceId == id)
.OrderByDescending(m => m.Time)
.Include(i => i.User)
.Include(i => i.Device)
.Include(i => i.Device.Location)
.AsNoTracking()
.ToPagedListAsync(loggings.PagedLoggings.Page, loggings.PagedLoggings.PageSize);
return View(loggings);
}
//---------------------------- Json check -----------------------------------------
//Kijk of het device ID al bestaat in de database
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public async Task<JsonResult> VerifyDeviceID(string deviceID)
{
//Debug.WriteLine(devId);
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
if (await db.Devices.Where(c => c.DeviceId == deviceID).Where(c => c.Active != ActiveStates.Deleted).AnyAsync())
{
return Json($"DeviceID {deviceID} is already in use.");
}
return Json(true);
}
}
}

View File

@@ -0,0 +1,790 @@
using System.Data;
using OfficeOpenXml;
using OfficeOpenXml.Table;
using System.Drawing;
using System.Text;
using System.Diagnostics;
using Aperio_Control_Centre.ACSDatabase;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Aperio_Control_Centre.ACSDatabase.Models;
using Aperio_Control_Centre.ACSDatabase.Types;
using Aperio_Control_Centre.Frontend.Models;
using Microsoft.AspNetCore.Mvc.Rendering;
using Aperio_Control_Centre.Export.Paxton;
using Aperio_Control_Centre.Extensions;
namespace Aperio_Control_Centre.Controllers
{
//[System.Web.Mvc.AuthorizeAttribute(Roles = "Administrator")]
[Authorize(Roles = "Administrator")]
public class ExportController(IDbContextFactory<ACSDatabaseContext> dbContextFactory) : Controller
{
private readonly IDbContextFactory<ACSDatabaseContext> _contextFactory = dbContextFactory;
// --------------------------- User List -------------------------------------------------------------------------
private async Task<List<User>> GetUserList(ExportUsersModel exportUsersModel)
{
List<ActiveStates> activeStates = new();
if (exportUsersModel.NewUsersSelect)
activeStates.Add(ActiveStates.New);
if (exportUsersModel.ActiveUsersSelect)
activeStates.Add(ActiveStates.Active);
if (exportUsersModel.NonActieveUsersSelect)
activeStates.Add(ActiveStates.Inactive);
List<int> groupsSelected = exportUsersModel.GroupSelectList.Where(s => s.Selected).Select(x => int.Parse(x.Value)).ToList();
List<int> departmentSelected = exportUsersModel.DepartmentSelectList.Where(s => s.Selected).Select(x => int.Parse(x.Value)).ToList();
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
return await db.Users
.Where(a => activeStates.Contains(a.Active))
.Where(g => groupsSelected.Contains(g.GroupId.Value) || departmentSelected.Contains(g.DepartmentId.Value))
.Include(g => g.Group)
.Include(d => d.Department)
.OrderBy(p => p.PassNumber).ToListAsync();
}
// --------------------------- ExportUsers -------------------------------------------------------------------------
// GET: Export/ExportUsers
[HttpGet]
[Authorize(Roles = "Administrator")]
public async Task<ActionResult> ExportUsers()
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
ExportUsersModel exportUsers = new()
{
UserList = new List<User>(),
GroupSelectList = await Helpers.SelectListHelpers.GroupsSelectListItems(db),
DepartmentSelectList = await Helpers.SelectListHelpers.DepartmentsSelectListItems(db)
};
Helpers.Cookies.SetRedirectCookie(Response.Cookies, "Export", "ExportUsers");
return View(exportUsers);
}
// POST: Export/ExportUsers
[HttpPost]
[Authorize(Roles = "Administrator")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ExportUsers(ExportUsersModel exportUsers)
{
if (ModelState.IsValid)
{
if (exportUsers == null)
{
throw new ArgumentNullException(nameof(exportUsers), "ExportUsers Export, exportUsers is null.");
}
exportUsers.UserList = await GetUserList(exportUsers);
return View(exportUsers);
}
return Redirect("ExportUsers");
}
// POST: Export/CreateUsersExcel
[HttpPost]
[Authorize(Roles = "Administrator")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> CreateUsersExcel(ExportUsersModel exportUsers)
{
if (ModelState.IsValid)
{
if (exportUsers == null)
{
throw new ArgumentNullException(nameof(exportUsers), "CreateUsersExcel Export, exportUsers is null.");
}
List<User> users = await GetUserList(exportUsers);
exportUsers.UserList = users.ToList();
//-------------------------
using DataTable Dt = new();
Dt.Columns.Add("Pas nummer", typeof(string));
Dt.Columns.Add("Gebruikers naam", typeof(string));
Dt.Columns.Add("Gebruikers informatie", typeof(string));
Dt.Columns.Add("Sub Regel", typeof(string));
Dt.Columns.Add("UID nummer", typeof(string));
Dt.Columns.Add("Autorisatiegroep", typeof(string));
Dt.Columns.Add("Afdeling", typeof(string));
Dt.Columns.Add("Pas actief", typeof(string));
Dt.Columns.Add("Aangemaakt", typeof(string));
Dt.Columns.Add("Laatste wijziging", typeof(string));
foreach (var item in users)
{
DataRow row = Dt.NewRow();
row[0] = item.PassNumber;
row[1] = item.Name;
row[2] = item.Info;
row[3] = item.SubLine;
row[4] = item.CredentialString;
if (item.Group != null)
{
row[5] = item.Group.Name;
}
if (item.Department != null)
{
row[6] = item.Department.Name;
}
row[7] = item.Active;
row[8] = item.Created;
row[9] = item.LastChanged;
Dt.Rows.Add(row);
}
using var excelPackage = new ExcelPackage(new MemoryStream());
var worksheet = excelPackage.Workbook.Worksheets.Add("Passen");
worksheet.Cells["A1"].Value = "Export datum";
worksheet.Cells["B1"].Value = DateTime.Now.ToString();
worksheet.Cells["A2"].LoadFromDataTable(Dt, true, TableStyles.None);
worksheet.Cells["A2:AN2"].Style.Font.Bold = true;
worksheet.Cells["A2:AN2"].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
worksheet.Cells["A2:AN2"].Style.Fill.BackgroundColor.SetColor(Color.LightBlue);
worksheet.DefaultRowHeight = 18;
worksheet.View.FreezePanes(3, 1);
for (int i = 1; i < worksheet.Dimension.End.Column; i++)
{
worksheet.Column(i).Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
worksheet.Column(i).AutoFit();
worksheet.Column(i).Width = worksheet.Column(i).Width + 2;
}
for (var row = 3; row <= worksheet.Dimension.End.Row; row++)
{
if (row % 2 != 0)
{
worksheet.Cells["A" + row + ":J" + row].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
worksheet.Cells["A" + row + ":J" + row].Style.Fill.BackgroundColor.SetColor(Color.GhostWhite);
}
}
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
var fileName = $"GebruikersExport-{DateTime.Now.Year:00}{DateTime.Now.Month:00}{DateTime.Now.Day:00}";
Response.Headers.Add("Content-Disposition", $"attachment;filename={fileName}.xlsx");
//Response.SendFileAsync(excelPackage.File);
//Response.BinaryWrite(excelPackage.GetAsByteArray());
//Response.Flush();
//Response.Close();
}
return Redirect("ExportUsers");
}
// --------------------------- Device List -------------------------------------------------------------------------
private async Task<List<Device>> GetDeviceList(ExportDeviceModel exportDevicesModel)
{
List<ActiveStates> activeStates = new();
if (exportDevicesModel.ActiveDevicesSelect)
activeStates.Add(ActiveStates.Active);
if (exportDevicesModel.NonActieveDevicesSelect)
activeStates.Add(ActiveStates.Inactive);
List<int> groupsSelected = exportDevicesModel.GroupSelectList.Where(s => s.Selected).Select(x => int.Parse(x.Value)).ToList();
List<int> locationSelected = exportDevicesModel.LocationSelectList.Where(s => s.Selected).Select(x => int.Parse(x.Value)).ToList();
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
List<int> devicesInGroup = await db.DeviceGroupJoins.Where(g => groupsSelected.Contains(g.GroupId)).Select(i => i.DeviceId).ToListAsync();
return await db.Devices
.Where(a => activeStates.Contains(a.Active))
.Where(l => locationSelected.Contains(l.LocationId.Value) || devicesInGroup.Contains(l.Id))
.Include(d => d.Location)
.OrderBy(p => p.DeviceId).ToListAsync();
}
// --------------------------- ExportDevices -------------------------------------------------------------------------
// GET: Export/ExportDevices
[HttpGet]
[Authorize(Roles = "Administrator")]
public async Task<ActionResult> ExportDevices()
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
ExportDeviceModel exportDevices = new()
{
DeviceList = new List<Device>(),
GroupSelectList = await Helpers.SelectListHelpers.GroupsSelectListItems(db),
LocationSelectList = Helpers.SelectListHelpers.LocationSelectItems(db),
};
Helpers.Cookies.SetRedirectCookie(Response.Cookies, "Export", "ExportDevices");
return View(exportDevices);
}
// POST: Export/ExportDevices
[HttpPost]
[Authorize(Roles = "Administrator")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ExportDevices(ExportDeviceModel exportDevice)
{
if (ModelState.IsValid)
{
if (exportDevice == null)
{
throw new ArgumentNullException(nameof(exportDevice), "ExportDevices Export, exportDevice is null.");
}
exportDevice.DeviceList = await GetDeviceList(exportDevice);
return View(exportDevice);
}
return Redirect("ExportDevices");
}
// POST: Export/CreateDevicesExcel
[HttpPost]
[Authorize(Roles = "Administrator")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> CreateDevicesExcel(ExportDeviceModel exportDevices)
{
Debug.WriteLine("Create Devcies Excel ");
if (ModelState.IsValid)
{
if (exportDevices == null)
{
throw new ArgumentNullException(nameof(exportDevices), "CreateDevicesExcel Export, exportDevice is null.");
}
IEnumerable<Device> devices = await GetDeviceList(exportDevices);
exportDevices.DeviceList = devices.ToList();
//-------------------------
using DataTable Dt = new();
Dt.Columns.Add("Apparaat ID", typeof(string));
Dt.Columns.Add("Hub ID", typeof(string));
Dt.Columns.Add("Apparaat naam", typeof(string));
Dt.Columns.Add("Apparaat informatie", typeof(string));
Dt.Columns.Add("Product type", typeof(string));
Dt.Columns.Add("Batterij status", typeof(string));
Dt.Columns.Add("locatie", typeof(string));
Dt.Columns.Add("Groepen", typeof(string));
Dt.Columns.Add("Apparaat actief", typeof(string));
Dt.Columns.Add("Laatste wijziging", typeof(string));
foreach (var item in devices)
{
DataRow row = Dt.NewRow();
row[0] = item.DeviceId;
row[1] = item.HubId;
row[2] = item.Name;
row[3] = item.Info;
row[4] = item.ProductClass;
row[5] = item.BatteryState;
if (item.Location != null)
{
row[6] = item.Location.AddressString;
}
row[7] = item.GroupsString;
row[8] = item.Active;
row[9] = item.LastChanged;
Dt.Rows.Add(row);
}
using var excelPackage = new ExcelPackage(new MemoryStream());
var worksheet = excelPackage.Workbook.Worksheets.Add("Apparaten");
worksheet.Cells["A1"].Value = "Export datum";
worksheet.Cells["B1"].Value = DateTime.Now.ToString();
worksheet.Cells["A2"].LoadFromDataTable(Dt, true, TableStyles.None);
worksheet.Cells["A2:AN2"].Style.Font.Bold = true;
worksheet.Cells["A2:AN2"].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
worksheet.Cells["A2:AN2"].Style.Fill.BackgroundColor.SetColor(Color.LightBlue);
worksheet.DefaultRowHeight = 18;
worksheet.View.FreezePanes(3, 1);
for (int i = 1; i < worksheet.Dimension.End.Column; i++)
{
worksheet.Column(i).Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
worksheet.Column(i).AutoFit();
worksheet.Column(i).Width = worksheet.Column(i).Width + 2;
}
for (var row = 3; row <= worksheet.Dimension.End.Row; row++)
{
if (row % 2 != 0)
{
worksheet.Cells["A" + row + ":J" + row].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
worksheet.Cells["A" + row + ":J" + row].Style.Fill.BackgroundColor.SetColor(Color.GhostWhite);
}
}
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
var fileName = $"ApparatenExport-{DateTime.Now.Year:00}{DateTime.Now.Month:00}{DateTime.Now.Day:00}";
Response.Headers.Add("Content-Disposition", $"attachment;filename={fileName}.xlsx");
//Response.BinaryWrite(excelPackage.GetAsByteArray());
//Response.Flush();
//Response.Close();
}
return Redirect("ExportDevices");
}
// --------------------------- Logging list -------------------------------------------------------------------------
private async Task<List<Logging>> GetLogList(ExportLoggingModel exportLogModel)
{
List<LogTypes> selectedLogTypes = exportLogModel.LogTypeSelectList.Where(s => s.Selected).Select(x => (LogTypes)int.Parse(x.Value)).ToList();
List<int> selectedGroups = exportLogModel.GroupSelectList.Where(s => s.Selected).Select(x => int.Parse(x.Value)).ToList();
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
List<int> selecteddevicesInGroups = await db.DeviceGroupJoins
.Where(g => selectedGroups.Contains(g.GroupId))
.Where(d => d.Device.Active != ActiveStates.Deleted)
.Select(d => d.DeviceId)
.ToListAsync();
List<int> selectedDevices = new();
foreach (var item in exportLogModel.DeviceSelectList.Where(s => s.Selected))
{
//System.Diagnostics.Debug.WriteLine("Device id = " + item.Value + " - " + item.Text);
if (selecteddevicesInGroups.Contains(int.Parse(item.Value)))
{
selectedDevices.Add(int.Parse(item.Value));
}
}
return await db.Loggings
.Where(s => s.Time >= exportLogModel.StartDateTime)
.Where(e => e.Time <= exportLogModel.EndDateTime)
.Where(i => selectedLogTypes.Contains(i.LogType))
.Where(g => selectedGroups.Contains(g.User.GroupId.Value) || g.UserId.HasValue == false)
.Where(d => selectedDevices.Contains(d.DeviceId.Value) || d.DeviceId.HasValue == false)
.ToListAsync();
}
// --------------------------- ExportLogging -------------------------------------------------------------------------
// GET: Export/ExportLogging
[HttpGet]
[Authorize(Roles = "Administrator")]
public async Task<ActionResult> ExportLogging()
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
ExportLoggingModel exportLogging = new()
{
StartDateTime = DateTime.Now,
EndDateTime = DateTime.Now,
LoggingsList = new List<Logging>(),
LogTypeSelectList = Enum.GetValues(typeof(LogTypes)).Cast<LogTypes>().Select(x => new SelectListItem { Text = x.GetDisplayName(), Value = ((int)x).ToString() }).ToList(),
GroupSelectList = await Helpers.SelectListHelpers.GroupsSelectListItems(db),
DeviceSelectList = Helpers.SelectListHelpers.DeviceSelectListItems(db)
};
Helpers.Cookies.SetRedirectCookie(Response.Cookies, "Export", "ExportLogging");
return View(exportLogging);
}
// POST: Export/ExportLogging
[HttpPost]
[Authorize(Roles = "Administrator")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ExportLogging(ExportLoggingModel exportLogging)
{
if (ModelState.IsValid)
{
if (exportLogging == null)
{
throw new ArgumentNullException(nameof(exportLogging), "ExportLogging Export, exportLogging is null.");
}
//System.Diagnostics.Debug.WriteLine("start date = " + exportLogging.StartDateTime);
//System.Diagnostics.Debug.WriteLine("end date = " + exportLogging.EndDateTime);
exportLogging.LoggingsList = await GetLogList(exportLogging);
return View(exportLogging);
}
return Redirect("ExportLogging");
}
// POST: Export/CreateLoggingExcel
[HttpPost]
[Authorize(Roles = "Administrator")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> CreateLoggingExcel(ExportLoggingModel exportLoggings)
{
//System.Diagnostics.Debug.WriteLine("Create Loggings Excel ");
if (ModelState.IsValid)
{
if (exportLoggings == null)
{
throw new ArgumentNullException(nameof(exportLoggings), "CreateLoggingExcel Export, exportLogging is null.");
}
List<Logging> loggings = await GetLogList(exportLoggings);
//-------------------------
using DataTable Dt = new();
Dt.Columns.Add("Tijd", typeof(string));
Dt.Columns.Add("Pas nummer", typeof(string));
Dt.Columns.Add("Gebruikers naam", typeof(string));
Dt.Columns.Add("Apparaat informatie", typeof(string));
Dt.Columns.Add("Locatie", typeof(string));
Dt.Columns.Add("Toegang", typeof(string));
Dt.Columns.Add("Bericht", typeof(string));
foreach (var item in loggings)
{
DataRow row = Dt.NewRow();
row[0] = item.Time;
if (item.User != null)
{
if (item.User.PassNumber != null)
{
row[1] = item.User.PassNumber;
}
row[2] = item.User.Name;
}
if (item.Device != null)
{
row[3] = item.Device.Name;
if (item.Device.Location != null)
{
row[4] = item.Device.Location.ShortAddressString;
}
}
row[5] = item.Access;
row[6] = item.Message;
Dt.Rows.Add(row);
}
using var excelPackage = new ExcelPackage(new MemoryStream());
var worksheet = excelPackage.Workbook.Worksheets.Add("Loggings");
worksheet.Cells["A1"].Value = "Export datum";
worksheet.Cells["B1"].Value = DateTime.Now.ToString();
worksheet.Cells["A2"].LoadFromDataTable(Dt, true, TableStyles.None);
worksheet.Cells["A2:AN2"].Style.Font.Bold = true;
worksheet.Cells["A2:AN2"].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
worksheet.Cells["A2:AN2"].Style.Fill.BackgroundColor.SetColor(Color.LightBlue);
worksheet.DefaultRowHeight = 18;
worksheet.View.FreezePanes(3, 1);
for (int i = 1; i < worksheet.Dimension.End.Column; i++)
{
worksheet.Column(i).Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
worksheet.Column(i).AutoFit();
worksheet.Column(i).Width = worksheet.Column(i).Width + 2;
}
for (var row = 3; row <= worksheet.Dimension.End.Row; row++)
{
if (row % 2 != 0)
{
worksheet.Cells["A" + row + ":G" + row].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
worksheet.Cells["A" + row + ":G" + row].Style.Fill.BackgroundColor.SetColor(Color.GhostWhite);
}
}
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
var fileName = $"LoggingsExport-{DateTime.Now.Year:00}{DateTime.Now.Month:00}{DateTime.Now.Day:00}";
Response.Headers.Add("Content-Disposition", $"attachment;filename={fileName}.xlsx");
//Response.BinaryWrite(excelPackage.GetAsByteArray());
//Response.Flush();
//Response.Close();
}
return Redirect("ExportLogging");
}
// --------------------------- ExportDordrecht -------------------------------------------------------------------------
// GET: Export/ExportDordrecht
[HttpGet]
[Authorize(Roles = "Administrator")]
public async Task<ActionResult> ExportDordrecht(string sortOrder)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
IQueryable<User> dordrechtUsers = db.Users
.Where(a => a.Active != ActiveStates.Deleted)
.Where(d => d.Dordrecht.Value == true)
.AsNoTracking();
Helpers.Cookies.SetRedirectCookie(Response.Cookies, "Export", "ExportDordrecht");
return View(await Helpers.Sorting.SortUserList(sortOrder, dordrechtUsers).ToListAsync());
}
// POST: Export/ExportDordrecht
[HttpPost]
[Authorize(Roles = "Administrator")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> CreateDordrechtExcel()
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
var dordrechtUsers = await db.Users
.Where(a => a.Active != ActiveStates.Deleted)
.Where(d => d.Dordrecht.Value == true)
.ToListAsync();
//-------------------------
using DataTable activeUsersTable = new();
activeUsersTable.Columns.Add("Mifare UID", typeof(string));
activeUsersTable.Columns.Add("Gebruikers naam", typeof(string));
activeUsersTable.Columns.Add("Pas nummer", typeof(string));
foreach (var item in dordrechtUsers.Where(u => u.Active != ActiveStates.Inactive))
{
DataRow row = activeUsersTable.NewRow();
row[0] = item.CredentialString;
row[1] = item.Name;
if (item.PassNumber.HasValue)
{
row[2] = item.PassNumber;
}
activeUsersTable.Rows.Add(row);
}
using DataTable inactiveUsersTable = new();
inactiveUsersTable.Columns.Add("Mifare UID", typeof(string));
inactiveUsersTable.Columns.Add("Gebruikers naam", typeof(string));
inactiveUsersTable.Columns.Add("Pas nummer", typeof(string));
foreach (var item in dordrechtUsers.Where(u => u.Active == ActiveStates.Inactive))
{
DataRow row = inactiveUsersTable.NewRow();
row[0] = item.CredentialString;
row[1] = item.Name;
if (item.PassNumber.HasValue)
{
row[2] = item.PassNumber;
}
inactiveUsersTable.Rows.Add(row);
}
using (var excelPackage = new ExcelPackage(new MemoryStream()))
{
// Active users worksheet
var activeWorksheet = excelPackage.Workbook.Worksheets.Add("Nieuwe en active Passen");
activeWorksheet.Cells["A1"].Value = "Export datum";
activeWorksheet.Cells["B1"].Value = DateTime.Now.ToString();
activeWorksheet.Cells["A2"].LoadFromDataTable(activeUsersTable, true, TableStyles.None);
activeWorksheet.Cells["A2:AN2"].Style.Font.Bold = true;
activeWorksheet.Cells["A2:AN2"].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
activeWorksheet.Cells["A2:AN2"].Style.Fill.BackgroundColor.SetColor(Color.LightBlue);
activeWorksheet.DefaultRowHeight = 18;
activeWorksheet.View.FreezePanes(3, 1);
for (int i = 1; i < activeWorksheet.Dimension.End.Column; i++)
{
activeWorksheet.Column(i).Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
activeWorksheet.Column(i).AutoFit();
activeWorksheet.Column(i).Width = activeWorksheet.Column(i).Width + 2;
}
for (var row = 3; row <= activeWorksheet.Dimension.End.Row; row++)
{
if (row % 2 != 0)
{
activeWorksheet.Cells["A" + row + ":C" + row].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
activeWorksheet.Cells["A" + row + ":C" + row].Style.Fill.BackgroundColor.SetColor(Color.GhostWhite);
}
}
//Inactive users worksheet
var inactiveWorksheet = excelPackage.Workbook.Worksheets.Add("Niet active Passen");
inactiveWorksheet.Cells["A1"].Value = "Export datum";
inactiveWorksheet.Cells["B1"].Value = DateTime.Now.ToString();
inactiveWorksheet.Cells["A2"].LoadFromDataTable(inactiveUsersTable, true, TableStyles.None);
inactiveWorksheet.Cells["A2:AN2"].Style.Font.Bold = true;
inactiveWorksheet.Cells["A2:AN2"].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
inactiveWorksheet.Cells["A2:AN2"].Style.Fill.BackgroundColor.SetColor(Color.LightBlue);
inactiveWorksheet.DefaultRowHeight = 18;
inactiveWorksheet.View.FreezePanes(3, 1);
for (int i = 1; i < inactiveWorksheet.Dimension.End.Column; i++)
{
inactiveWorksheet.Column(i).Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
inactiveWorksheet.Column(i).AutoFit();
inactiveWorksheet.Column(i).Width = inactiveWorksheet.Column(i).Width + 2;
}
for (var row = 3; row <= inactiveWorksheet.Dimension.End.Row; row++)
{
if (row % 2 != 0)
{
inactiveWorksheet.Cells["A" + row + ":C" + row].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
inactiveWorksheet.Cells["A" + row + ":C" + row].Style.Fill.BackgroundColor.SetColor(Color.GhostWhite);
}
}
//Create excel document
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
var fileName = $"DordrechtExport-{DateTime.Now.Year:00}{DateTime.Now.Month:00}{DateTime.Now.Day:00}";
Response.Headers.Add("Content-Disposition", $"attachment;filename={fileName}.xlsx");
//Response.BinaryWrite(excelPackage.GetAsByteArray());
//Response.Flush();
//Response.Close();
}
return Redirect("ExportDordrecht");
}
// --------------------------- ExportErasmus -------------------------------------------------------------------------
private async Task<List<User>> GetErasmusUserList(ExportUsersModel exportUsersModel)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
List<int> departmentSelected = new();
foreach (var item in exportUsersModel.DepartmentSelectList)
{
if (item.Selected == true)
{
departmentSelected.Add(int.Parse(item.Value));
}
}
var deletedUsers = await db.Users
.Where(a => a.Active == ActiveStates.Deleted)
.Where(l => l.LastChanged >= exportUsersModel.PaxtonEpocDate)
.Where(g => departmentSelected.Contains(g.DepartmentId.Value))
.Include(g => g.Group)
.Include(d => d.Department)
.OrderBy(p => p.PassNumber)
.ToListAsync();
var inactiveUsers = await db.Users
.Where(a => a.Active == ActiveStates.Inactive)
.Where(l => l.LastChanged >= exportUsersModel.PaxtonEpocDate)
.Where(g => departmentSelected.Contains(g.DepartmentId.Value))
.Include(g => g.Group)
.Include(d => d.Department)
.OrderBy(p => p.PassNumber)
.ToListAsync();
var activeUsers = await db.Users
.Where(a => a.Active == ActiveStates.Active)
.Where(g => departmentSelected.Contains(g.DepartmentId.Value))
.Include(g => g.Group)
.Include(d => d.Department)
.OrderBy(p => p.PassNumber)
.ToListAsync();
activeUsers.AddRange(inactiveUsers);
activeUsers.AddRange(deletedUsers);
return activeUsers;
}
// GET: Export/ExportErasmus
[HttpGet]
[Authorize(Roles = "Administrator")]
public async Task<ActionResult> ExportErasmus()
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
ExportUsersModel exportUsers = new()
{
UserList = new List<User>(),
DepartmentSelectList = await Helpers.SelectListHelpers.DepartmentsSelectListItems(db),
PaxtonDepartment = "Huurder 02 Arbounie",
PaxtonAccessLevelName = "Arbo Unie",
PaxtonEpocDate = await Helpers.ConfigurationHelper.ErasmusEpocDate(db),
};
Helpers.Cookies.SetRedirectCookie(Response.Cookies, "Export", "ExportErasmus");
return View(exportUsers);
}
// POST: Export/ExportErasmus
[HttpPost]
[Authorize(Roles = "Administrator")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ExportErasmus(ExportUsersModel exportUsers)
{
if (ModelState.IsValid)
{
if (exportUsers == null)
{
throw new ArgumentNullException(nameof(exportUsers), "ExportErasmus Export, exportUsers is null.");
}
exportUsers.UserList = await GetErasmusUserList(exportUsers);
return View(exportUsers);
}
return Redirect("ExportErasmus");
}
[HttpPost]
[Authorize(Roles = "Administrator")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> CreateErasmusCSV(ExportUsersModel exportUsers)
{
if (ModelState.IsValid)
{
if (exportUsers == null)
{
throw new ArgumentNullException(nameof(exportUsers), "CreateErasmusCSV Export, exportUsers is null.");
}
exportUsers.UserList = await GetErasmusUserList(exportUsers);
List<PaxtonUserModel> paxtonUsers = new();
foreach (var user in exportUsers.UserList)
{
//Debug.WriteLine($"{item.Name}");
PaxtonUserModel paxtonuser = new()
{
Firstname = PaxtonUserModel.SplitUsername(user.Name).firstname,
Surname = PaxtonUserModel.SplitUsername(user.Name).lastname,
Department = exportUsers.PaxtonDepartment,
ActiveDate = user.Created,
ExpiryDate = PaxtonUserModel.CalculateExpiryDate(user.LastChanged, user.Active == ActiveStates.Active),
PersonnelNumber = user.PassNumber.ToString(),
};
paxtonuser.AccessLevels.Add(new PaxtonAuthorizationModel()
{
Name = exportUsers.PaxtonAccessLevelName,
Ordinal = true
});
paxtonuser.Cards.Add(new PaxtonCardModel()
{
Number = PaxtonCardModel.NumberFromHex(user.CredentialString),
Type = PaxtonCardTypes.Niet_gespecificeerd,
Lost = false
});
paxtonUsers.Add(paxtonuser);
}
string csv = PaxtonExport.CreateExport(paxtonUsers);
//Create csv document
Response.Clear();
Response.ContentType = "text/csv";
var fileName = $"ErasmusExport-{DateTime.Now.Year:00}{DateTime.Now.Month:00}{DateTime.Now.Day:00}";
Response.Headers.Add("Content-Disposition", $"attachment;filename={fileName}.csv");
//Response.BinaryWrite(Encoding.UTF8.GetBytes(csv));
//Response.Flush();
//Response.Close();
}
return Redirect("ExportErasmus");
}
}
}

View File

@@ -0,0 +1,258 @@
using Aperio_Control_Centre.ACSDatabase;
using Aperio_Control_Centre.ACSDatabase.Models;
using Aperio_Control_Centre.ACSDatabase.Types;
using Aperio_Control_Centre.Frontend.Models;
using Aperio_Control_Centre.Helpers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data;
using System.Net;
namespace Aperio_Control_Centre.Controllers
{
public class GroupsController(IDbContextFactory<ACSDatabaseContext> dbContextFactory) : Controller
{
private readonly IDbContextFactory<ACSDatabaseContext> _contextFactory = dbContextFactory;
// GET: UserGroups
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin, Viewer")]
public async Task<ActionResult> Index()
{
Helpers.Cookies.SetRedirectCookie(Response.Cookies, "Groups", "Index");
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
return View(await db.Groups
.Where(x => x.Active == ActiveStates.Active)
.Include(I => I.Timezone)
.Include(u => u.Users)
.Include(d => d.DeviceGroupJoins.Select(x => x.Device))
.AsNoTracking()
.ToListAsync()
);
}
//--------------------- View Group ----------------------------------------------
// GET: UserGroups/View/5
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public async Task<ActionResult> View(string sortOrder, int? id)
{
if (id == null)
{
return BadRequest();
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
GroupViewModel groupView = new()
{
Group = await db.Groups
.Where(i => i.Id == id)
.Include(I => I.Timezone)
.Include(u => u.Users.Select(d => d.Department))
.Include(l => l.DeviceGroupJoins.Select(x => x.Device).Select(l => l.Location))
.SingleOrDefaultAsync()
};
if (groupView.Group == null)
{
return NotFound();
}
groupView.Devices = Helpers.Sorting.SortDeviceList(sortOrder, groupView.Group.DevicesAll.AsQueryable());
groupView.Users = Helpers.Sorting.SortUserList(sortOrder, groupView.Group.Users.Where(u => u.Active != ActiveStates.Deleted).AsQueryable());
return View(groupView);
}
//--------------------- Create ----------------------------------------------
// GET: UserGroups/Create
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public async Task<ActionResult> Create()
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Group newgroup = new()
{
DeviceSelectList = Helpers.SelectListHelpers.LockDeviceSelectListItems(db),
TimezoneSelection = await Helpers.SelectListHelpers.TimeZoneSelectList(db)
};
return View(newgroup);
}
// POST: UserGroups/Create
[Authorize(Roles = "Administrator, DeviceAdmin")]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Group group)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
if (ModelState.IsValid)
{
if (group == null)
{
throw new ArgumentNullException(nameof(group), "Create Groups, group is null.");
}
group.Active = ActiveStates.Active;
group.LastChanged = DateTime.Now;
db.Groups.Add(group);
AcsLogging.Add(User.Identity, $"Groep {group.Name} aangemaakt", LogTypes.System, db);
foreach (var device in group.DeviceSelectList)
{
//System.Diagnostics.Debug.WriteLine($"group select ID = {group.Text} - {group.Value} - {group.Selected}");
if (device.Selected == true)
{
if (int.TryParse(device.Value, out int deviceId))
{
//add to group
Device dev = db.Devices.Find(deviceId);
if (dev != null)
{
DeviceGroupJoin join = new()
{
DeviceId = deviceId,
GroupId = group.Id,
};
db.DeviceGroupJoins.Add(join);
AcsLogging.Add(User.Identity, $"Apparaat {dev.Name} toegevoegd aan groep {group.Name}", LogTypes.Device, dev, db);
}
}
}
}
await db.SaveChangesAsync();
return Helpers.Cookies.RedirectToCookie(Request.Cookies);
}
group.TimezoneSelection = await Helpers.SelectListHelpers.TimeZoneSelectList(db);
return View(group);
}
//--------------------- Edit ----------------------------------------------
// GET: UserGroups/Edit/5
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return BadRequest();
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Group group = await db.Groups
.Where(i => i.Id == id)
.Include(u => u.Users.Select(d => d.Department))
.Include(d => d.DeviceGroupJoins.Select(d => d.Device))
.SingleOrDefaultAsync();
if (group == null)
{
return NotFound();
}
group.DeviceSelectList = Helpers.SelectListHelpers.LockDeviceSelectListItems(group.Id, db);
group.TimezoneSelection = await Helpers.SelectListHelpers.TimeZoneSelectList(db);
return View(group);
}
// POST: UserGroups/Edit/5
[Authorize(Roles = "Administrator, DeviceAdmin")]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(Group group)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
if (ModelState.IsValid)
{
if (group == null)
{
throw new ArgumentNullException(nameof(group), "Edit Groups, group is null.");
}
group.Active = ActiveStates.Active;
group.LastChanged = DateTime.Now;
db.Entry(group).State = EntityState.Modified;
//db.Groups.AddOrUpdate(group);
AcsLogging.Add(User.Identity, $"Groep {group.Name} bewerkt", LogTypes.System, db);
foreach (var device in group.DeviceSelectList)
{
//System.Diagnostics.Debug.WriteLine($"group select ID = {group.Text} - {group.Value} - {group.Selected}");
if (int.TryParse(device.Value, out int deviceId))
{
Device dev = db.Devices.Find(deviceId);
if (dev != null)
{
var groupjoin = await db.DeviceGroupJoins.Where(d => d.DeviceId == dev.Id).Where(g => g.GroupId == group.Id).SingleOrDefaultAsync();
if (groupjoin != null && device.Selected == false)
{
//remove from group
db.DeviceGroupJoins.Remove(groupjoin);
AcsLogging.Add(User.Identity, $"Apparaat {dev.Name} verwijderd uit groep {group.Name}", LogTypes.Device, dev, db);
}
if (groupjoin == null && device.Selected == true)
{
//add to group
DeviceGroupJoin join = new()
{
DeviceId = dev.Id,
GroupId = group.Id
};
db.DeviceGroupJoins.Add(join);
AcsLogging.Add(User.Identity, $"Apparaat {dev.Name} toegevoegd aan groep {group.Name}", LogTypes.Device, dev, db);
}
}
}
}
await db.SaveChangesAsync();
return Helpers.Cookies.RedirectToCookie(Request.Cookies);
}
group.TimezoneSelection = await Helpers.SelectListHelpers.TimeZoneSelectList(db);
return View(group);
}
//------------------- Delete ---------------------------
// GET: UserGroups/Delete/5
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return BadRequest();
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Group group = await db.Groups.FindAsync(id);
if (group == null)
{
return NotFound();
}
return View(group);
}
// POST: UserGroups/Delete/5
[Authorize(Roles = "Administrator, DeviceAdmin")]
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Group group = db.Groups.Find(id);
group.Active = ActiveStates.Deleted;
group.LastChanged = DateTime.Now;
db.Entry(group).State = EntityState.Modified;
AcsLogging.Add(User.Identity, $"Groep {group.Name} verwijderd", LogTypes.System, db);
await db.SaveChangesAsync();
return Helpers.Cookies.RedirectToCookie(Request.Cookies);
}
}
}

View File

@@ -0,0 +1,261 @@
using Aperio_Control_Centre.ACSDatabase;
using Aperio_Control_Centre.ACSDatabase.Models;
using Aperio_Control_Centre.ACSDatabase.Types;
using Aperio_Control_Centre.Frontend.Models;
using Aperio_Control_Centre.Helpers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data;
using System.Globalization;
using System.Net;
namespace Aperio_Control_Centre.Controllers
{
public class LocationsController(IDbContextFactory<ACSDatabaseContext> dbContextFactory) : Controller
{
private readonly IDbContextFactory<ACSDatabaseContext> _contextFactory = dbContextFactory;
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public JsonResult Lookup(string Zipcode, string Number)
{
if (Int32.TryParse(new String(Number.Where(Char.IsDigit).ToArray()), out int nr) == false)
{
return Json(new { error = "gebruiker correct huisnummer" });
}
string letter = new(Number.Where(Char.IsLetter).ToArray());
int letterIdx = 0;
if (letter.Length == 1)
{
letterIdx = ((int)char.ToUpper(letter[0])) - 64;
}
if (Zipcode == null)
{
return Json(new { error = "Geen postcode opgegeven" });
}
if (Zipcode.Length > 0)
{
try
{
//https://api.pdok.nl/bzk/locatieserver/search/v3_1/free
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(new Uri("https://api.pdok.nl/bzk/locatieserver/search/v3_1/free?fq=postcode:" + Zipcode + "&fq=huisnummer:" + nr));
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "GET";
httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
GeoDataRootObject result;
using (StreamReader sr = new(httpWebRequest.GetResponse().GetResponseStream()))
{
result = System.Text.Json.JsonSerializer.Deserialize<GeoDataRootObject>(sr.ReadToEnd());
}
if (result == null)
{
return Json(new { error = "Deserialize error in response" });
}
if (result.Response.NumFound == 1)
{
// ETRS:89 projectie
// WKT string
// "POINT(5.39109 51.49700212)"
//set comma to point
CultureInfo customCulture = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
customCulture.NumberFormat.NumberDecimalSeparator = ".";
Thread.CurrentThread.CurrentCulture = customCulture;
//DbGeometry point = DbGeometry.FromText(result.Response.Docs.FirstOrDefault().Centroide_ll);
//return Json(new
//{
// longitude = point.XCoordinate,
// latitude = point.YCoordinate,
// Street = result.Response.Docs.FirstOrDefault().StraatNaam,
// City = result.Response.Docs.FirstOrDefault().GemeenteNaam,
// Province = result.Response.Docs.FirstOrDefault().ProvincieNaam,
// Country = "Nederland",
//});
}
else
{
return Json(new { error = result.Response.NumFound + " addressen gevonden met deze postcode" });
}
}
catch (Exception e)
{
return Json(new { error = e.Message });
}
}
return Json(new { error = "Geen postcode opgegeven" });
}
// GET: Locations
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin, Viewer")]
public async Task<ActionResult> Index(string sortOrder)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
IQueryable<Location> locationlist = db.Locations
.Where(i => i.Active != ActiveStates.Deleted)
.Include(d => d.Devices)
.AsNoTracking();
Cookies.SetRedirectCookie(Response.Cookies, "Locations", "Index");
return View(await Sorting.SortLocationsList(sortOrder, locationlist).ToListAsync());
}
//--------------------- View Locations ----------------------------------------------
// GET: Locations/View/5
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public async Task<ActionResult> View(string sortOrder, int? locationId)
{
if (locationId == null)
{
return BadRequest();
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
LocationViewModel locationView = new()
{
Location = await db.Locations.FindAsync(locationId)
};
if (locationView.Location == null)
{
return NotFound();
}
locationView.Devices = await Sorting.SortDeviceList(sortOrder, db.Devices.Where(u => u.LocationId == locationView.Location.Id && u.Active != ActiveStates.Deleted)).ToListAsync();
return View(locationView);
}
// GET: Locations/Create
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public ActionResult Create()
{
return View(new Location());
}
// POST: Locations/Create
[HttpPost]
[Authorize(Roles = "Administrator, DeviceAdmin")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Location location)
{
if (ModelState.IsValid)
{
if (location == null)
{
throw new ArgumentNullException(nameof(location), "Create Location, location is null.");
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
location.LastChanged = DateTime.Now;
location.Active = ActiveStates.Active;
db.Locations.Add(location);
AcsLogging.Add(User.Identity, $"Locatie {location.AddressString} aangemaakt", LogTypes.System, db);
await db.SaveChangesAsync();
return Helpers.Cookies.RedirectToCookie(Request.Cookies);
}
return View(location);
}
// GET: Locations/Edit/5
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return BadRequest();
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Location locations = await db.Locations.FindAsync(id);
if (locations == null)
{
return NotFound();
}
return View(locations);
}
// POST: Locations/Edit/5
[HttpPost]
[Authorize(Roles = "Administrator, DeviceAdmin")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(Location location)
{
if (ModelState.IsValid)
{
if (location == null)
{
throw new ArgumentNullException(nameof(location), "Edit Location, location is null.");
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
location.LastChanged = DateTime.Now;
location.Active = ActiveStates.Active;
db.Entry(location).State = EntityState.Modified;
AcsLogging.Add(User.Identity, $"Locatie {location.AddressString} bewerkt", LogTypes.System, db);
await db.SaveChangesAsync();
return Helpers.Cookies.RedirectToCookie(Request.Cookies);
}
return View(location);
}
// GET: Locations/Delete/5
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return BadRequest();
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Location locations = await db.Locations.FindAsync(id);
if (locations == null)
{
return NotFound();
}
return View(locations);
}
// POST: Locations/Delete/5
[HttpPost, ActionName("Delete")]
[Authorize(Roles = "Administrator, DeviceAdmin")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Location location = db.Locations.Find(id);
if (location == null)
{
return BadRequest();
}
location.LastChanged = DateTime.Now;
location.Active = ActiveStates.Deleted;
db.Entry(location).State = EntityState.Modified;
AcsLogging.Add(User.Identity, "Locatie " + location.AddressString + " verwijderd", LogTypes.System, db);
await db.SaveChangesAsync();
return Helpers.Cookies.RedirectToCookie(Request.Cookies);
}
}
}

View File

@@ -0,0 +1,293 @@
using Aperio_Control_Centre.ACSDatabase;
using Aperio_Control_Centre.ACSDatabase.Types;
using Aperio_Control_Centre.Models;
using Aperio_Control_Centre.PagedList;
using Aperio_Control_Centre.PagedList.MVC;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data;
namespace Aperio_Control_Centre.Controllers
{
public class LoggingsController(IDbContextFactory<ACSDatabaseContext> dbContextFactory) : Controller
{
private readonly IDbContextFactory<ACSDatabaseContext> _contextFactory = dbContextFactory;
// GET: Index Loggings
[HttpGet]
[Authorize(Roles = "Administrator,Viewer")]
public async Task<ActionResult> Index(int? page, int? pageSize, DateTime? startLogdate, DateTime? endLogdate)
{
PagedLoggingsModel loggings = new();
Helpers.Cookies.SetRedirectCookie(Response.Cookies, "Loggings", "Index");
loggings.Page = PageListHelper.GetPage(page);
loggings.PageSize = PageListHelper.GetPageSize(pageSize, Request);
Helpers.Cookies.SetPageListSizeCookie(Response.Cookies, loggings.PageSize);
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
loggings.StartLogdate = await PageListHelper.GetStartDate(startLogdate, db);
loggings.EndLogdate = PageListHelper.GetEndDate(endLogdate);
loggings.Loggings = await db.Loggings
.Where(d => d.Time >= loggings.StartLogdate)
.Where(d => d.Time <= loggings.EndLogdate)
.Include(i => i.User)
.Include(i => i.Device)
.Include(i => i.Device.Location)
.OrderByDescending(t => t.Time)
.AsNoTracking()
.ToPagedListAsync(loggings.Page, loggings.PageSize);
return View(loggings);
}
// GET: User Loggings
[HttpGet]
[Authorize(Roles = "Administrator,Viewer")]
public async Task<ActionResult> UserLog(int? page, int? pageSize, DateTime? startLogdate, DateTime? endLogdate)
{
PagedLoggingsModel loggings = new();
Helpers.Cookies.SetRedirectCookie(Response.Cookies, "Loggings", "UserLog");
loggings.Page = PageListHelper.GetPage(page);
loggings.PageSize = PageListHelper.GetPageSize(pageSize, Request);
Helpers.Cookies.SetPageListSizeCookie(Response.Cookies, loggings.PageSize);
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
loggings.StartLogdate = await PageListHelper.GetStartDate(startLogdate, db);
loggings.EndLogdate = PageListHelper.GetEndDate(endLogdate);
loggings.Loggings = await db.Loggings
.Where(d => d.Time >= loggings.StartLogdate)
.Where(d => d.Time <= loggings.EndLogdate)
.Where(l => l.LogType == LogTypes.User)
.Include(i => i.User)
.Include(i => i.Device)
.Include(i => i.Device.Location)
.OrderByDescending(t => t.Time)
.AsNoTracking()
.ToPagedListAsync(loggings.Page, loggings.PageSize);
return View(loggings);
}
// GET: Access denied Loggings
[HttpGet]
[Authorize(Roles = "Administrator,Viewer")]
public async Task<ActionResult> AccessDenied(int? page, int? pageSize, DateTime? startLogdate, DateTime? endLogdate)
{
PagedLoggingsModel loggings = new();
Helpers.Cookies.SetRedirectCookie(Response.Cookies, "Loggings", "AccessDenied");
loggings.Page = PageListHelper.GetPage(page);
loggings.PageSize = PageListHelper.GetPageSize(pageSize, Request);
Helpers.Cookies.SetPageListSizeCookie(Response.Cookies, loggings.PageSize);
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
loggings.StartLogdate = await PageListHelper.GetStartDate(startLogdate, db);
loggings.EndLogdate = PageListHelper.GetEndDate(endLogdate);
loggings.Loggings = await db.Loggings
.Where(d => d.Time >= loggings.StartLogdate)
.Where(d => d.Time <= loggings.EndLogdate)
.Where(l => l.LogType == LogTypes.User && l.Access != AccessTypes.Granted && l.Access.HasValue)
.Include(i => i.User)
.Include(i => i.Device)
.Include(i => i.Device.Location)
.OrderByDescending(t => t.Time)
.AsNoTracking()
.ToPagedListAsync(loggings.Page, loggings.PageSize);
return View(loggings);
}
// GET: Unknown User Loggings
[HttpGet]
[Authorize(Roles = "Administrator,Viewer")]
public async Task<ActionResult> UnknownUserLog(int? page, int? pageSize, DateTime? startLogdate, DateTime? endLogdate)
{
PagedLoggingsModel loggings = new();
Helpers.Cookies.SetRedirectCookie(Response.Cookies, "Loggings", "UnknownUserLog");
loggings.Page = PageListHelper.GetPage(page);
loggings.PageSize = PageListHelper.GetPageSize(pageSize, Request);
Helpers.Cookies.SetPageListSizeCookie(Response.Cookies, loggings.PageSize);
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
loggings.StartLogdate = await PageListHelper.GetStartDate(startLogdate, db);
loggings.EndLogdate = PageListHelper.GetEndDate(endLogdate);
loggings.Loggings = await db.Loggings
.Where(d => d.Time >= loggings.StartLogdate)
.Where(d => d.Time <= loggings.EndLogdate)
.Where(l => l.LogType == LogTypes.UnknownUser)
.Include(i => i.User)
.Include(i => i.Device)
.Include(i => i.Device.Location)
.OrderByDescending(t => t.Time)
.AsNoTracking()
.ToPagedListAsync(loggings.Page, loggings.PageSize);
return View(loggings);
}
// GET: Device Loggings
[HttpGet]
[Authorize(Roles = "Administrator,Viewer")]
public async Task<ActionResult> DeviceLog(int? page, int? pageSize, DateTime? startLogdate, DateTime? endLogdate)
{
PagedLoggingsModel loggings = new();
Helpers.Cookies.SetRedirectCookie(Response.Cookies, "Loggings", "DeviceLog");
loggings.Page = PageListHelper.GetPage(page);
loggings.PageSize = PageListHelper.GetPageSize(pageSize, Request);
Helpers.Cookies.SetPageListSizeCookie(Response.Cookies, loggings.PageSize);
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
loggings.StartLogdate = await PageListHelper.GetStartDate(startLogdate, db);
loggings.EndLogdate = PageListHelper.GetEndDate(endLogdate);
loggings.Loggings = await db.Loggings
.Where(d => d.Time >= loggings.StartLogdate)
.Where(d => d.Time <= loggings.EndLogdate)
.Where(l => l.LogType == LogTypes.Device || l.LogType == LogTypes.Bootlog)
.Include(i => i.User)
.Include(i => i.Device)
.Include(i => i.Device.Location)
.OrderByDescending(t => t.Time)
.AsNoTracking()
.ToPagedListAsync(loggings.Page, loggings.PageSize);
return View(loggings);
}
// GET: DTC Loggings
[HttpGet]
[Authorize(Roles = "Administrator,Viewer")]
public async Task<ActionResult> DTCLog(int? page, int? pageSize, DateTime? startLogdate, DateTime? endLogdate)
{
PagedLoggingsModel loggings = new();
Helpers.Cookies.SetRedirectCookie(Response.Cookies, "Loggings", "DTCLog");
loggings.Page = PageListHelper.GetPage(page);
loggings.PageSize = PageListHelper.GetPageSize(pageSize, Request);
Helpers.Cookies.SetPageListSizeCookie(Response.Cookies, loggings.PageSize);
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
loggings.StartLogdate = await PageListHelper.GetStartDate(startLogdate, db);
loggings.EndLogdate = PageListHelper.GetEndDate(endLogdate);
loggings.Loggings = await db.Loggings
.Where(d => d.Time >= loggings.StartLogdate)
.Where(d => d.Time <= loggings.EndLogdate)
.Where(l => l.LogType == LogTypes.DTC)
.Include(i => i.Device)
.Include(i => i.Device.Location)
.OrderByDescending(t => t.Time)
.AsNoTracking()
.ToPagedListAsync(loggings.Page, loggings.PageSize);
return View(loggings);
}
// GET: System Loggings
[HttpGet]
[Authorize(Roles = "Administrator,Viewer")]
public async Task<ActionResult> SystemLog(int? page, int? pageSize, DateTime? startLogdate, DateTime? endLogdate)
{
PagedLoggingsModel loggings = new();
Helpers.Cookies.SetRedirectCookie(Response.Cookies, "Loggings", "SystemLog");
loggings.Page = PageListHelper.GetPage(page);
loggings.PageSize = PageListHelper.GetPageSize(pageSize, Request);
Helpers.Cookies.SetPageListSizeCookie(Response.Cookies, loggings.PageSize);
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
loggings.StartLogdate = await PageListHelper.GetStartDate(startLogdate, db);
loggings.EndLogdate = PageListHelper.GetEndDate(endLogdate);
loggings.Loggings = await db.Loggings
.Where(d => d.Time >= loggings.StartLogdate)
.Where(d => d.Time <= loggings.EndLogdate)
.Where(l => l.LogType == LogTypes.System)
.OrderByDescending(t => t.Time)
.AsNoTracking()
.ToPagedListAsync(loggings.Page, loggings.PageSize);
return View(loggings);
}
// GET: Boot Loggings
[HttpGet]
[Authorize(Roles = "Administrator,Viewer")]
public async Task<ActionResult> BootLog(int? page, int? pageSize, DateTime? startLogdate, DateTime? endLogdate)
{
PagedLoggingsModel loggings = new();
Helpers.Cookies.SetRedirectCookie(Response.Cookies, "Loggings", "DTCLog");
loggings.Page = PageListHelper.GetPage(page);
loggings.PageSize = PageListHelper.GetPageSize(pageSize, Request);
Helpers.Cookies.SetPageListSizeCookie(Response.Cookies, loggings.PageSize);
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
loggings.StartLogdate = await PageListHelper.GetStartDate(startLogdate, db);
loggings.EndLogdate = PageListHelper.GetEndDate(endLogdate);
loggings.Loggings = await db.Loggings
.Where(d => d.Time >= loggings.StartLogdate)
.Where(d => d.Time <= loggings.EndLogdate)
.Where(l => l.LogType == LogTypes.Bootlog)
.Include(i => i.Device)
.Include(i => i.Device.Location)
.OrderByDescending(t => t.Time)
.AsNoTracking()
.ToPagedListAsync(loggings.Page, loggings.PageSize);
return View(loggings);
}
// GET: Manual Open Loggings
[HttpGet]
[Authorize(Roles = "Administrator,Viewer")]
public async Task<ActionResult> ManualOpenLog(int? page, int? pageSize, DateTime? startLogdate, DateTime? endLogdate)
{
PagedLoggingsModel loggings = new();
Helpers.Cookies.SetRedirectCookie(Response.Cookies, "Loggings", "ManualOpenLog");
loggings.Page = PageListHelper.GetPage(page);
loggings.PageSize = PageListHelper.GetPageSize(pageSize, Request);
Helpers.Cookies.SetPageListSizeCookie(Response.Cookies, loggings.PageSize);
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
loggings.StartLogdate = await PageListHelper.GetStartDate(startLogdate, db);
loggings.EndLogdate = PageListHelper.GetEndDate(endLogdate);
loggings.Loggings = await db.Loggings
.Where(d => d.Time >= loggings.StartLogdate)
.Where(d => d.Time <= loggings.EndLogdate)
.Where(l => l.LogType == LogTypes.ManualOpen)
.Include(i => i.Device)
.Include(i => i.Device.Location)
.OrderByDescending(t => t.Time)
.AsNoTracking()
.ToPagedListAsync(loggings.Page, loggings.PageSize);
return View(loggings);
}
}
}

View File

@@ -0,0 +1,243 @@
using Aperio_Control_Centre.ACSDatabase;
using Aperio_Control_Centre.ACSDatabase.Models;
using Aperio_Control_Centre.ACSDatabase.Types;
using Aperio_Control_Centre.Helpers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data;
using System.Net;
namespace Aperio_Control_Centre.Controllers
{
public class TimezoneController(IDbContextFactory<ACSDatabaseContext> dbContextFactory) : Controller
{
private readonly IDbContextFactory<ACSDatabaseContext> _contextFactory = dbContextFactory;
// GET: /Timezone/
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin, Viewer")]
public async Task<ActionResult> Index()
{
Helpers.Cookies.SetRedirectCookie(Response.Cookies, "Timezone", "Index");
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
return View(await db.Timezones
.Where(m => m.Active != ActiveStates.Deleted)
.Include(g => g.Groups)
.Include(d => d.Devices.Select(l => l.Location))
.ToListAsync());
}
//-------------------------- Create --------------------------------------
// GET: /Timezone/Create
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public ActionResult Create()
{
return View(new Timezone());
}
// POST: /Timezone/Create
[Authorize(Roles = "Administrator, DeviceAdmin")]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Timezone timezone)
{
if (ModelState.IsValid)
{
if (timezone == null)
{
throw new ArgumentNullException(nameof(timezone), "Create Timezones, timezone is null.");
}
timezone.Active = ActiveStates.Active;
timezone.LastChanged = DateTime.Now;
timezone.WeekDays = CreateweekDaysTypes(timezone);
if (timezone.WholeDayTime)
{
timezone.TwentyFourHours = TwentyFourHoursTypes.TwentyFourHours;
}
else
{
timezone.TwentyFourHours = TwentyFourHoursTypes.Timeselected;
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
db.Timezones.Add(timezone);
AcsLogging.Add(User.Identity, "Tijdzone " + timezone.Name + " aangemaakt", LogTypes.System, db);
await db.SaveChangesAsync();
return Helpers.Cookies.RedirectToCookie(Request.Cookies);
}
return View(timezone);
}
//-------------------------- Edit --------------------------------------
// GET: /Timezone/Edit/5
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return BadRequest();
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Timezone timezones = await db.Timezones
.Where(i => i.Id == id)
.Include(g => g.Groups)
.Include(d => d.Devices.Select(l => l.Location))
.SingleOrDefaultAsync();
if (timezones == null)
{
return NotFound();
}
timezones.AllDays = timezones.WeekDays.HasFlag(WeekDaysTypes.Daily);
timezones.Monday = timezones.WeekDays.HasFlag(WeekDaysTypes.Monday);
timezones.Tuesday = timezones.WeekDays.HasFlag(WeekDaysTypes.Tuesday);
timezones.Wednesday = timezones.WeekDays.HasFlag(WeekDaysTypes.Wednesday);
timezones.Thursday = timezones.WeekDays.HasFlag(WeekDaysTypes.Thursday);
timezones.Friday = timezones.WeekDays.HasFlag(WeekDaysTypes.Friday);
timezones.Saturday = timezones.WeekDays.HasFlag(WeekDaysTypes.Saturday);
timezones.Sunday = timezones.WeekDays.HasFlag(WeekDaysTypes.Sunday);
if (timezones.TwentyFourHours == TwentyFourHoursTypes.TwentyFourHours)
{
timezones.WholeDayTime = true;
}
return View(timezones);
}
// POST: /Timezone/Edit/5
[Authorize(Roles = "Administrator, DeviceAdmin")]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(Timezone timezone)
{
if (ModelState.IsValid)
{
if (timezone == null)
{
throw new ArgumentNullException(nameof(timezone), "Edit Timezones, timezone is null.");
}
timezone.Active = ActiveStates.Active;
timezone.LastChanged = DateTime.Now;
timezone.WeekDays = CreateweekDaysTypes(timezone);
if (timezone.WholeDayTime)
{
timezone.TwentyFourHours = TwentyFourHoursTypes.TwentyFourHours;
}
else
{
timezone.TwentyFourHours = TwentyFourHoursTypes.Timeselected;
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
db.Entry(timezone).State = EntityState.Modified;
AcsLogging.Add(User.Identity, "Tijdzone " + timezone.Name + " bewerkt", LogTypes.System, db);
await db.SaveChangesAsync();
return Helpers.Cookies.RedirectToCookie(Request.Cookies);
}
return View(timezone);
}
//-------------------------- Delete --------------------------------------
// GET: /Timezone/Delete/5
[HttpGet]
[Authorize(Roles = "Administrator, DeviceAdmin")]
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return BadRequest();
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Timezone timezones = await db.Timezones.FindAsync(id);
if (timezones == null)
{
return NotFound();
}
return View(timezones);
}
// POST: /Timezone/Delete/5
[Authorize(Roles = "Administrator, DeviceAdmin")]
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
Timezone timezone = db.Timezones.Find(id);
if (timezone == null)
{
return NotFound();
}
timezone.Active = ActiveStates.Deleted;
timezone.LastChanged = DateTime.Now;
db.Entry(timezone).State = EntityState.Modified;
AcsLogging.Add(User.Identity, "Tijdzone " + timezone.Name + " verwijderd", LogTypes.System, db);
await db.SaveChangesAsync();
return Helpers.Cookies.RedirectToCookie(Request.Cookies);
}
//-------------------------- private functions --------------------------------------
private static WeekDaysTypes CreateweekDaysTypes(Timezone timezones)
{
WeekDaysTypes newweekdaystypes = new();
if (timezones.AllDays)
newweekdaystypes |= WeekDaysTypes.Daily;
else
newweekdaystypes &= ~WeekDaysTypes.Daily;
if (timezones.Monday)
newweekdaystypes |= WeekDaysTypes.Monday;
else
newweekdaystypes &= ~WeekDaysTypes.Monday;
if (timezones.Tuesday)
newweekdaystypes |= WeekDaysTypes.Tuesday;
else
newweekdaystypes &= ~WeekDaysTypes.Tuesday;
if (timezones.Wednesday)
newweekdaystypes |= WeekDaysTypes.Wednesday;
else
newweekdaystypes &= ~WeekDaysTypes.Wednesday;
if (timezones.Thursday)
newweekdaystypes |= WeekDaysTypes.Thursday;
else
newweekdaystypes &= ~WeekDaysTypes.Thursday;
if (timezones.Friday)
newweekdaystypes |= WeekDaysTypes.Friday;
else
newweekdaystypes &= ~WeekDaysTypes.Friday;
if (timezones.Saturday)
newweekdaystypes |= WeekDaysTypes.Saturday;
else
newweekdaystypes &= ~WeekDaysTypes.Saturday;
if (timezones.Sunday)
newweekdaystypes |= WeekDaysTypes.Sunday;
else
newweekdaystypes &= ~WeekDaysTypes.Sunday;
return newweekdaystypes;
}
}
}

View File

@@ -5,9 +5,9 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc.Rendering;
using Aperio_Control_Centre.ACSDatabase;
using Aperio_Control_Centre.Identity;
using Aperio_Control_Centre.Frontend.Helpers;
using Aperio_Control_Centre.Frontend.Models;
using Aperio_Control_Centre.ACSDatabase.Types;
using Aperio_Control_Centre.Helpers;
namespace Aperio_Control_Centre.Controllers
{

View File

@@ -0,0 +1,610 @@
using Aperio_Control_Centre.ACSDatabase;
using Aperio_Control_Centre.ACSDatabase.Models;
using Aperio_Control_Centre.ACSDatabase.Types;
using Aperio_Control_Centre.Helpers;
using Aperio_Control_Centre.Models;
using Aperio_Control_Centre.PagedList;
using Aperio_Control_Centre.PagedList.MVC;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data;
using System.Net;
using System.Security.Principal;
namespace Aperio_Control_Centre.Controllers
{
public class UserController(IDbContextFactory<ACSDatabaseContext> dbContextFactory) : Controller
{
private readonly IDbContextFactory<ACSDatabaseContext> _contextFactory = dbContextFactory;
// GET: /User/
[HttpGet]
[Authorize(Roles = "Administrator,UserAdmin,Viewer")]
public async Task<ActionResult> Index(string sortOrder)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
var userlist = db.Users
.Where(t => t.Active != ActiveStates.Deleted)
.Include(I => I.Group)
.Include(I => I.Group.Timezone)
.Include(I => I.Department)
.AsNoTracking();
Cookies.SetRedirectCookie(Response.Cookies, "User", "Index");
if (String.IsNullOrEmpty(sortOrder))
{
if (Request.Cookies.ContainsKey("AllUserSort") == true)
{
return View(await Sorting.SortUserList(Request.Cookies["AllUserSort"], userlist).ToListAsync());
}
}
Cookies.SetSortorderCookie(Response.Cookies, "AllUserSort", sortOrder);
return View(await Sorting.SortUserList(sortOrder, userlist).ToListAsync());
}
// ------------------ ActiveList ----------------------------------------
// GET: /User/ActiveList
[HttpGet]
[Authorize(Roles = "Administrator,UserAdmin,Viewer")]
public async Task<ActionResult> ActiveList(string sortOrder)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
IQueryable<User> userlist = db.Users
.Where(t => t.Active == ActiveStates.Active)
.Include(I => I.Group)
.Include(I => I.Group.Timezone)
.Include(I => I.Department)
.AsNoTracking();
Cookies.SetRedirectCookie(Response.Cookies, "User", "ActiveList");
if (String.IsNullOrEmpty(sortOrder))
{
if (Request.Cookies.ContainsKey("ActiveUserSort") == true)
{
return View(await Sorting.SortUserList(Request.Cookies["ActiveUserSort"], userlist).ToListAsync());
}
}
Cookies.SetSortorderCookie(Response.Cookies, "ActiveUserSort", sortOrder);
return View(await Sorting.SortUserList(sortOrder, userlist).ToListAsync());
}
// POST: /User/ActiveList
[HttpPost]
[Authorize(Roles = "Administrator,UserAdmin")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ActiveList(int[] SelectedItems, string action)
{
if (SelectedItems != null)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
switch (action)
{
case "block":
BlockUsers(User.Identity, SelectedItems, db);
break;
case "delete":
DeleteUsers(User.Identity, SelectedItems, db);
break;
default:
break;
}
await db.SaveChangesAsync();
}
return Cookies.RedirectToCookie(Request.Cookies);
}
// ------------------ NewList ----------------------------------------
// GET: /User/newlist
[HttpGet]
[Authorize(Roles = "Administrator,UserAdmin,Viewer")]
public async Task<ActionResult> NewList(string sortOrder)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
var userlist = db.Users
.Where(t => t.Active == ActiveStates.New)
.Include(I => I.Group)
.Include(I => I.Group.Timezone)
.Include(I => I.Department)
.AsNoTracking();
Cookies.SetRedirectCookie(Response.Cookies, "User", "NewList");
if (String.IsNullOrEmpty(sortOrder))
{
if (Request.Cookies.ContainsKey("NewUserSort") == true)
{
return View(await Sorting.SortUserList(Request.Cookies["NewUserSort"], userlist).ToListAsync());
}
}
Cookies.SetSortorderCookie(Response.Cookies, "NewUserSort", sortOrder);
return View(await Sorting.SortUserList(sortOrder, userlist).ToListAsync());
}
// POST: /User/newlist
[HttpPost]
[Authorize(Roles = "Administrator,UserAdmin")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> NewList(int[] SelectedItems, string action)
{
if (SelectedItems != null)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
switch (action)
{
case "activate":
DeblockUsers(User.Identity, SelectedItems, db);
break;
case "block":
BlockUsers(User.Identity, SelectedItems, db);
break;
case "delete":
DeleteUsers(User.Identity, SelectedItems, db);
break;
default:
break;
}
await db.SaveChangesAsync();
}
return Cookies.RedirectToCookie(Request.Cookies);
}
// ------------------ InactiveList ----------------------------------------
// GET: /User/InactiveList
[HttpGet]
[Authorize(Roles = "Administrator,UserAdmin,Viewer")]
public async Task<ActionResult> InactiveList(string sortOrder)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
var userlist = db.Users
.Where(t => t.Active == ActiveStates.Inactive)
.Include(I => I.Group)
.Include(I => I.Group.Timezone)
.Include(I => I.Department)
.AsNoTracking();
Cookies.SetRedirectCookie(Response.Cookies, "User", "InactiveList");
if (String.IsNullOrEmpty(sortOrder))
{
if (Request.Cookies.ContainsKey("InactiveUserSort") == true)
{
return View(await Sorting.SortUserList(Request.Cookies["InactiveUserSort"], userlist).ToListAsync());
}
}
Cookies.SetSortorderCookie(Response.Cookies, "InactiveUserSort", sortOrder);
return View(await Sorting.SortUserList(sortOrder, userlist).ToListAsync());
}
// POST: /User/InactiveList
[Authorize(Roles = "Administrator,UserAdmin")]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> InactiveList(int[] SelectedItems, string action)
{
if (SelectedItems != null)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
switch (action)
{
case "activate":
DeblockUsers(User.Identity, SelectedItems, db);
break;
case "delete":
DeleteUsers(User.Identity, SelectedItems, db);
break;
default:
break;
}
await db.SaveChangesAsync();
}
return Cookies.RedirectToCookie(Request.Cookies);
}
//---------------------------- Create -----------------------------------------
// GET: /User/Create
[HttpGet]
[Authorize(Roles = "Administrator,UserAdmin")]
public async Task<ActionResult> Create()
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
return View(new User
{
CredentialType = CredentialTypes.Mifare,
DepartmentsSelectList = await SelectListHelpers.DepartmentsSelectList(db),
GroupsSelectList = await SelectListHelpers.GroupsSelectList(db)
});
}
// POST: /User/Create
[Authorize(Roles = "Administrator,UserAdmin")]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(User user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user), "Create user, user is null");
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
if (ModelState.IsValid)
{
if (await db.Users.Where(x => x.CredentialString == user.CredentialString && x.Active != ActiveStates.Deleted).AnyAsync())
{
if (user.CredentialType == CredentialTypes.Keypad)
{
ModelState.AddModelError(string.Empty, "Pincode bestaat al");
}
else
{
ModelState.AddModelError(string.Empty, "UID nummer bestaat al");
}
user.DepartmentsSelectList = await SelectListHelpers.DepartmentsSelectList(db);
user.GroupsSelectList = await SelectListHelpers.GroupsSelectList(db);
return View(user);
}
user.Created = DateTime.Now;
user.LastChanged = DateTime.Now;
user.Active = ActiveStates.New;
db.Users.Add(user);
AcsLogging.Add(User.Identity, "Pas aangemaakt", LogTypes.User, user, db);
if (user.GroupId.HasValue)
{
Group group = await db.Groups.FindAsync(user.GroupId);
AcsLogging.Add(User.Identity, $"Toegevoegd aan groep {group.Name}", LogTypes.User, user, db);
}
await db.SaveChangesAsync();
return Cookies.RedirectToCookie(Request.Cookies);
}
user.DepartmentsSelectList = await SelectListHelpers.DepartmentsSelectList(db);
user.GroupsSelectList = await SelectListHelpers.GroupsSelectList(db);
return View(user);
}
// GET: /User/Create
[HttpGet]
[Authorize(Roles = "Administrator,UserAdmin")]
public ActionResult SL040Settings()
{
return View();
}
//---------------------------- Edit -----------------------------------------
// GET: /User/Edit/5
[HttpGet]
[Authorize(Roles = "Administrator,UserAdmin")]
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return BadRequest();
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
User user = await db.Users
.Where(i => i.Id == id)
.Include(g => g.Group.Timezone)
.SingleOrDefaultAsync();
if (user == null)
{
return NotFound();
}
user.DepartmentsSelectList = await SelectListHelpers.DepartmentsSelectList(db);
user.GroupsSelectList = await SelectListHelpers.GroupsSelectList(db);
user.LastLoggings = await AcsLogging.LastUserLoggings(user, 25, db);
user.DeviceAccessList = await db.DeviceGroupJoins
.Where(g => g.GroupId == user.GroupId)
.Select(s => s.Device)
.Where(d => d.Active == ActiveStates.Active)
.Include(l => l.Location)
.ToListAsync();
return View(user);
}
// POST: /User/Edit/5
[Authorize(Roles = "Administrator,UserAdmin")]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(User user)
{
if (ModelState.IsValid)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user), "Edit user, user is null");
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
User oldUser = db.Users.Find(user.Id);
if (oldUser.CredentialString != user.CredentialString)
{
var checkcredentials = await db.Users.Where(x => x.CredentialString == user.CredentialString && x.Active != ActiveStates.Deleted).AnyAsync();
if (checkcredentials == true)
{
if (user.CredentialType == CredentialTypes.Keypad)
{
ViewBag.message = "Pincode bestaat al";
}
else
{
ViewBag.message = "Pas nummer bestaat al";
}
return View(user);
}
}
if (oldUser.GroupId != user.GroupId)
{
if (user.GroupId.HasValue)
{
AcsLogging.Add(User.Identity, "Pas naar groep " + db.Groups.Find(user.GroupId).Name, LogTypes.User, user, db);
}
else
{
AcsLogging.Add(User.Identity, "Pas uit alle groepen", LogTypes.User, user, db);
}
}
db.Entry(oldUser).State = EntityState.Detached;
if (user.GroupId.HasValue == false)
{
if (user.Active != ActiveStates.New)
{
user.Active = ActiveStates.Inactive;
}
}
user.LastChanged = DateTime.Now;
db.Entry(user).State = EntityState.Modified;
AcsLogging.Add(User.Identity, "Pas bewerkt", LogTypes.User, user, db);
await db.SaveChangesAsync();
return Cookies.RedirectToCookie(Request.Cookies);
}
return View(user);
}
//---------------------------- Delete -----------------------------------------
// GET: /User/Delete/5
[HttpGet]
[Authorize(Roles = "Administrator,UserAdmin")]
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return BadRequest();
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
User user = await db.Users
.Where(i => i.Id == id)
.Include(d => d.Department)
.Include(g => g.Group)
.SingleOrDefaultAsync();
if (user == null)
{
return NotFound();
}
ViewBag.returnController = Request.Cookies["Controller"];
ViewBag.returnPage = Request.Cookies["Action"];
return View(user);
}
// POST: /User/Delete/5
[Authorize(Roles = "Administrator,UserAdmin")]
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
DeleteUser(User.Identity, id, db);
await db.SaveChangesAsync();
return Cookies.RedirectToCookie(Request.Cookies);
}
private static void DeleteUsers(IIdentity identity, int[] usersIds, ACSDatabaseContext db)
{
foreach (int user in usersIds)
{
DeleteUser(identity, user, db);
}
}
private static void DeleteUser(IIdentity identity, int id, ACSDatabaseContext db)
{
User user = db.Users.Find(id);
user.Active = ActiveStates.Deleted;
user.LastChanged = DateTime.Now;
AcsLogging.Add(identity, "Pas verwijderd", LogTypes.User, user, db);
}
//---------------------------- Block -----------------------------------------
// GET: /User/Block/5
[HttpGet]
[Authorize(Roles = "Administrator,UserAdmin")]
public async Task<ActionResult> Block(int? id)
{
if (id == null)
{
return BadRequest();
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
User user = await db.Users
.Where(i => i.Id == id)
.Include(d => d.Department)
.Include(g => g.Group)
.SingleOrDefaultAsync();
if (user == null)
{
return NotFound();
}
ViewBag.returnController = Request.Cookies["Controller"];
ViewBag.returnPage = Request.Cookies["Action"];
return View(user);
}
// POST: /User/Block/5
[Authorize(Roles = "Administrator,UserAdmin")]
[HttpPost, ActionName("Block")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> BlockConfirmed(int id)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
BlockUser(User.Identity, id, db);
await db.SaveChangesAsync();
return Cookies.RedirectToCookie(Request.Cookies);
}
private static void BlockUsers(IIdentity identity, int[] usersIds, ACSDatabaseContext db)
{
foreach (int user in usersIds)
{
BlockUser(identity, user, db);
}
}
private static void BlockUser(IIdentity identity, int id, ACSDatabaseContext db)
{
User user = db.Users.Find(id);
if (user.CredentialType != CredentialTypes.Unknown)
{
user.Active = ActiveStates.Inactive;
user.LastChanged = DateTime.Now;
}
AcsLogging.Add(identity, "Pas geblokkeerd", LogTypes.User, user, db);
}
//---------------------------- Deblock -----------------------------------------
// GET: /User/Deblock/5
[HttpGet]
[Authorize(Roles = "Administrator,UserAdmin")]
public async Task<ActionResult> Deblock(int? id)
{
if (id == null)
{
return BadRequest();
}
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
User user = await db.Users
.Where(i => i.Id == id)
.Include(d => d.Department)
.Include(g => g.Group)
.SingleOrDefaultAsync();
if (user == null)
{
return NotFound();
}
ViewBag.returnController = Request.Cookies["Controller"];
ViewBag.returnPage = Request.Cookies["Action"];
return View(user);
}
// POST: /User/deblock/5
[Authorize(Roles = "Administrator,UserAdmin")]
[HttpPost, ActionName("Deblock")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeblockConfirmed(int id)
{
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
DeblockUser(User.Identity, id, db);
await db.SaveChangesAsync();
return Cookies.RedirectToCookie(Request.Cookies);
}
private static void DeblockUsers(IIdentity identity, int[] usersIds, ACSDatabaseContext db)
{
foreach (int user in usersIds)
{
DeblockUser(identity, user, db);
}
}
private static void DeblockUser(IIdentity identity, int id, ACSDatabaseContext db)
{
User user = db.Users.Find(id);
if (user.CredentialType != CredentialTypes.Unknown)
{
user.Active = ActiveStates.Active;
user.LastChanged = DateTime.Now;
}
AcsLogging.Add(identity, "Pas geactiveerd", LogTypes.User, user, db);
}
//---------------------------- Log -----------------------------------------
// GET: User Loggings
[HttpGet]
[Authorize(Roles = "Administrator,UserAdmin")]
public async Task<ActionResult> Log(int? id, int? page, int? pageSize, DateTime? startLogdate, DateTime? endLogdate)
{
if (id == null)
{
return BadRequest();
}
SelectedLog loggings = new();
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
loggings.SelectedUser = await db.Users.FindAsync(id);
if (loggings.SelectedUser == null)
{
return NotFound();
}
Cookies.SetRedirectCookie(Response.Cookies, "User", $"Log/{id}");
loggings.PagedLoggings.Page = PageListHelper.GetPage(page);
loggings.PagedLoggings.PageSize = PageListHelper.GetPageSize(pageSize, Request);
Cookies.SetPageListSizeCookie(Response.Cookies, loggings.PagedLoggings.PageSize);
loggings.PagedLoggings.StartLogdate = await PageListHelper.GetStartDate(startLogdate, db);
loggings.PagedLoggings.EndLogdate = PageListHelper.GetEndDate(endLogdate);
loggings.PagedLoggings.Loggings = await db.Loggings
.Where(d => d.Time >= loggings.PagedLoggings.StartLogdate)
.Where(d => d.Time <= loggings.PagedLoggings.EndLogdate)
.Where(u => u.UserId == id)
.OrderByDescending(m => m.Time)
.Include(i => i.User)
.Include(i => i.Device)
.Include(i => i.Device.Location)
.AsNoTracking()
.ToPagedListAsync(loggings.PagedLoggings.Page, loggings.PagedLoggings.PageSize);
return View(loggings);
}
//---------------------------- Json check -----------------------------------------
//Kijk of de gebruiker al bestaat in de database
[HttpGet]
[Authorize(Roles = "Administrator,UserAdmin")]
public async Task<JsonResult> VerifyCredentails(string credentialString, int? id)
{
//Debug.WriteLine($"cred = {credentialString}");
//Debug.WriteLine($"id = {id}");
using ACSDatabaseContext db = await _contextFactory.CreateDbContextAsync();
if (await db.Users.Where(c => c.CredentialString == credentialString).Where(i => i.Id != id).Where(c => c.Active != ActiveStates.Deleted).AnyAsync())
{
return Json($"UID {credentialString} is already in use.");
}
return Json(true);
}
}
}

View File

@@ -0,0 +1,21 @@
using System.ComponentModel.DataAnnotations;
using System.Reflection;
namespace Aperio_Control_Centre.Extensions
{
public static class EnumExtension
{
public static string GetDisplayName(this Enum enumValue)
{
if (enumValue == null)
{
throw new ArgumentNullException(nameof(enumValue), "GetDisplayName EnumHelper, enumValue is null.");
}
return enumValue.GetType().GetMember(enumValue.ToString())
.First()
.GetCustomAttribute<DisplayAttribute>()
.Name;
}
}
}

View File

@@ -0,0 +1,142 @@
using Aperio_Control_Centre.ACSDatabase;
using Aperio_Control_Centre.ACSDatabase.Models;
using Aperio_Control_Centre.ACSDatabase.Types;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
namespace Aperio_Control_Centre.Helpers
{
public static class SelectListHelpers
{
public static Task<List<SelectListItem>> DepartmentsSelectListItems(ACSDatabaseContext db)
{
return db.Departments
.Where(a => a.Active != ActiveStates.Deleted)
.Select(s => new SelectListItem
{
Value = s.Id.ToString(),
Text = s.Name,
}).ToListAsync();
}
public static async Task<SelectList> DepartmentsSelectList(ACSDatabaseContext db)
{
return new SelectList(await DepartmentsSelectListItems(db), "Value", "Text");
}
public static Task<List<SelectListItem>> GroupsSelectListItems(ACSDatabaseContext db)
{
return db.Groups
.Where(a => a.Active != ActiveStates.Deleted)
.Select(s => new SelectListItem
{
Value = s.Id.ToString(),
Text = s.Name,
}).ToListAsync();
}
public static async Task<SelectList> GroupsSelectList(ACSDatabaseContext db)
{
return new SelectList(await GroupsSelectListItems(db), "Value", "Text");
}
public static List<GroupListItem> GroupsListItems(ACSDatabaseContext db)
{
return db.Groups
.Where(a => a.Active != ActiveStates.Deleted)
.Include(t => t.Timezone)
.AsEnumerable()
.Select(group => new GroupListItem
{
Text = group.Name,
Value = group.Id.ToString(),
TimeZoneActive = group.Timezone != null && group.Timezone.IsTimezoneActive2
}).ToList();
}
public static List<GroupListItem> GroupsListItems(Device device, ACSDatabaseContext db)
{
return db.Groups
.Where(a => a.Active != ActiveStates.Deleted)
.Include(t => t.Timezone)
.AsEnumerable()
.Select(group => new GroupListItem
{
Selected = group.DeviceGroupJoins.Where(d => d.DeviceId == device.Id).Where(g => g.GroupId == group.Id).Any(),
Text = group.Name,
Value = group.Id.ToString(),
TimeZoneActive = group.Timezone != null && group.Timezone.IsTimezoneActive2
}).ToList();
}
public static Task<List<SelectListItem>> TimezoneSelectListItems(ACSDatabaseContext db)
{
return db.Timezones
.Where(a => a.Active != ActiveStates.Deleted)
.Select(s => new SelectListItem
{
Value = s.Id.ToString(),
Text = s.Name,
}).ToListAsync();
}
public static async Task<SelectList> TimeZoneSelectList(ACSDatabaseContext db)
{
return new SelectList(await TimezoneSelectListItems(db), "Value", "Text");
}
public static List<SelectListItem> LocationSelectItems(ACSDatabaseContext db)
{
return db.Locations
.Where(a => a.Active != ActiveStates.Deleted)
.AsEnumerable()
.Select(s => new SelectListItem
{
Value = s.Id.ToString(),
Text = s.AddressString,
}).ToList();
}
public static SelectList LocationSelectList(ACSDatabaseContext db)
{
return new SelectList(LocationSelectItems(db), "Value", "Text");
}
public static List<SelectListItem> DeviceSelectListItems(ACSDatabaseContext db)
{
return db.Devices
.Where(a => a.Active != ActiveStates.Deleted)
.Include(l => l.Location)
.AsEnumerable()
.Select(s => new SelectListItem
{
Value = s.Id.ToString(),
Text = s.LocationId.HasValue ? s.Location.AddressString + " - " + s.Name : s.Name,
}).ToList();
}
public static List<SelectListItem> LockDeviceSelectListItems(ACSDatabaseContext db)
{
return db.Devices
.Where(a => a.Active != ActiveStates.Deleted)
.Where(p => p.ProductClass == ProductClass.H1502R11 || p.ProductClass == ProductClass.Lock)
.Include(l => l.Location)
.AsEnumerable()
.Select(s => new SelectListItem
{
Value = s.Id.ToString(),
Text = s.LocationId.HasValue ? $"{s.Location.AddressString} - {s.Name} ({s.Active},{s.ProductClass})" : s.Name,
}).ToList();
}
public static List<SelectListItem> LockDeviceSelectListItems(int groupId, ACSDatabaseContext db)
{
return db.Devices
.Where(a => a.Active != ActiveStates.Deleted)
.Where(p => p.ProductClass == ProductClass.H1502R11 || p.ProductClass == ProductClass.Lock)
.Include(l => l.Location)
.AsEnumerable()
.Select(dev => new SelectListItem
{
Value = dev.Id.ToString(),
Text = dev.LocationId.HasValue ? $"{dev.Location.AddressString} - {dev.Name} ({dev.Active},{dev.ProductClass})" : dev.Name,
Selected = dev.DeviceGroupJoins.Where(d => d.DeviceId == dev.Id).Where(g => g.GroupId == groupId).Any(),
}).ToList();
}
}
}

View File

@@ -0,0 +1,138 @@
using Aperio_Control_Centre.ACSDatabase.Models;
using Aperio_Control_Centre.ACSDatabase.Types;
namespace Aperio_Control_Centre.Helpers
{
public static class Sorting
{
public static IQueryable<Device> SortDeviceList(string sortOrder, IQueryable<Device> devicelist)
{
if (sortOrder != null)
{
devicelist = sortOrder switch
{
"devid_asc" => devicelist.OrderBy(s => s.DeviceId),
"devid_desc" => devicelist.OrderByDescending(s => s.DeviceId),
"name_asc" => devicelist.OrderBy(s => s.Name),
"name_desc" => devicelist.OrderByDescending(s => s.Name),
"loc_asc" => devicelist.Where(l => l.LocationId != null).OrderBy(s => s.Location.ShortAddressString).Concat(devicelist.Where(l => l.LocationId == null)),
"loc_desc" => devicelist.Where(l => l.LocationId != null).OrderByDescending(s => s.Location.ShortAddressString).Concat(devicelist.Where(l => l.LocationId == null)),
"hubid_asc" => devicelist.OrderBy(s => s.HubId),
"hubid_desc" => devicelist.OrderByDescending(s => s.HubId),
"ipaddress_asc" => devicelist.OrderBy(s => s.Ipaddress),
"ipaddress_desc" => devicelist.OrderByDescending(s => s.Ipaddress),
"batt_asc" => devicelist.OrderBy(s => s.BatteryState),
"batt_desc" => devicelist.OrderByDescending(s => s.BatteryState),
"conn_asc" => devicelist.OrderBy(s => s.ConnectionState),
"conn_desc" => devicelist.OrderByDescending(s => s.ConnectionState),
"status_asc" => devicelist.OrderBy(s => s.DoorState),
"status_desc" => devicelist.OrderByDescending(s => s.DoorState),
_ => devicelist.OrderBy(s => s.Id),
};
}
return devicelist;
}
public static List<Device> SortDeviceList(string sortOrder, List<Device> devicelist)
{
if (sortOrder != null)
{
devicelist = sortOrder switch
{
"devid_asc" => devicelist.OrderBy(s => s.DeviceId).ToList(),
"devid_desc" => devicelist.OrderByDescending(s => s.DeviceId).ToList(),
"name_asc" => devicelist.OrderBy(s => s.Name).ToList(),
"name_desc" => devicelist.OrderByDescending(s => s.Name).ToList(),
"loc_asc" => devicelist.Where(l => l.LocationId != null).OrderBy(s => s.Location.ShortAddressString).Concat(devicelist.Where(l => l.LocationId == null)).ToList(),
"loc_desc" => devicelist.Where(l => l.LocationId != null).OrderByDescending(s => s.Location.ShortAddressString).Concat(devicelist.Where(l => l.LocationId == null)).ToList(),
"hubid_asc" => devicelist.OrderBy(s => s.HubId).ToList(),
"hubid_desc" => devicelist.OrderByDescending(s => s.HubId).ToList(),
"ipaddress_asc" => devicelist.OrderBy(s => s.Ipaddress).ToList(),
"ipaddress_desc" => devicelist.OrderByDescending(s => s.Ipaddress).ToList(),
"batt_asc" => devicelist.OrderBy(s => s.BatteryState).ToList(),
"batt_desc" => devicelist.OrderByDescending(s => s.BatteryState).ToList(),
"conn_asc" => devicelist.OrderBy(s => s.ConnectionState).ToList(),
"conn_desc" => devicelist.OrderByDescending(s => s.ConnectionState).ToList(),
"status_asc" => devicelist.OrderBy(s => s.DoorState).ToList(),
"status_desc" => devicelist.OrderByDescending(s => s.DoorState).ToList(),
_ => devicelist.OrderBy(s => s.Id).ToList(),
};
}
return devicelist;
}
public static IQueryable<User> SortUserList(string sortOrder, IQueryable<User> userlist)
{
if (sortOrder != null)
{
userlist = sortOrder switch
{
"uid_asc" => userlist.OrderBy(s => s.CredentialString),
"uid_desc" => userlist.OrderByDescending(s => s.CredentialString),
"pass_asc" => userlist.OrderBy(s => s.PassNumber),
"pass_desc" => userlist.OrderByDescending(s => s.PassNumber),
"name_asc" => userlist.OrderBy(s => s.Name),
"name_desc" => userlist.OrderByDescending(s => s.Name),
"group_asc" => userlist.Where(s => s.GroupId != null).OrderBy(s => s.Group.Name).Concat(userlist.Where(g => g.GroupId == null)),
"group_desc" => userlist.Where(s => s.GroupId != null).OrderByDescending(s => s.Group.Name).Concat(userlist.Where(g => g.Group == null)),
"department_asc" => userlist.Where(s => s.DepartmentId != null).OrderBy(s => s.Department.Name).Concat(userlist.Where(g => g.DepartmentId == null)),
"department_desc" => userlist.Where(s => s.DepartmentId != null).OrderByDescending(s => s.Department.Name).Concat(userlist.Where(g => g.DepartmentId == null)),
"credtype_asc" => userlist.OrderBy(s => s.CredentialType),
"credtype_desc" => userlist.OrderByDescending(s => s.CredentialType),
"changed_asc" => userlist.OrderBy(s => s.LastChanged),
"changed_desc" => userlist.OrderByDescending(s => s.LastChanged),
"created_asc" => userlist.OrderBy(s => s.Created),
"created_desc" => userlist.OrderByDescending(s => s.Created),
"subline_asc" => userlist.OrderBy(s => s.SubLine),
"subline_desc" => userlist.OrderByDescending(s => s.SubLine),
"dordrecht_asc" => userlist.OrderBy(s => s.Dordrecht),
"dordrecht_desc" => userlist.OrderByDescending(s => s.Dordrecht),
_ => userlist.OrderBy(s => s.Id),
};
}
return userlist;
}
public static IQueryable<Department> SortDepartmentList(string sortOrder, IQueryable<Department> departmentlist)
{
if (sortOrder != null)
{
departmentlist = sortOrder switch
{
"name_asc" => departmentlist.OrderBy(s => s.Name),
"name_desc" => departmentlist.OrderByDescending(s => s.Name),
"info_asc" => departmentlist.OrderBy(s => s.Info),
"info_desc" => departmentlist.OrderByDescending(s => s.Info),
_ => departmentlist.OrderBy(s => s.Id),
};
}
return departmentlist;
}
public static IQueryable<Location> SortLocationsList(string sortOrder, IQueryable<Location> locationlist)
{
if (sortOrder != null)
{
locationlist = sortOrder switch
{
"street_asc" => locationlist.OrderBy(s => s.Street),
"street_desc" => locationlist.OrderByDescending(s => s.Street),
"nr_asc" => locationlist.OrderBy(s => s.Nr),
"nr_desc" => locationlist.OrderByDescending(s => s.Nr),
"city_asc" => locationlist.OrderBy(s => s.City),
"city_desc" => locationlist.OrderByDescending(s => s.City),
"zipcode_asc" => locationlist.OrderBy(s => s.Zipcode),
"zipcode_desc" => locationlist.OrderByDescending(s => s.Zipcode),
"prov_asc" => locationlist.OrderBy(s => s.Province),
"prov_desc" => locationlist.OrderByDescending(s => s.Province),
"country_asc" => locationlist.OrderBy(s => s.Country),
"country_desc" => locationlist.OrderByDescending(s => s.Country),
"devcount_asc" => locationlist.OrderBy(s => s.Devices.Where(l => l.Active != ActiveStates.Deleted).Count()),
"devcount_desc" => locationlist.OrderByDescending(s => s.Devices.Where(l => l.Active != ActiveStates.Deleted).Count()),
_ => locationlist.OrderBy(s => s.Id),
};
}
return locationlist;
}
}
}

View File

@@ -0,0 +1,25 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using Aperio_Control_Centre.ACSDatabase.Models;
namespace Aperio_Control_Centre.Models
{
public class PagedLoggingsModel
{
public int PageSize { get; set; }
public int Page { get; set; }
[DisplayName("Start log")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
public DateTime StartLogdate { get; set; }
[DisplayName("Einde log")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
public DateTime EndLogdate { get; set; }
public PagedList.IPagedList<Logging> Loggings { get; set; }
}
}

View File

@@ -0,0 +1,13 @@
using Aperio_Control_Centre.ACSDatabase.Models;
namespace Aperio_Control_Centre.Models
{
public class SelectedLog
{
public Device SelectedDevice { get; set; }
public User SelectedUser { get; set; }
public PagedLoggingsModel PagedLoggings { get; set; } = new();
}
}

View File

@@ -0,0 +1,121 @@
using System.Collections;
namespace Aperio_Control_Centre.PagedList;
/// <summary>
/// Represents a subset of a collection of objects that can be individually accessed by index and containing
/// metadata about the superset collection of objects this subset was created from.
/// </summary>
/// <remarks>
/// Represents a subset of a collection of objects that can be individually accessed by index and containing
/// metadata about the superset collection of objects this subset was created from.
/// </remarks>
/// <typeparam name = "T">The type of object the collection should contain.</typeparam>
/// <seealso cref = "IPagedList{T}" />
/// <seealso cref = "List{T}" />
public abstract class BasePagedList<T> : PagedListMetaData, IPagedList<T>
{
protected readonly List<T> Subset = new();
public const int DefaultPageSize = 100;
/// <summary>
/// Parameterless constructor.
/// </summary>
protected internal BasePagedList()
{
}
/// <summary>
/// Initializes a new instance of a type deriving from <see cref = "BasePagedList{T}" /> and sets properties
/// needed to calculate position and size data on the subset and superset.
/// </summary>
/// <param name = "pageNumber">The one-based index of the subset of objects contained by this instance.</param>
/// <param name = "pageSize">The maximum size of any individual subset.</param>
/// <param name = "totalItemCount">The size of the superset.</param>
protected internal BasePagedList(int pageNumber, int pageSize, int totalItemCount)
{
if (pageNumber < 1)
{
throw new ArgumentOutOfRangeException($"pageNumber = {pageNumber}. PageNumber cannot be below 1.");
}
if (pageSize < 1)
{
throw new ArgumentOutOfRangeException($"pageSize = {pageSize}. PageSize cannot be less than 1.");
}
if (totalItemCount < 0)
{
throw new ArgumentOutOfRangeException($"totalItemCount = {totalItemCount}. TotalItemCount cannot be less than 0.");
}
// set source to blank list if superset is null to prevent exceptions
TotalItemCount = totalItemCount;
PageSize = pageSize;
PageNumber = pageNumber;
PageCount = TotalItemCount > 0 ? (int)Math.Ceiling(TotalItemCount / (double)PageSize) : 0;
var pageNumberIsGood = PageCount > 0 && PageNumber <= PageCount;
HasPreviousPage = pageNumberIsGood && PageNumber > 1;
HasNextPage = pageNumberIsGood && PageNumber < PageCount;
IsFirstPage = pageNumberIsGood && PageNumber == 1;
IsLastPage = pageNumberIsGood && PageNumber == PageCount;
var numberOfFirstItemOnPage = (PageNumber - 1) * PageSize + 1;
FirstItemOnPage = pageNumberIsGood ? numberOfFirstItemOnPage : 0;
var numberOfLastItemOnPage = numberOfFirstItemOnPage + PageSize - 1;
LastItemOnPage = pageNumberIsGood
? numberOfLastItemOnPage > TotalItemCount
? TotalItemCount
: numberOfLastItemOnPage
: 0;
}
#region IPagedList<T> Members
/// <summary>
/// Returns an enumerator that iterates through the BasePagedList&lt;T&gt;.
/// </summary>
/// <returns>A BasePagedList&lt;T&gt;.Enumerator for the BasePagedList&lt;T&gt;.</returns>
public IEnumerator<T> GetEnumerator()
{
return Subset.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the BasePagedList&lt;T&gt;.
/// </summary>
/// <returns>A BasePagedList&lt;T&gt;.Enumerator for the BasePagedList&lt;T&gt;.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
///<summary>
/// Gets the element at the specified index.
///</summary>
///<param name = "index">The zero-based index of the element to get.</param>
public T this[int index] => Subset[index];
/// <summary>
/// Gets the number of elements contained on this page.
/// </summary>
public virtual int Count => Subset.Count;
///<summary>
/// Gets a non-enumerable copy of this paged list.
///</summary>
///<returns>A non-enumerable copy of this paged list.</returns>
public PagedListMetaData GetMetaData()
{
return new PagedListMetaData(this);
}
#endregion
}

View File

@@ -0,0 +1,123 @@
namespace Aperio_Control_Centre.PagedList;
/// <summary>
/// Represents a subset of a collection of objects that can be individually accessed by index and containing
/// metadata about the superset collection of objects this subset was created from.
/// </summary>
/// <remarks>
/// Represents a subset of a collection of objects that can be individually accessed by index and containing
/// metadata about the superset collection of objects this subset was created from.
/// </remarks>
/// <typeparam name="T">The type of object the collection should contain.</typeparam>
/// <seealso cref="IEnumerable{T}"/>
public interface IPagedList<out T> : IPagedList, IReadOnlyList<T>
{
///<summary>
/// Gets a non-enumerable copy of this paged list.
///</summary>
///<returns>A non-enumerable copy of this paged list.</returns>
PagedListMetaData GetMetaData();
}
/// <summary>
/// Represents a subset of a collection of objects that can be individually accessed by index and containing
/// metadata about the superset collection of objects this subset was created from.
/// </summary>
/// <remarks>
/// Represents a subset of a collection of objects that can be individually accessed by index and containing
/// metadata about the superset collection of objects this subset was created from.
/// </remarks>
public interface IPagedList
{
/// <summary>
/// Total number of subsets within the superset.
/// </summary>
/// <value>
/// Total number of subsets within the superset.
/// </value>
int PageCount { get; }
/// <summary>
/// Total number of objects contained within the superset.
/// </summary>
/// <value>
/// Total number of objects contained within the superset.
/// </value>
int TotalItemCount { get; }
/// <summary>
/// One-based index of this subset within the superset, zero if the superset is empty.
/// </summary>
/// <value>
/// One-based index of this subset within the superset, zero if the superset is empty.
/// </value>
int PageNumber { get; }
/// <summary>
/// Maximum size any individual subset.
/// </summary>
/// <value>
/// Maximum size any individual subset.
/// </value>
int PageSize { get; }
/// <summary>
/// Returns true if the superset is not empty and PageNumber is less than or equal to PageCount and this
/// is NOT the first subset within the superset.
/// </summary>
/// <value>
/// Returns true if the superset is not empty and PageNumber is less than or equal to PageCount and this
/// is NOT the first subset within the superset.
/// </value>
bool HasPreviousPage { get; }
/// <summary>
/// Returns true if the superset is not empty and PageNumber is less than or equal to PageCount and this
/// is NOT the last subset within the superset.
/// </summary>
/// <value>
/// Returns true if the superset is not empty and PageNumber is less than or equal to PageCount and this
/// is NOT the last subset within the superset.
/// </value>
bool HasNextPage { get; }
/// <summary>
/// Returns true if the superset is not empty and PageNumber is less than or equal to PageCount and this
/// is the first subset within the superset.
/// </summary>
/// <value>
/// Returns true if the superset is not empty and PageNumber is less than or equal to PageCount and this
/// is the first subset within the superset.
/// </value>
bool IsFirstPage { get; }
/// <summary>
/// Returns true if the superset is not empty and PageNumber is less than or equal to PageCount and this
/// is the last subset within the superset.
/// </summary>
/// <value>
/// Returns true if the superset is not empty and PageNumber is less than or equal to PageCount and this
/// is the last subset within the superset.
/// </value>
bool IsLastPage { get; }
/// <summary>
/// One-based index of the first item in the paged subset, zero if the superset is empty or PageNumber
/// is greater than PageCount.
/// </summary>
/// <value>
/// One-based index of the first item in the paged subset, zero if the superset is empty or PageNumber
/// is greater than PageCount.
/// </value>
int FirstItemOnPage { get; }
/// <summary>
/// One-based index of the last item in the paged subset, zero if the superset is empty or PageNumber
/// is greater than PageCount.
/// </summary>
/// <value>
/// One-based index of the last item in the paged subset, zero if the superset is empty or PageNumber
/// is greater than PageCount.
/// </value>
int LastItemOnPage { get; }
}

View File

@@ -0,0 +1,174 @@
using Aperio_Control_Centre.ACSDatabase;
using Microsoft.AspNetCore.Html;
using Microsoft.EntityFrameworkCore;
using System.Collections.Immutable;
using System.Text;
namespace Aperio_Control_Centre.PagedList.MVC
{
public static class PageListHelper
{
private static readonly int DefaultPageSize = 25;
public static int GetPageSize(int? pageSize, HttpRequest request)
{
if (pageSize == null)
{
pageSize = DefaultPageSize;
var ps = request.Cookies["PageSize"];
if (ps != null)
{
if (int.TryParse(ps, out int s))
{
pageSize = s;
}
}
}
return pageSize.Value;
}
public static int GetPage(int? page)
{
if (page == null || page <= 0)
{
return 1;
}
return page.Value;
}
public static async Task<DateTime> GetStartDate(DateTime? startLogdate, ACSDatabaseContext db)
{
if (startLogdate != null)
{
return startLogdate.Value;
}
else
{
return (await db.Loggings.FirstAsync()).Time;
}
}
public static DateTime GetEndDate(DateTime? endLogdate)
{
if (endLogdate != null)
{
return endLogdate.Value;
}
else
{
return DateTime.Now.AddDays(1);
}
}
public static HtmlString PagedListPager(IPagedList pagedList, Func<int, string> generatePageUrl, PagedListRenderOptions options)
{
var list = pagedList ?? new StaticPagedList<int>(ImmutableList<int>.Empty, 1, 10, 0);
//Debug.WriteLine($"IsLastPage = {list.IsLastPage}");
//Debug.WriteLine($"IsFirstPage = {list.IsFirstPage}");
//Debug.WriteLine($"HasNextPage = {list.HasNextPage}");
//Debug.WriteLine($"HasPreviousPage = {list.HasPreviousPage}");
//Debug.WriteLine($"PageNumber = {list.PageNumber}");
//Debug.WriteLine($"PageCount = {list.PageCount}");
//Debug.WriteLine($"TotalItemCount = {list.TotalItemCount}");
//Debug.WriteLine($"FirstItemOnPage = {list.FirstItemOnPage}");
//Debug.WriteLine($"LastItemOnPage = {list.LastItemOnPage}");
//calculate start and end of range of page numbers
var firstPageToDisplay = 1;
var lastPageToDisplay = list.PageCount;
// cannot fit all pages into pager
var maxPageNumbersToDisplay = options.MaximumPageNumbersToDisplay.Value;
firstPageToDisplay = list.PageNumber - maxPageNumbersToDisplay / 2;
if (firstPageToDisplay < 1)
{
firstPageToDisplay = 1;
}
int pageNumbersToDisplay = maxPageNumbersToDisplay;
lastPageToDisplay = firstPageToDisplay + pageNumbersToDisplay - 1;
if (lastPageToDisplay > list.PageCount)
{
firstPageToDisplay = list.PageCount - maxPageNumbersToDisplay + 1;
}
//Debug.WriteLine($"firstPageToDisplay = {firstPageToDisplay}");
//Debug.WriteLine($"lastPageToDisplay = {lastPageToDisplay}");
//Debug.WriteLine($"pageNumbersToDisplay = {pageNumbersToDisplay}");
StringBuilder stringBuilder = new();
stringBuilder.Append("<ul class='pagination'>");
//first
if (list.IsFirstPage)
{
stringBuilder.Append($"<li class='page-item disabled'><a class='page-link'>{options.LinkToFirstPageFormat}</a></li>");
}
else
{
stringBuilder.Append($"<li class='page-item'><a class='page-link' href='{generatePageUrl(1)}'>{options.LinkToFirstPageFormat}</a></li>");
}
//previous
if (list.HasPreviousPage)
{
stringBuilder.Append($"<li class='page-item'><a class='page-link' href='{generatePageUrl(list.PageNumber - 1)}'>{options.LinkToPreviousPageFormat}</a></li>");
}
else
{
stringBuilder.Append($"<li class='page-item disabled'><a class='page-link'>{options.LinkToPreviousPageFormat}</a></li>");
}
//page
foreach (var i in Enumerable.Range(firstPageToDisplay, pageNumbersToDisplay))
{
//Debug.WriteLine($"pageNumber = {i}");
if (i > 0)
{
//show page number link
if (i == list.PageNumber)
{
stringBuilder.Append($"<li class='page-item active'><a class='page-link' href='{generatePageUrl(i)}'>{i}</a></li>");
}
else
{
stringBuilder.Append($"<li class='page-item'><a class='page-link' href='{generatePageUrl(i)}'>{i}</a></li>");
}
}
}
//next
if (list.HasNextPage)
{
stringBuilder.Append($"<li class='page-item'><a class='page-link' href='{generatePageUrl(list.PageNumber + 1)}'>{options.LinkToNextPageFormat}</a></li>");
}
else
{
stringBuilder.Append($"<li class='page-item disabled'><a class='page-link'>{options.LinkToNextPageFormat}</a></li>");
}
//last
if (list.IsLastPage)
{
stringBuilder.Append($"<li class='page-item disabled'><a class='page-link'>{options.LinkToLastPageFormat}</a></li>");
}
else
{
stringBuilder.Append($"<li class='page-item'><a class='page-link' href='{generatePageUrl(list.PageCount)}'>{options.LinkToLastPageFormat}</a></li>");
}
stringBuilder.Append("</ul>");
return new HtmlString(stringBuilder.ToString());
}
}
}

View File

@@ -0,0 +1,53 @@
namespace Aperio_Control_Centre.PagedList.MVC;
public sealed class PagedListRenderOptions
{
///<summary>
/// The default settings render all navigation links and no descriptive text
///</summary>
public PagedListRenderOptions()
{
MaximumPageNumbersToDisplay = 10;
LinkToFirstPageFormat = "<<";
LinkToPreviousPageFormat = "<";
LinkToNextPageFormat = ">";
LinkToLastPageFormat = ">>";
}
///<summary>
/// The maximum number of page numbers to display. Null displays all page numbers.
///</summary>
public int? MaximumPageNumbersToDisplay { get; set; }
///<summary>
/// The pre-formatted text to display inside the hyperlink to the first page. The one-based index of the page (always 1 in this case) is passed into the formatting function - use {0} to reference it.
///</summary>
///<example>
/// "&lt;&lt; First"
///</example>
public string LinkToFirstPageFormat { get; set; }
///<summary>
/// The pre-formatted text to display inside the hyperlink to the previous page. The one-based index of the page is passed into the formatting function - use {0} to reference it.
///</summary>
///<example>
/// "&lt; Previous"
///</example>
public string LinkToPreviousPageFormat { get; set; }
///<summary>
/// The pre-formatted text to display inside the hyperlink to the next page. The one-based index of the page is passed into the formatting function - use {0} to reference it.
///</summary>
///<example>
/// "Next &gt;"
///</example>
public string LinkToNextPageFormat { get; set; }
///<summary>
/// The pre-formatted text to display inside the hyperlink to the last page. The one-based index of the page is passed into the formatting function - use {0} to reference it.
///</summary>
///<example>
/// "Last &gt;&gt;"
///</example>
public string LinkToLastPageFormat { get; set; }
}

View File

@@ -0,0 +1,142 @@
using System.Linq.Expressions;
namespace Aperio_Control_Centre.PagedList;
public class PagedList<T, TKey> : BasePagedList<T>
{
/// <summary>
/// Initializes a new instance of the <see cref="PagedList{T}"/> class that divides the supplied superset into
/// subsets the size of the supplied pageSize. The instance then only contains the objects contained in the
/// subset specified by index.
/// </summary>
/// <param name="superset">
/// The collection of objects to be divided into subsets. If the collection
/// implements <see cref="IQueryable{T}"/>, it will be treated as such.
/// </param>
/// <param name="keySelector">Expression for Order</param>
/// <param name="pageNumber">
/// The one-based index of the subset of objects to be contained by this instance.
/// </param>
/// <param name="pageSize">The maximum size of any individual subset.</param>
/// <exception cref="ArgumentOutOfRangeException">The specified index cannot be less than zero.</exception>
/// <exception cref="ArgumentOutOfRangeException">The specified page size cannot be less than one.</exception>
public PagedList(IQueryable<T> superset, Expression<Func<T, TKey>> keySelector, int pageNumber, int pageSize)
: base(pageNumber, pageSize, superset?.Count() ?? 0)
{
// add items to internal list
if (TotalItemCount > 0)
{
InitSubset(superset, keySelector.Compile(), pageNumber, pageSize);
}
}
public PagedList(IQueryable<T> superset, Func<T, TKey> keySelectorMethod, int pageNumber, int pageSize)
: base(pageNumber, pageSize, superset?.Count() ?? 0)
{
if (TotalItemCount > 0)
{
InitSubset(superset, keySelectorMethod, pageNumber, pageSize);
}
}
private void InitSubset(IEnumerable<T> superset, Func<T, TKey> keySelectorMethod, int pageNumber, int pageSize)
{
// add items to internal list
var skip = (pageNumber - 1) * pageSize;
var items = superset.OrderBy(keySelectorMethod).Skip(skip).Take(pageSize).ToList();
Subset.AddRange(items);
}
}
/// <summary>
/// Represents a subset of a collection of objects that can be individually accessed by index and containing
/// metadata about the superset collection of objects this subset was created from.
/// </summary>
/// <remarks>
/// Represents a subset of a collection of objects that can be individually accessed by index and containing
/// metadata about the superset collection of objects this subset was created from.
/// </remarks>
/// <typeparam name="T">The type of object the collection should contain.</typeparam>
/// <seealso cref="IPagedList{T}"/>
/// <seealso cref="BasePagedList{T}"/>
/// <seealso cref="StaticPagedList{T}"/>
/// <seealso cref="List{T}"/>
public class PagedList<T> : BasePagedList<T>
{
/// <summary>
/// Initializes a new instance of the <see cref="PagedList{T}"/> class that divides the supplied superset
/// into subsets the size of the supplied pageSize. The instance then only contains the objects contained
/// in the subset specified by index.
/// </summary>
/// <param name="superset">
/// The collection of objects to be divided into subsets. If the collection
/// implements <see cref="IQueryable{T}"/>, it will be treated as such.
/// </param>
/// <param name="pageNumber">
/// The one-based index of the subset of objects to be contained by this instance.
/// </param>
/// <param name="pageSize">The maximum size of any individual subset.</param>
/// <exception cref="ArgumentOutOfRangeException">The specified index cannot be less than zero.</exception>
/// <exception cref="ArgumentOutOfRangeException">The specified page size cannot be less than one.</exception>
//[PublicAPI]
public PagedList(IQueryable<T> superset, int pageNumber, int pageSize)
: base(pageNumber, pageSize, superset?.Count() ?? 0)
{
if (TotalItemCount > 0 && superset != null)
{
var skip = (pageNumber - 1) * pageSize;
Subset.AddRange(superset.Skip(skip).Take(pageSize));
}
}
/// <summary>
/// Initializes a new instance of the <see cref="PagedList{T}"/> class that divides the supplied superset
/// into subsets the size of the supplied pageSize. The instance then only contains the objects contained in
/// the subset specified by index.
/// </summary>
/// <param name="superset">
/// The collection of objects to be divided into subsets. If the collection
/// implements <see cref="IQueryable{T}"/>, it will be treated as such.
/// </param>
/// <param name="pageNumber">The one-based index of the subset of objects to be contained by this instance.</param>
/// <param name="pageSize">The maximum size of any individual subset.</param>
/// <exception cref="ArgumentOutOfRangeException">The specified index cannot be less than zero.</exception>
/// <exception cref="ArgumentOutOfRangeException">The specified page size cannot be less than one.</exception>
public PagedList(IEnumerable<T> superset, int pageNumber, int pageSize)
: this(superset.AsQueryable<T>(), pageNumber, pageSize)
{
}
/// <summary>
/// For Clone PagedList
/// </summary>
/// <param name="pagedList">Source PagedList</param>
/// <param name="superset">Source collection</param>
public PagedList(IPagedList pagedList, IEnumerable<T> superset)
{
TotalItemCount = pagedList.TotalItemCount;
PageSize = pagedList.PageSize;
PageNumber = pagedList.PageNumber;
PageCount = pagedList.PageCount;
HasPreviousPage = pagedList.HasPreviousPage;
HasNextPage = pagedList.HasNextPage;
IsFirstPage = pagedList.IsFirstPage;
IsLastPage = pagedList.IsLastPage;
FirstItemOnPage = pagedList.FirstItemOnPage;
LastItemOnPage = pagedList.LastItemOnPage;
Subset.AddRange(superset);
}
/// <summary>
/// Method return empty paged list
/// </summary>
/// <param name="pageNumber"></param>
/// <param name="pageSize"></param>
/// <returns></returns>
//[PublicAPI]
public static PagedList<T> Empty(int pageNumber = 1, int pageSize = DefaultPageSize) => new(Array.Empty<T>(), pageNumber, pageSize);
}

View File

@@ -0,0 +1,378 @@
using System.Linq.Expressions;
namespace Aperio_Control_Centre.PagedList;
/// <summary>
/// Container for extension methods designed to simplify the creation of instances of <see cref="PagedList{T}"/>.
/// </summary>
public static class PagedListExtensions
{
/// <summary>
/// Splits a collection of objects into n pages with an (for example, if I have a list of 45 shoes and
/// say 'shoes.Split(5)' I will now have 4 pages of 10 shoes and 1 page of 5 shoes.
/// </summary>
/// <typeparam name="T">The type of object the collection should contain.</typeparam>
/// <param name="superset">The collection of objects to be divided into subsets.</param>
/// <param name="numberOfPages">The number of pages this collection should be split into.</param>
/// <returns>A subset of this collection of objects, split into n pages.</returns>
public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> superset, int numberOfPages)
{
int take = Convert.ToInt32(Math.Ceiling(superset.Count() / (double)numberOfPages));
var result = new List<IEnumerable<T>>();
for (int i = 0; i < numberOfPages; i++)
{
var chunk = superset.Skip(i * take).Take(take).ToList();
if (chunk.Any())
{
result.Add(chunk);
};
}
return result;
}
/// <summary>
/// Splits a collection of objects into an unknown number of pages with n items per page (for example,
/// if I have a list of 45 shoes and say 'shoes.Partition(10)' I will now have 4 pages of 10 shoes and
/// 1 page of 5 shoes.
/// </summary>
/// <typeparam name="T">The type of object the collection should contain.</typeparam>
/// <param name="superset">The collection of objects to be divided into subsets.</param>
/// <param name="pageSize">The maximum number of items each page may contain.</param>
/// <returns>A subset of this collection of objects, split into pages of maximum size n.</returns>
public static IEnumerable<IEnumerable<T>> Partition<T>(this IEnumerable<T> superset, int pageSize)
{
// Cache this to avoid evaluating it twice
var count = superset.Count();
if (count < pageSize)
{
yield return superset;
}
else
{
var numberOfPages = Math.Ceiling(count / (double)pageSize);
for (var i = 0; i < numberOfPages; i++)
{
yield return superset.Skip(pageSize * i).Take(pageSize);
}
}
}
/// <summary>
/// Creates a subset of this collection of objects that can be individually accessed by index and containing
/// metadata about the collection of objects the subset was created from.
/// </summary>
/// <typeparam name="T">The type of object the collection should contain.</typeparam>
/// <param name="superset">
/// The collection of objects to be divided into subsets. If the collection
/// implements <see cref="IQueryable{T}"/>, it will be treated as such.
/// </param>
/// <param name="pageNumber">
/// The one-based index of the subset of objects to be contained by this instance.
/// </param>
/// <param name="pageSize">The maximum size of any individual subset.</param>
/// <returns>A subset of this collection of objects that can be individually accessed by index and containing
/// metadata about the collection of objects the subset was created from.</returns>
/// <seealso cref="PagedList{T}"/>
public static IPagedList<T> ToPagedList<T>(this IEnumerable<T> superset, int pageNumber, int pageSize)
{
return new PagedList<T>(superset ?? new List<T>(), pageNumber, pageSize);
}
/// <summary>
/// Creates a subset of this collection of objects that can be individually accessed by index and containing
/// metadata about the collection of objects the subset was created from.
/// </summary>
/// <typeparam name="T">The type of object the collection should contain.</typeparam>
/// <param name="superset">
/// The collection of objects to be divided into subsets. If the collection
/// implements <see cref="IQueryable{T}"/>, it will be treated as such.
/// </param>
/// <param name="pageNumber">
/// The one-based index of the subset of objects to be contained by this instance.
/// </param>
/// <param name="pageSize">The maximum size of any individual subset.</param>
/// <param name="totalSetCount">The total size of set</param>
/// <returns>A subset of this collection of objects that can be individually accessed by index and containing
/// metadata about the collection of objects the subset was created from.</returns>
/// <seealso cref="PagedList{T}"/>
public static IPagedList<T> ToPagedList<T>(this IQueryable<T> superset, int pageNumber, int pageSize, int? totalSetCount)
{
if (pageNumber < 1)
{
throw new ArgumentOutOfRangeException($"pageNumber = {pageNumber}. PageNumber cannot be below 1.");
}
if (pageSize < 1)
{
throw new ArgumentOutOfRangeException($"pageSize = {pageSize}. PageSize cannot be less than 1.");
}
if (superset == null)
{
return StaticPagedList<T>.Empty(pageNumber, pageSize);
}
var supersetCount = superset.Count();
if (supersetCount > totalSetCount)
{
throw new ArgumentOutOfRangeException($"superset count = {supersetCount} superset count cannot be more than {totalSetCount.Value}.");
}
List<T> subset;
var totalCount = totalSetCount ?? supersetCount;
if ((totalCount <= 0 || totalSetCount.HasValue) && supersetCount <= pageSize)
{
subset = superset.ToList();
}
else
{
var skip = (pageNumber - 1) * pageSize;
subset = superset.Skip(skip).Take(pageSize).ToList();
}
return new StaticPagedList<T>(subset, pageNumber, pageSize, totalCount);
}
/// <summary>
/// Creates a subset of this collection of objects that can be individually accessed by index and containing
/// metadata about the collection of objects the subset was created from.
/// </summary>
/// <typeparam name="T">The type of object the collection should contain.</typeparam>
/// <param name="superset">
/// The collection of objects to be divided into subsets. If the
/// collection implements <see cref="IQueryable{T}"/>, it will be treated as such.
/// </param>
/// <returns>A subset of this collection of objects that can be individually accessed by index and containing
/// metadata about the collection of objects the subset was created from.</returns>
/// <seealso cref="PagedList{T}"/>
public static IPagedList<T> ToPagedList<T>(this IEnumerable<T> superset)
{
var supersetSize = superset?.Count() ?? 0;
var pageSize = supersetSize == 0 ? 1 : supersetSize;
return new PagedList<T>(superset ?? new List<T>(), 1, pageSize);
}
/// <summary>
/// Cast to Custom Type
/// </summary>
/// <param name="source">Source</param>
/// <param name="selector">Selector</param>
/// <typeparam name="TSource">Input Type</typeparam>
/// <typeparam name="TResult">Result Type</typeparam>
/// <returns>New PagedList</returns>
public static IPagedList<TResult> Select<TSource, TResult>(this IPagedList<TSource> source, Func<TSource, TResult> selector)
{
var subset = ((IEnumerable<TSource>)source).Select(selector);
return new PagedList<TResult>(source, subset);
}
/// <summary>
/// Creates a subset of this collection of objects that can be individually accessed by index and containing
/// metadata about the collection of objects the subset was created from.
/// </summary>
/// <typeparam name="T">The type of object the collection should contain.</typeparam>
/// <typeparam name="TKey">Type For Compare</typeparam>
/// <param name="superset">
/// The collection of objects to be divided into subsets. If the collection
/// implements <see cref="IQueryable{T}"/>, it will be treated as such.
/// </param>
/// <param name="keySelector">Expression for Order</param>
/// <param name="pageNumber">
/// The one-based index of the subset of objects to be contained by this instance.
/// </param>
/// <param name="pageSize">The maximum size of any individual subset.</param>
/// <returns>
/// A subset of this collection of objects that can be individually accessed by index and containing
/// metadata about the collection of objects the subset was created from.
/// </returns>
public static IPagedList<T> ToPagedList<T, TKey>(this IQueryable<T> superset, Expression<Func<T, TKey>> keySelector, int pageNumber, int pageSize)
{
return new PagedList<T, TKey>(superset, keySelector, pageNumber, pageSize);
}
/// <summary>
/// Creates a subset of this collection of objects that can be individually accessed by index and containing
/// metadata about the collection of objects the subset was created from.
/// </summary>
/// <typeparam name="T">The type of object the collection should contain.</typeparam>
/// <typeparam name="TKey">Type For Compare</typeparam>
/// <param name="superset">
/// The collection of objects to be divided into subsets. If the collection
/// implements <see cref="IEnumerable{T}"/>, it will be treated as such.
/// </param>
/// <param name="keySelector">Expression for Order</param>
/// <param name="pageNumber">The one-based index of the subset of objects to be contained by this instance.</param>
/// <param name="pageSize">The maximum size of any individual subset.</param>
/// <returns>
/// A subset of this collection of objects that can be individually accessed by index and containing metadata
/// about the collection of objects the subset was created from.
/// </returns>
public static IPagedList<T> ToPagedList<T, TKey>(this IEnumerable<T> superset, Expression<Func<T, TKey>> keySelector, int pageNumber, int pageSize)
{
return new PagedList<T, TKey>(superset.AsQueryable(), keySelector, pageNumber, pageSize);
}
/// <summary>
/// Async creates a subset of this collection of objects that can be individually accessed by index and
/// containing metadata about the collection of objects the subset was created from.
/// </summary>
/// <typeparam name="T">The type of object the collection should contain.</typeparam>
/// <param name="superset">The collection of objects to be divided into subsets. If the collection implements <see cref="IQueryable{T}"/>, it will be treated as such.</param>
/// <param name="pageNumber">The one-based index of the subset of objects to be contained by this instance.</param>
/// <param name="pageSize">The maximum size of any individual subset.</param>
/// <param name="totalSetCount">The total size of set</param>
/// <param name="cancellationToken"></param>
/// <returns>
/// A subset of this collection of objects that can be individually accessed by index and containing metadata
/// about the collection of objects the subset was created from.
/// </returns>
/// <seealso cref="PagedList{T}"/>
public static Task<IPagedList<T>> ToPagedListAsync<T>(this IQueryable<T> superset, int pageNumber, int pageSize, int? totalSetCount, CancellationToken cancellationToken)
{
return Task.Factory.StartNew(() =>
{
return ToPagedList(superset, pageNumber, pageSize, totalSetCount);
}, cancellationToken);
}
/// <summary>
/// Async creates a subset of this collection of objects that can be individually accessed by index and
/// containing metadata about the collection of objects the subset was created from.
/// </summary>
/// <typeparam name="T">The type of object the collection should contain.</typeparam>
/// <param name="superset">
/// The collection of objects to be divided into subsets. If the collection
/// implements <see cref="IQueryable{T}"/>, it will be treated as such.
/// </param>
/// <param name="pageNumber">
/// The one-based index of the subset of objects to be contained by this instance.
/// </param>
/// <param name="pageSize">The maximum size of any individual subset.</param>
/// <param name="totalSetCount">The total size of set</param>
/// <returns>
/// A subset of this collection of objects that can be individually accessed by index and containing metadata
/// about the collection of objects the subset was created from.
/// </returns>
/// <seealso cref="PagedList{T}"/>
public static Task<IPagedList<T>> ToPagedListAsync<T>(this IQueryable<T> superset, int pageNumber, int pageSize, int? totalSetCount = null)
{
return AsQueryable(superset).ToPagedListAsync(pageNumber, pageSize, totalSetCount, CancellationToken.None);
}
/// <summary>
/// Creates a subset of this collection of objects that can be individually accessed by index and containing
/// metadata about the collection of objects the subset was created from.
/// </summary>
/// <typeparam name="T">The type of object the collection should contain.</typeparam>
/// <param name="superset">
/// The collection of objects to be divided into subsets. If the collection
/// implements <see cref="IEnumerable{T}"/>, it will be treated as such.
/// </param>
/// <param name="pageNumber">
/// The one-based index of the subset of objects to be contained by this instance.
/// </param>
/// <param name="pageSize">The maximum size of any individual subset.</param>
/// <param name="cancellationToken"></param>
/// <param name="totalSetCount">The total size of set</param>
/// <returns>
/// A subset of this collection of objects that can be individually accessed by index and containing metadata
/// about the collection of objects the subset was created from.
/// </returns>
/// <seealso cref="PagedList{T}"/>
public static Task<IPagedList<T>> ToPagedListAsync<T>(this IEnumerable<T> superset, int pageNumber, int pageSize, CancellationToken cancellationToken, int? totalSetCount = null)
{
return AsQueryable(superset).ToPagedListAsync(pageNumber, pageSize, totalSetCount, cancellationToken);
}
/// <summary>
/// Creates a subset of this collection of objects that can be individually accessed by index and containing
/// metadata about the collection of objects the subset was created from.
/// </summary>
/// <typeparam name="T">The type of object the collection should contain.</typeparam>
/// <param name="superset">
/// The collection of objects to be divided into subsets. If the collection
/// implements <see cref="IEnumerable{T}"/>, it will be treated as such.
/// </param>
/// <param name="pageNumber">
/// The one-based index of the subset of objects to be contained by this instance.
/// </param>
/// <param name="pageSize">The maximum size of any individual subset.</param>
/// <param name="totalSetCount">The total size of set</param>
/// <returns>
/// A subset of this collection of objects that can be individually accessed by index and containing metadata
/// about the collection of objects the subset was created from.
/// </returns>
/// <seealso cref="PagedList{T}"/>
public static Task<IPagedList<T>> ToPagedListAsync<T>(this IEnumerable<T> superset, int pageNumber, int pageSize, int? totalSetCount = null)
{
return AsQueryable(superset).ToPagedListAsync(pageNumber, pageSize, totalSetCount, CancellationToken.None);
}
/// <summary>
/// Async creates a subset of this collection of objects that can be individually accessed by index (defaulting
/// to the first page) and containing metadata about the collection of objects the subset was created from.
/// </summary>
/// <typeparam name="T">The type of object the collection should contain.</typeparam>
/// <param name="superset"></param>
/// <param name="pageNumber">
/// The one-based index of the subset of objects to be contained by this instance, defaulting to the first page.
/// </param>
/// <param name="pageSize">The maximum size of any individual subset.</param>
/// <param name="cancellationToken"></param>
/// <param name="totalSetCount">The total size of set</param>
/// <returns>
/// A subset of this collection of objects that can be individually accessed by index and containing
/// metadata about the collection of objects the subset was created from.
/// </returns>
/// <seealso cref="PagedList{T}"/>
public static Task<IPagedList<T>> ToPagedListAsync<T>(this IQueryable<T> superset, int? pageNumber, int pageSize, CancellationToken cancellationToken, int? totalSetCount = null)
{
return AsQueryable(superset).ToPagedListAsync(pageNumber ?? 1, pageSize, totalSetCount, cancellationToken);
}
/// <summary>
/// Async creates a subset of this collection of objects that can be individually accessed by index
/// (defaulting to the first page) and containing metadata about the collection of objects the subset
/// was created from.
/// </summary>
/// <typeparam name="T">The type of object the collection should contain.</typeparam>
/// <param name="superset"></param>
/// <param name="pageNumber">
/// The one-based index of the subset of objects to be contained by this instance,
/// defaulting to the first page.
/// </param>
/// <param name="pageSize">The maximum size of any individual subset.</param>
/// <param name="totalSetCount">The total size of set</param>
/// <returns>
/// A subset of this collection of objects that can be individually accessed by index and containing metadata
/// about the collection of objects the subset was created from.
/// </returns>
/// <seealso cref="PagedList{T}"/>
public static Task<IPagedList<T>> ToPagedListAsync<T>(this IQueryable<T> superset, int? pageNumber, int pageSize, int? totalSetCount = null)
{
return AsQueryable(superset).ToPagedListAsync(pageNumber ?? 1, pageSize, totalSetCount, CancellationToken.None);
}
private static IQueryable<T> AsQueryable<T>(IQueryable<T> superset)
{
return superset ?? new EnumerableQuery<T>(new List<T>());
}
private static IQueryable<T> AsQueryable<T>(IEnumerable<T> superset)
{
return superset == null ? new EnumerableQuery<T>(new List<T>()) : superset.AsQueryable();
}
}

View File

@@ -0,0 +1,126 @@
namespace Aperio_Control_Centre.PagedList;
///<summary>
/// Non-enumerable version of the PagedList class.
///</summary>
public class PagedListMetaData : IPagedList
{
/// <summary>
/// Protected constructor that allows for instantiation without passing in a separate list.
/// </summary>
protected PagedListMetaData()
{
}
///<summary>
/// Non-enumerable version of the PagedList class.
///</summary>
///<param name="pagedList">A PagedList (likely enumerable) to copy metadata from.</param>
public PagedListMetaData(IPagedList pagedList)
{
PageCount = pagedList.PageCount;
TotalItemCount = pagedList.TotalItemCount;
PageNumber = pagedList.PageNumber;
PageSize = pagedList.PageSize;
HasPreviousPage = pagedList.HasPreviousPage;
HasNextPage = pagedList.HasNextPage;
IsFirstPage = pagedList.IsFirstPage;
IsLastPage = pagedList.IsLastPage;
FirstItemOnPage = pagedList.FirstItemOnPage;
LastItemOnPage = pagedList.LastItemOnPage;
}
#region IPagedList Members
/// <summary>
/// Total number of subsets within the superset.
/// </summary>
/// <value>
/// Total number of subsets within the superset.
/// </value>
public int PageCount { get; protected set; }
/// <summary>
/// Total number of objects contained within the superset.
/// </summary>
/// <value>
/// Total number of objects contained within the superset.
/// </value>
public int TotalItemCount { get; protected set; }
/// <summary>
/// One-based index of this subset within the superset, zero if the superset is empty.
/// </summary>
/// <value>
/// One-based index of this subset within the superset, zero if the superset is empty.
/// </value>
public int PageNumber { get; protected set; }
/// <summary>
/// Maximum size any individual subset.
/// </summary>
/// <value>
/// Maximum size any individual subset.
/// </value>
public int PageSize { get; protected set; }
/// <summary>
/// Returns true if the superset is not empty and PageNumber is less than or equal to PageCount and this is NOT the first subset within the superset.
/// </summary>
/// <value>
/// Returns true if the superset is not empty and PageNumber is less than or equal to PageCount and this is NOT the first subset within the superset.
/// </value>
public bool HasPreviousPage { get; protected set; }
/// <summary>
/// Returns true if the superset is not empty and PageNumber is less than or equal to PageCount and this
/// is NOT the last subset within the superset.
/// </summary>
/// <value>
/// Returns true if the superset is not empty and PageNumber is less than or equal to PageCount and this
/// is NOT the last subset within the superset.
/// </value>
public bool HasNextPage { get; protected set; }
/// <summary>
/// Returns true if the superset is not empty and PageNumber is less than or equal to PageCount and this
/// is the first subset within the superset.
/// </summary>
/// <value>
/// Returns true if the superset is not empty and PageNumber is less than or equal to PageCount and
/// this is the first subset within the superset.
/// </value>
public bool IsFirstPage { get; protected set; }
/// <summary>
/// Returns true if the superset is not empty and PageNumber is less than or equal to PageCount and
/// this is the last subset within the superset.
/// </summary>
/// <value>
/// Returns true if the superset is not empty and PageNumber is less than or equal to PageCount and this
/// is the last subset within the superset.
/// </value>
public bool IsLastPage { get; protected set; }
/// <summary>
/// One-based index of the first item in the paged subset, zero if the superset is empty or PageNumber
/// is greater than PageCount.
/// </summary>
/// <value>
/// One-based index of the first item in the paged subset, zero if the superset is empty or PageNumber
/// is greater than PageCount.
/// </value>
public int FirstItemOnPage { get; protected set; }
/// <summary>
/// One-based index of the last item in the paged subset, zero if the superset is empty or PageNumber
/// is greater than PageCount.
/// </summary>
/// <value>
/// One-based index of the last item in the paged subset, zero if the superset is empty or PageNumber
/// is greater than PageCount.
/// </value>
public int LastItemOnPage { get; protected set; }
#endregion
}

View File

@@ -0,0 +1,59 @@
namespace Aperio_Control_Centre.PagedList;
/// <summary>
/// Represents a subset of a collection of objects that can be individually accessed by index and containing
/// metadata about the superset collection of objects this subset was created from.
/// </summary>
/// <remarks>
/// Represents a subset of a collection of objects that can be individually accessed by index and containing
/// metadata about the superset collection of objects this subset was created from.
/// </remarks>
/// <typeparam name="T">The type of object the collection should contain.</typeparam>
/// <seealso cref="IPagedList{T}"/>
/// <seealso cref="BasePagedList{T}"/>
/// <seealso cref="PagedList{T}"/>
/// <seealso cref="List{T}"/>
public class StaticPagedList<T> : BasePagedList<T>
{
/// <summary>
/// Initializes a new instance of the <see cref="StaticPagedList{T}"/> class that contains the already
/// divided subset and information about the size of the superset and the subset's position within it.
/// </summary>
/// <param name="subset">The single subset this collection should represent.</param>
/// <param name="metaData">
/// Supply the ".MetaData" property of an existing IPagedList instance to recreate
/// it here (such as when creating a new instance of a PagedList after having used Automapper to convert
/// its contents to a DTO.)
/// </param>
/// <exception cref="ArgumentOutOfRangeException">The specified index cannot be less than zero.</exception>
/// <exception cref="ArgumentOutOfRangeException">The specified page size cannot be less than one.</exception>
public StaticPagedList(IEnumerable<T> subset, IPagedList metaData)
: this(subset, metaData.PageNumber, metaData.PageSize, metaData.TotalItemCount)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="StaticPagedList{T}"/> class that contains the already
/// divided subset and information about the size of the superset and the subset's position within it.
/// </summary>
/// <param name="subset">The single subset this collection should represent.</param>
/// <param name="pageNumber">The one-based index of the subset of objects contained by this instance.</param>
/// <param name="pageSize">The maximum size of any individual subset.</param>
/// <param name="totalItemCount">The size of the superset.</param>
/// <exception cref="ArgumentOutOfRangeException">The specified index cannot be less than zero.</exception>
/// <exception cref="ArgumentOutOfRangeException">The specified page size cannot be less than one.</exception>
public StaticPagedList(IEnumerable<T> subset, int pageNumber, int pageSize, int totalItemCount)
: base(pageNumber, pageSize, totalItemCount)
{
Subset.AddRange(subset);
}
/// <summary>
/// Method return empty static paged list
/// </summary>
/// <param name="pageNumber"></param>
/// <param name="pageSize"></param>
/// <returns></returns>
//[PublicAPI]
public static StaticPagedList<T> Empty(int pageNumber = 1, int pageSize = DefaultPageSize) => new(Array.Empty<T>(), pageNumber, pageSize, 0);
}