Compare commits

...

2 Commits

Author SHA1 Message Date
a9264e99a5 work on tests 2019-04-28 21:17:02 +02:00
7910e3687c Init 2019-04-28 09:55:22 +02:00
34 changed files with 1642 additions and 163 deletions

4
.gitignore vendored
View File

@ -245,4 +245,6 @@ ModelManifest.xml
.fake/
[Ll]ogs/
[Ll]ogs/*
[Ll]ogs/*
App_Data/ResourceImages/*

View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27130.2020
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ResourcesManager", "ResoursesManager\ResourcesManager.csproj", "{7DA03B24-3B56-4A2F-9540-C61E94DC0434}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ResourcesManagerTests", "ResourcesManagerTests\ResourcesManagerTests.csproj", "{F62CF157-2386-4A3B-A512-B6961DF63604}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7DA03B24-3B56-4A2F-9540-C61E94DC0434}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7DA03B24-3B56-4A2F-9540-C61E94DC0434}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7DA03B24-3B56-4A2F-9540-C61E94DC0434}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7DA03B24-3B56-4A2F-9540-C61E94DC0434}.Release|Any CPU.Build.0 = Release|Any CPU
{F62CF157-2386-4A3B-A512-B6961DF63604}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F62CF157-2386-4A3B-A512-B6961DF63604}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F62CF157-2386-4A3B-A512-B6961DF63604}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F62CF157-2386-4A3B-A512-B6961DF63604}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DFE12CC6-F894-4FD9-95F8-10A94508E234}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,111 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using ResourcesManager.Controllers;
using ResourcesManager.Interfaces;
using ResourcesManager.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace ResourcesManager.Controllers.Tests
{
[TestClass()]
public class NotificationsControllerTests
{
public List<Notification> expectedNotifications;
public Mock<INotificationRepository> mockNotifRepo;
NotificationsController notifController;
public NotificationsControllerTests()
{
InitializeTestData();
}
[TestInitialize]
public void InitializeTestData()
{
expectedNotifications = new List<Notification> {
new Notification() { Id=1, Title = "Cím", Description = "text text" },
new Notification() { Id=2, Title = "Cím", Description = "text text", Readed = false },
new Notification() { Id=3, Title = "Cím", Description = "text text" }
};
mockNotifRepo = new Mock<INotificationRepository>() { CallBase = true };
notifController = new NotificationsController(mockNotifRepo.Object);
mockNotifRepo.Setup(m => m.GetNotifications()).Returns(expectedNotifications);
mockNotifRepo.Setup(m => m.GetNotificationByID(It.IsAny<int>())).Returns((int id) =>
{
return expectedNotifications.FirstOrDefault(x => x.Id == id);
});
mockNotifRepo.Setup(m => m.InsertNotification(It.IsAny<Notification>())).Returns((Notification notif) =>
{
expectedNotifications.Add(notif);
return true;
});
mockNotifRepo.Setup(m => m.UpdateNotification(It.IsAny<Notification>())).Returns((Notification target) =>
{
var notif = expectedNotifications.FirstOrDefault(x => x.Id == target.Id);
if (notif == null)
{
return false;
}
notif.Title = target.Title;
notif.Description = target.Description;
notif.Readed = target.Readed;
notif.Logo = target.Logo;
notif.Link = target.Link;
notif.User = target.User;
notif.CreateDate = target.CreateDate;
return true;
});
mockNotifRepo.Setup(m => m.DeleteNotification(It.IsAny<int>())).Returns((int id) =>
{
var notif = expectedNotifications.FirstOrDefault(x => x.Id == id);
if (notif == null)
{
return false;
}
expectedNotifications.Remove(notif);
return true;
});
}
[TestMethod()]
public void Notification_Unread_Test()
{
var result = notifController.GetUnread();
Assert.IsNotNull((result as JsonResult).Data);
}
[TestMethod()]
public void Notification_Readed_Test()
{
notifController.Readed(1);
var result = expectedNotifications.FirstOrDefault(n => n.Id == 1);
Assert.AreEqual(result.Readed, true);
}
[TestMethod()]
public void Notification_MakeReadAll_Test()
{
notifController.MakeReadAll();
var result = expectedNotifications.All(n => n.Readed == true);
Assert.IsTrue(result);
}
[TestCleanup]
public void Notifications_CleanUpTestData()
{
expectedNotifications = null;
mockNotifRepo = null;
}
}
}

View File

@ -0,0 +1,235 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using ResourcesManager.Controllers;
using ResourcesManager.Interfaces;
using ResourcesManager.Models;
using ResourcesManagerTests.RepositoryTests;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace ResourcesManager.Controllers.Tests
{
[TestClass()]
public class ReservationsControllerTests
{
List<Reservation> expectedReservs;
public Mock<IReservationRepository> mockReservRepo;
ReservationsController reservController;
UserRepositoryTests userRepoTest;
ResourcesControllerTests resourceContTest;
StatisticsControllerTests statContTest;
public ReservationsControllerTests()
{
InitializeTestData();
}
[TestInitialize]
public void InitializeTestData()
{
expectedReservs = new List<Reservation> {
new Reservation() {
Id =1,
Begining = DateTime.Now.AddHours(-3),
End = DateTime.Now.AddHours(-2),
Resource = new Resource(){
Users = new List<ApplicationUser>(){
new ApplicationUser(),
new ApplicationUser()
}
}
},
new Reservation() {
Id =2,
Begining = DateTime.Now.AddHours(1),
End = DateTime.Now.AddHours(2),
Resource = new Resource(){
Users = new List<ApplicationUser>(){
new ApplicationUser(),
new ApplicationUser()
}
}
},
new Reservation() {
Id =3,
Begining = DateTime.Now.AddHours(3),
End = DateTime.Now.AddHours(4),
Resource = new Resource(){
Users = new List<ApplicationUser>(){
new ApplicationUser(),
new ApplicationUser()
}
}
}
};
mockReservRepo = new Mock<IReservationRepository>() { CallBase = true };
resourceContTest = new ResourcesControllerTests();
userRepoTest = new UserRepositoryTests();
statContTest = new StatisticsControllerTests();
reservController = new ReservationsController(mockReservRepo.Object,
userRepoTest.mockUserRepo.Object,
resourceContTest.mockResourceRepo.Object,
statContTest.mockStatRepo.Object);
mockReservRepo.Setup(m => m.GetReservations()).Returns(expectedReservs);
mockReservRepo.Setup(m => m.GetReservationByID(It.IsAny<int>())).Returns((int id) =>
{
return expectedReservs.FirstOrDefault(x => x.Id == id);
});
mockReservRepo.Setup(m => m.InsertReservation(It.IsAny<Reservation>())).Returns((Reservation reserv) =>
{
expectedReservs.Add(reserv);
return true;
});
mockReservRepo.Setup(m => m.UpdateReservation(It.IsAny<Reservation>())).Returns((Reservation target) =>
{
var reserv = expectedReservs.FirstOrDefault(x => x.Id == target.Id);
if (reserv == null)
{
return false;
}
reserv.Begining = target.Begining;
reserv.End = target.End;
reserv.Resource = target.Resource;
reserv.ResourceId = target.ResourceId;
reserv.User = target.User;
return true;
});
mockReservRepo.Setup(m => m.DeleteReservation(It.IsAny<int>())).Returns((int id) =>
{
var resource = expectedReservs.FirstOrDefault(x => x.Id == id);
if (resource == null)
{
return false;
}
expectedReservs.Remove(resource);
return true;
});
}
[TestMethod()]
public void Reservation_Get_Index_Test()
{
var result = reservController.Index();
Assert.IsNotNull((result as ViewResult).Model);
}
[TestMethod()]
public void Reservation_Get_Week_Test()
{
var result = reservController.Week(DateTime.Now);
Assert.IsNotNull((result as ViewResult).Model);
}
[TestMethod()]
public void Reservation_Get_Day_Test()
{
var result = reservController.Day(DateTime.Now);
Assert.IsNotNull((result as ViewResult).Model);
}
[TestMethod()]
public void Reservation_Get_Create_Test()
{
var result = reservController.Create(1);
Assert.IsNotNull((result as ViewResult).Model);
}
[TestMethod()]
public void Reservation_Post_Create_Ok_Test()
{
var beforeCount = ((reservController.Index() as ViewResult).Model as ReservationViewModel).Reservations?.Count();
Assert.AreEqual(3, beforeCount);
reservController.Create(new Reservation() { Id = 4, Begining = DateTime.Now.AddHours(2), End = DateTime.Now.AddHours(3), ResourceId = 1 });
var afterCount = ((reservController.Index() as ViewResult).Model as ReservationViewModel).Reservations?.Count();
Assert.AreEqual(4, afterCount);
}
[TestMethod()]
public void Reservation_Post_Create_Fail_Test()
{
var beforeCount = ((reservController.Index() as ViewResult).Model as ReservationViewModel).Reservations?.Count();
Assert.AreEqual(3, beforeCount);
reservController.Create(new Reservation() { Id = 4, Begining = DateTime.Now });
var afterCount = ((reservController.Index() as ViewResult).Model as ReservationViewModel).Reservations?.Count();
Assert.AreEqual(3, afterCount);
}
[TestMethod()]
public void Reservation_Get_Edit_Test()
{
var result = reservController.Edit(1);
Assert.IsNotNull((result as ViewResult).Model);
}
[TestMethod()]
public void Reservation_Post_Edit_Ok_Test()
{
var beforeBegin = DateTime.Now.AddDays(2);
reservController.Edit(new Reservation() { Id = 3, Begining = beforeBegin, End = DateTime.Now.AddDays(2).AddHours(4), ResourceId = 1 });
var afterBegin = ((reservController.Details(3) as ViewResult).Model as Reservation).Begining;
Assert.AreEqual(beforeBegin, afterBegin);
}
[TestMethod()]
public void Reservation_Post_Edit_Fail_Test()
{
var beforeBegin = DateTime.Now.AddDays(2);
reservController.Edit(new Reservation() { Id = 3, Begining = beforeBegin, ResourceId = 1 });
var afterBegin = ((reservController.Details(3) as ViewResult).Model as Reservation).Begining;
Assert.AreNotEqual(beforeBegin, afterBegin);
}
[TestMethod()]
public void Reservation_Get_Delete_Test()
{
var result = reservController.Delete(1);
Assert.IsNotNull((result as ViewResult).Model);
}
[TestMethod()]
public void Reservation_Post_Delete_Ok_Test()
{
var beforeCount = ((reservController.Index() as ViewResult).Model as ReservationViewModel).Reservations?.Count();
Assert.AreEqual(3, beforeCount);
reservController.DeleteConfirmed(1);
var afterCount = ((reservController.Index() as ViewResult).Model as ReservationViewModel).Reservations?.Count();
Assert.AreEqual(2, afterCount);
}
[TestMethod()]
public void Reservation_Post_Delete_Fail_Test()
{
var beforeCount = ((reservController.Index() as ViewResult).Model as ReservationViewModel).Reservations?.Count();
Assert.AreEqual(3, beforeCount);
reservController.DeleteConfirmed(8);
var afterCount = ((reservController.Index() as ViewResult).Model as ReservationViewModel).Reservations?.Count();
Assert.AreEqual(3, afterCount);
}
[TestCleanup]
public void Resources_CleanUpTestData()
{
expectedReservs = null;
mockReservRepo = null;
statContTest.Statistic_CleanUpTestData();
resourceContTest.Resources_CleanUpTestData();
userRepoTest.User_CleanUpTestData();
}
}
}

View File

@ -0,0 +1,205 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using ResourcesManager.Controllers;
using ResourcesManager.Interfaces;
using ResourcesManager.Models;
using ResourcesManagerTests.RepositoryTests;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace ResourcesManager.Controllers.Tests
{
[TestClass()]
public class ResourcesControllerTests
{
public List<Resource> expectedResources;
public Mock<IResourceRepository> mockResourceRepo;
ResourcesController resourcesController;
UserRepositoryTests userRepoTest;
public ResourcesControllerTests()
{
InitializeTestData();
}
[TestInitialize]
public void InitializeTestData()
{
expectedResources = new List<Resource> {
new Resource() { Id=1, Name = "Béla", AssetTag = "4jk5h23k", IsShared = false },
new Resource() { Id=2, Name = "Lajos", AssetTag = "6546", IsShared = true },
new Resource() { Id=3, Name = "Kati", AssetTag = "u547547", IsShared = false }
};
mockResourceRepo = new Mock<IResourceRepository>() { CallBase = true };
userRepoTest = new UserRepositoryTests();
resourcesController = new ResourcesController(mockResourceRepo.Object, userRepoTest.mockUserRepo.Object);
mockResourceRepo.Setup(m => m.GetResouces()).Returns(expectedResources);
mockResourceRepo.Setup(m => m.GetResourceByID(It.IsAny<int>())).Returns((int id) =>
{
return expectedResources.FirstOrDefault(x => x.Id == id);
});
mockResourceRepo.Setup(m => m.InsertResouce(It.IsAny<Resource>())).Returns((Resource resource) =>
{
expectedResources.Add(resource);
return true;
});
mockResourceRepo.Setup(m => m.UpdateResouce(It.IsAny<Resource>())).Returns((Resource target) =>
{
var resource = expectedResources.FirstOrDefault(x => x.Id == target.Id);
if (resource == null)
{
return false;
}
resource.Name = target.Name;
resource.Description = target.Description;
resource.AssetTag = target.AssetTag;
resource.ImagePath = target.ImagePath;
resource.IsShared = target.IsShared;
resource.TimeLimit = target.TimeLimit;
resource.Reservation = target.Reservation;
resource.Users = target.Users;
return true;
});
mockResourceRepo.Setup(m => m.DeleteResouce(It.IsAny<int>())).Returns((int id) =>
{
var resource = expectedResources.FirstOrDefault(x => x.Id == id);
if (resource == null)
{
return false;
}
expectedResources.Remove(resource);
return true;
});
}
[TestMethod()]
public void Resources_Get_Index_Test()
{
var result = resourcesController.Index();
Assert.IsNotNull((result as ViewResult).Model);
}
[TestMethod()]
public void Resources_Get_Details_Ok_Test()
{
var result = resourcesController.Details(1);
Assert.IsNotNull((result as ViewResult).Model);
}
[TestMethod()]
public void Resources_Get_Details_Fail_Test()
{
var result = resourcesController.Details(null) as HttpStatusCodeResult;
Assert.IsNotNull(result);
Assert.AreEqual(result.StatusCode, 400);
}
[TestMethod()]
public void Resources_Get_Create_Test()
{
var result = resourcesController.Create();
Assert.IsNotNull(result);
}
[TestMethod()]
public void Resources_Post_Create_Ok_Test()
{
var beforeCount = ((resourcesController.Index() as ViewResult).Model as IEnumerable<Resource>).Count();
Assert.AreEqual(3, beforeCount);
resourcesController.Create(new Resource() {Id=4, Name = "Sanyi", AssetTag = "hh564he56", IsShared = false });
var afterCount = ((resourcesController.Index() as ViewResult).Model as IEnumerable<Resource>).Count();
Assert.AreEqual(4, afterCount);
}
[TestMethod()]
public void Resources_Post_Create_Fail_Test()
{
var beforeCount = ((resourcesController.Index() as ViewResult).Model as IEnumerable<Resource>).Count();
Assert.AreEqual(3, beforeCount);
resourcesController.Create(new Resource() { Name = "Sanyi", IsShared = false });
var afterCount = ((resourcesController.Index() as ViewResult).Model as IEnumerable<Resource>).Count();
Assert.AreEqual(3, afterCount);
}
[TestMethod()]
public void Resources_Get_Edit_Test()
{
var result = resourcesController.Edit(1);
Assert.IsNotNull((result as ViewResult).Model);
}
[TestMethod()]
public void Resources_Post_Edit_Ok_Test()
{
string beforeName = "Katika";
resourcesController.Edit(new Resource() { Id = 3, Name = beforeName, AssetTag = "u547547", IsShared = false });
object afterName = ((resourcesController.Details(3) as ViewResult).Model as Resource).Name;
Assert.AreEqual(beforeName, afterName);
}
[TestMethod()]
public void Resources_Post_Edit_Fail_Test()
{
string beforeName = "Katika";
resourcesController.Edit(new Resource() { Id = 3, Name = beforeName, IsShared = false });
object afterName = ((resourcesController.Details(3) as ViewResult).Model as Resource).Name;
Assert.AreNotEqual(beforeName, afterName);
}
[TestMethod()]
public void Resources_Get_Delete_Test()
{
var result = resourcesController.Delete(1);
Assert.AreEqual((result as ViewResult).Model, expectedResources[0]);
}
[TestMethod()]
public void Resources_Post_Delete_Ok_Test()
{
var beforeCount = ((resourcesController.Index() as ViewResult).Model as IEnumerable<Resource>).Count();
Assert.AreEqual(3, beforeCount);
resourcesController.DeleteConfirmed(1);
var afterCount = ((resourcesController.Index() as ViewResult).Model as IEnumerable<Resource>).Count();
Assert.AreEqual(2, afterCount);
}
[TestMethod()]
public void Resources_Post_Delete_Fail_Test()
{
var beforeCount = ((resourcesController.Index() as ViewResult).Model as IEnumerable<Resource>).Count();
Assert.AreEqual(3, beforeCount);
resourcesController.DeleteConfirmed(8);
var afterCount = ((resourcesController.Index() as ViewResult).Model as IEnumerable<Resource>).Count();
Assert.AreEqual(3, afterCount);
}
[TestCleanup]
public void Resources_CleanUpTestData()
{
expectedResources = null;
mockResourceRepo = null;
userRepoTest.User_CleanUpTestData();
}
}
}

View File

@ -0,0 +1,73 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using ResourcesManager.Controllers;
using ResourcesManager.Interfaces;
using ResourcesManager.Models;
using ResourcesManagerTests.RepositoryTests;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace ResourcesManager.Controllers.Tests
{
[TestClass()]
public class StatisticsControllerTests
{
List<StatisticModel> expectedStat;
public Mock<IStatisticRepository> mockStatRepo;
StatisticsController statController;
ResourcesControllerTests resourcesContTest;
UserRepositoryTests userRepoTest;
public StatisticsControllerTests()
{
InitializeStatisticTestData();
}
[TestInitialize]
public void InitializeStatisticTestData()
{
expectedStat = new List<StatisticModel> {
new StatisticModel(){ Id= 1, ResourceId = 1, ReservationId = 1, StatisticType = StatisticType.Login, DateTime = DateTime.Now, UserId = Guid.NewGuid().ToString()},
new StatisticModel(){ Id= 2, ResourceId = 2, ReservationId = 2, StatisticType = StatisticType.Reserv, DateTime = DateTime.Now, UserId = Guid.NewGuid().ToString()},
new StatisticModel(){ Id= 3, ResourceId = 3, ReservationId = 3, StatisticType = StatisticType.ResourceCreate, DateTime = DateTime.Now, UserId = Guid.NewGuid().ToString()},
};
mockStatRepo = new Mock<IStatisticRepository>() { CallBase = true };
resourcesContTest = new ResourcesControllerTests();
userRepoTest = new UserRepositoryTests();
statController = new StatisticsController(mockStatRepo.Object, resourcesContTest.mockResourceRepo.Object, userRepoTest.mockUserRepo.Object);
mockStatRepo.Setup(m => m.GetStatistics()).Returns(expectedStat);
mockStatRepo.Setup(m => m.GetStatisticByID(It.IsAny<int>())).Returns((int id) =>
{
return expectedStat.FirstOrDefault(x => x.Id == id);
});
mockStatRepo.Setup(m => m.InsertStatistic(It.IsAny<StatisticModel>())).Returns((StatisticModel stat) =>
{
expectedStat.Add(stat);
return true;
});
}
[TestMethod()]
public void Statistic_Get_Index_Test()
{
var result = statController.Index(StatisticType.Login, 1);
Assert.IsNotNull((result as ViewResult).Model);
}
//todo: még
[TestCleanup]
public void Statistic_CleanUpTestData()
{
expectedStat = null;
resourcesContTest.Resources_CleanUpTestData();
userRepoTest.User_CleanUpTestData();
}
}
}

View File

@ -0,0 +1,77 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using ResourcesManager.Controllers;
using ResourcesManager.Interfaces;
using ResourcesManager.Models;
using ResourcesManagerTests.RepositoryTests;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace ResourcesManager.Controllers.Tests
{
[TestClass()]
public class SubscribeControllerTests
{
SubscribeController subController;
ResourcesControllerTests resoucesContTest;
UserRepositoryTests userRepoTest;
StatisticsControllerTests statContTest;
public SubscribeControllerTests()
{
InitializeTestData();
}
[TestInitialize]
public void InitializeTestData()
{
resoucesContTest = new ResourcesControllerTests();
userRepoTest = new UserRepositoryTests();
statContTest = new StatisticsControllerTests();
subController = new SubscribeController(resoucesContTest.mockResourceRepo.Object, userRepoTest.mockUserRepo.Object, statContTest.mockStatRepo.Object);
}
[TestMethod()]
public void Subscribe_Get_Index_Test()
{
var result = subController.Index();
Assert.IsNotNull((result as ViewResult).Model);
}
[TestMethod()]
public void Subscribe_Follow_Test()
{
subController.Follow(1);
var result = resoucesContTest.expectedResources.FirstOrDefault(r => r.Id == 1);
Assert.IsNotNull(result.Users);
}
[TestMethod()]
public void Subscribe_UnFollowAll_Test()
{
subController.UnFollowAll();
var result = resoucesContTest.expectedResources.All(x => x.Users == null || x.Users.Count == 0);
Assert.IsTrue(result);
}
[TestMethod()]
public void Subscribe_Unfollow_Test()
{
subController.Unfollow(1);
var result = resoucesContTest.expectedResources.FirstOrDefault(r => r.Id == 1);
var count = result.Users.Count;
Assert.AreEqual(count, 0);
}
[TestCleanup]
public void Resources_CleanUpTestData()
{
resoucesContTest.Resources_CleanUpTestData();
userRepoTest.User_CleanUpTestData();
statContTest = null;
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ResourcesManagerTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ResourcesManagerTests")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f62cf157-2386-4a3b-a512-b6961df63604")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,44 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using ResourcesManager.Interfaces;
using ResourcesManager.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ResourcesManagerTests.RepositoryTests
{
[TestClass]
class UserRepositoryTests
{
List<ApplicationUser> expectedUsers;
public Mock<IUserRepository> mockUserRepo;
public UserRepositoryTests()
{
InitializeTestData();
}
[TestInitialize]
public void InitializeTestData()
{
expectedUsers = new List<ApplicationUser> {
new ApplicationUser() { },
new ApplicationUser() { },
new ApplicationUser() { },
};
mockUserRepo = new Mock<IUserRepository>() { CallBase = true };
mockUserRepo.Setup(m => m.GetUsers()).Returns(expectedUsers);
}
[TestCleanup]
public void User_CleanUpTestData()
{
expectedUsers = null;
mockUserRepo = null;
}
}
}

View File

@ -0,0 +1,129 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.props" Condition="Exists('..\packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{F62CF157-2386-4A3B-A512-B6961DF63604}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ResourcesManagerTests</RootNamespace>
<AssemblyName>ResourcesManagerTests</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
<ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
<IsCodedUITest>False</IsCodedUITest>
<TestProjectType>UnitTest</TestProjectType>
<TargetFrameworkProfile />
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Castle.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL">
<HintPath>..\packages\Castle.Core.4.3.1\lib\net45\Castle.Core.dll</HintPath>
</Reference>
<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<Reference Include="Microsoft.VisualStudio.TestPlatform.TestFramework, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\MSTest.TestFramework.1.2.0\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll</HintPath>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\MSTest.TestFramework.1.2.0\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll</HintPath>
</Reference>
<Reference Include="Moq, Version=4.10.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL">
<HintPath>..\packages\Moq.4.10.1\lib\net45\Moq.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Runtime.CompilerServices.Unsafe, Version=4.0.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.4.5.0\lib\netstandard1.0\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
</Reference>
<Reference Include="System.Threading.Tasks.Extensions, Version=4.2.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Threading.Tasks.Extensions.4.5.1\lib\portable-net45+win8+wp8+wpa81\System.Threading.Tasks.Extensions.dll</HintPath>
</Reference>
<Reference Include="System.Web.Mvc">
<HintPath>..\packages\Microsoft.AspNet.Mvc.5.2.3\lib\net45\System.Web.Mvc.dll</HintPath>
</Reference>
</ItemGroup>
<Choose>
<When Condition="('$(VisualStudioVersion)' == '10.0' or '$(VisualStudioVersion)' == '') and '$(TargetFrameworkVersion)' == 'v3.5'">
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
</ItemGroup>
</When>
<Otherwise />
</Choose>
<ItemGroup>
<Compile Include="Controllers\NotificationsControllerTests.cs" />
<Compile Include="Controllers\ReservationsControllerTests.cs" />
<Compile Include="Controllers\ResourcesControllerTests.cs" />
<Compile Include="Controllers\StatisticsControllerTests.cs" />
<Compile Include="Controllers\SubscribeControllerTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RepositoryTests\UserRepositoryTests.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ResoursesManager\ResourcesManager.csproj">
<Project>{7DA03B24-3B56-4A2F-9540-C61E94DC0434}</Project>
<Name>ResourcesManager</Name>
</ProjectReference>
</ItemGroup>
<Choose>
<When Condition="'$(VisualStudioVersion)' == '10.0' And '$(IsCodedUITest)' == 'True'">
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.QualityTools.CodedUITestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestTools.UITest.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestTools.UITest.Extension, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestTools.UITesting, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
</ItemGroup>
</When>
</Choose>
<Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.props'))" />
<Error Condition="!Exists('..\packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.targets'))" />
</Target>
<Import Project="..\packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.targets" Condition="Exists('..\packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.targets')" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,35 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Castle.Core" version="4.3.1" targetFramework="net452" />
<package id="Moq" version="4.10.1" targetFramework="net452" />
<package id="MSTest.TestAdapter" version="1.2.0" targetFramework="net452" />
<package id="MSTest.TestFramework" version="1.2.0" targetFramework="net452" />
<package id="System.Runtime.CompilerServices.Unsafe" version="4.5.0" targetFramework="net452" />
<package id="System.Threading.Tasks.Extensions" version="4.5.1" targetFramework="net452" />
</packages>

View File

@ -1,22 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Express 14 for Web
VisualStudioVersion = 14.0.25123.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ResoursesManager", "ResoursesManager\ResoursesManager.csproj", "{7DA03B24-3B56-4A2F-9540-C61E94DC0434}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7DA03B24-3B56-4A2F-9540-C61E94DC0434}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7DA03B24-3B56-4A2F-9540-C61E94DC0434}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7DA03B24-3B56-4A2F-9540-C61E94DC0434}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7DA03B24-3B56-4A2F-9540-C61E94DC0434}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -9,14 +9,27 @@ using System.Web.Mvc;
using ResourcesManager.Models;
using System.Web.Helpers;
using System.IO;
using ResourcesManager.Interfaces;
using ResourcesManager.Repositories;
namespace ResourcesManager.Controllers
{
[Authorize]
public class NotificationsController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
private ApplicationDbContext context = new ApplicationDbContext();
private INotificationRepository notifRepo;
readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public NotificationsController()
{
context = new ApplicationDbContext();
notifRepo = new NotificationRepository(context);
}
public NotificationsController(INotificationRepository notifRepo)
{
this.notifRepo = notifRepo;
}
public ActionResult Readed(int? id, string link = null)
{
@ -27,55 +40,59 @@ namespace ResourcesManager.Controllers
logger.Warn("BadRequest");
}
db.Notifications.First(n => n.Id == id).Readed = true;
db.SaveChanges();
var notif = notifRepo.GetNotificationByID((int)id);
notif.Readed = true;
notifRepo.UpdateNotification(notif);
if (string.IsNullOrEmpty(link) || link == "null")
{
return Redirect(Request.UrlReferrer.ToString());
return Redirect(Request?.UrlReferrer?.ToString() ?? "/");
}
}
catch (Exception ex)
{
logger.Error("", ex);
}
return Redirect(link);
return Redirect(link ?? "/");
}
public ActionResult GetUnread()
{
using (ApplicationDbContext db = new ApplicationDbContext())
try
{
try
{
return Json(db.Notifications.OrderByDescending(k => k.CreateDate).Where(m => m.Readed == false && (m.User == User.Identity.Name || m.User == null)).ToList(), JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
logger.Warn("hiba", e);
return null;
}
return Json(notifRepo.GetNotifications().ToList().OrderByDescending(k => k.CreateDate).Where(m => m.Readed == false && (m.User == User?.Identity?.Name || m.User == null)).ToList(), JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
logger.Warn("hiba", e);
return null;
}
}
public ActionResult MakeReadAll()
{
try
{
db.Notifications.Where(k => k.Readed == false && (k.User == User.Identity.Name || k.User == null)).ToList().ForEach(k => k.Readed = true);
db.SaveChanges();
var list = notifRepo.GetNotifications().Where(k => k.Readed == false && (k.User == User?.Identity?.Name || k.User == null)).ToList();
foreach (var item in list)
{
item.Readed = true;
notifRepo.UpdateNotification(item);
}
}
catch (Exception ex)
{
logger.Error("", ex);
}
return Redirect(HttpContext.Request.UrlReferrer.ToString());
return Redirect(HttpContext?.Request?.UrlReferrer?.ToString() ?? "/");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
context.Dispose();
notifRepo.Dispose();
}
base.Dispose(disposing);
}

View File

@ -10,14 +10,36 @@ using ResourcesManager.Models;
using Microsoft.AspNet.Identity;
using System.IO;
using ResourcesManager.Helpers;
using ResourcesManager.Interfaces;
using ResourcesManager.Handlers;
using ResourcesManager.Repositories;
namespace ResourcesManager.Controllers
{
[Authorize]
public class ReservationsController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
private ApplicationDbContext context;
private IReservationRepository reservRepo;
private IUserRepository userRepo;
private IResourceRepository resourceRepo;
private IStatisticRepository statRepo;
readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public ReservationsController()
{
context = new ApplicationDbContext();
reservRepo = new ReservationRepository(context);
userRepo = new UserRepository(context);
resourceRepo = new ResourceRepository(context);
statRepo = new StatisticRepository(context);
}
public ReservationsController(IReservationRepository reservRepo, IUserRepository userRepo, IResourceRepository resourceRepo, IStatisticRepository statRepo)
{
this.reservRepo = reservRepo;
this.userRepo = userRepo;
this.resourceRepo = resourceRepo;
this.statRepo = statRepo;
}
public ActionResult Index(int? year = null, int? month = null, int? resourceId = null)
{
@ -45,8 +67,8 @@ namespace ResourcesManager.Controllers
model.Start = startOfMonth;
model.End = endOfMonth;
var reservations = db.Reservations
.Include(x => x.Resource)
var reservations = reservRepo.GetReservations()
.ToList()
.OrderBy(x => x.Begining)
.Where(x => x.Begining > startOfMonth && x.Begining < endOfMonth)
.ToList();
@ -69,8 +91,8 @@ namespace ResourcesManager.Controllers
var startDay = date.AddDays(startShift);
var endDay = date.AddDays(endShift);
var reservations = db.Reservations
.Include(x => x.Resource)
var reservations = reservRepo.GetReservations()
.ToList()
.OrderBy(x => x.Begining)
.Where(x => x.Begining > startDay && x.Begining < endDay)
.ToList();
@ -97,8 +119,8 @@ namespace ResourcesManager.Controllers
try
{
var end = day.AddDays(1);
var reservations = db.Reservations
.Include(x => x.Resource)
var reservations = reservRepo.GetReservations()
.ToList()
.OrderBy(x => x.Begining)
.Where(x => x.Begining > day && x.Begining < end)
.ToList();
@ -125,7 +147,7 @@ namespace ResourcesManager.Controllers
log.Warn("BadRequest");
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Reservation reservation = db.Reservations.Find(id);
Reservation reservation = reservRepo.GetReservationByID((int)id);
if (reservation == null)
{
log.Warn("HttpNotFound");
@ -147,13 +169,13 @@ namespace ResourcesManager.Controllers
model.Reservation.Begining = DateTime.Now.AddHours(1);
model.Reservation.End = DateTime.Now.AddHours(2);
model.Reservation.ResourceId = (int)resourceId;
model.Reservation.Resource = db.Resources.Find(resourceId);
model.Reservation.Resource = resourceRepo.GetResourceByID((int)resourceId);
}
else
{
model.Reservation.Begining = (DateTime)time;
model.Reservation.End = ((DateTime)time).AddHours(1);
model.Resources = db.Resources.ToList();
model.Resources = resourceRepo.GetResouces().ToList();
}
return View(model);
}
@ -170,8 +192,8 @@ namespace ResourcesManager.Controllers
{
try
{
model.Resource = db.Resources.Include(k => k.Users).FirstOrDefault(k => k.Id == model.ResourceId);
model.User = User.Identity.Name;
model.Resource = resourceRepo.GetResourceByID(model.ResourceId);
model.User = User?.Identity?.Name;
if (model.Resource.TimeLimit != null)
{
TimeSpan difference = model.End.Subtract(model.Begining);
@ -182,22 +204,22 @@ namespace ResourcesManager.Controllers
if (difference > timelimit)
{
ModelState.AddModelError("", "Túl lépted az idő limitet!");
return View(new ReservationCreateViewModel() { Reservation = model, Resources = db.Resources.ToList() });
return View(new ReservationCreateViewModel() { Reservation = model, Resources = resourceRepo.GetResouces().ToList().ToList() });
}
}
if (model.Begining > DateTime.Now.AddHours(-1) && model.Begining < DateTime.Now)
{
ModelState.AddModelError("", "Legalább egy órával a kezdés előtt le kell foglalnod!");
return View(new ReservationCreateViewModel() { Reservation = model, Resources = db.Resources.ToList() });
return View(new ReservationCreateViewModel() { Reservation = model, Resources = resourceRepo.GetResouces().ToList() });
}
if (model.Begining >= model.End)
{
ModelState.AddModelError("", "A kezdő időpont nem lehet hamarabb mint a befejező!");
return View(new ReservationCreateViewModel() { Reservation = model, Resources = db.Resources.ToList() });
return View(new ReservationCreateViewModel() { Reservation = model, Resources = resourceRepo.GetResouces().ToList() });
}
var data = db.Reservations.ToList();
var data = reservRepo.GetReservations().ToList();
foreach (var item in data)
{
if (item.ResourceId == model.ResourceId)
@ -205,13 +227,13 @@ namespace ResourcesManager.Controllers
if (item.Begining < model.End && item.End > model.Begining)
{
ModelState.AddModelError("", "Ez az időpont már foglalt");
return View(new ReservationCreateViewModel() { Reservation = model, Resources = db.Resources.ToList() });
return View(new ReservationCreateViewModel() { Reservation = model, Resources = resourceRepo.GetResouces().ToList() });
}
}
}
db.Reservations.Add(model);
db.Statistic.Add(new StatisticModel()
reservRepo.InsertReservation(model);
statRepo.InsertStatistic(new StatisticModel()
{
ReservationId = model.Id,
ResourceId = model.ResourceId,
@ -219,12 +241,11 @@ namespace ResourcesManager.Controllers
StatisticType = StatisticType.Reserv,
DateTime = DateTime.Now
});
db.SaveChanges();
log.Info("Új Foglalás: " + model.ToString());
//Értesítés küldés
var users = model.Resource.Users.Select(k => k.UserName).ToList();
string message = string.Format("{0} lefoglalta {1} erőforrást {2} tól {3}-ig.", User.Identity.Name, model.Resource.Name, model.Begining, model.End);
string message = string.Format("{0} lefoglalta {1} erőforrást {2} tól {3}-ig.", User?.Identity?.Name, model.Resource.Name, model.Begining, model.End);
string url = "/Reservations/Details/" + model.Id;
NotificationHelper.Send(users, "Foglalás", message, model.Resource.ImagePath, url);
return RedirectToAction("Details", "Reservations", new { Id = model.Id });
@ -245,15 +266,15 @@ namespace ResourcesManager.Controllers
log.Warn("BadRequest");
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Reservation reservation = db.Reservations.Find(id);
Reservation reservation = reservRepo.GetReservationByID((int)id);
if (reservation == null)
{
log.Warn("HttpNotFound");
return HttpNotFound();
}
if (!((reservation.User == User.Identity.Name) || User.IsInRole("Admin")))
if (!((reservation.User == User?.Identity?.Name) || User.IsInRole("Admin")))
{
log.Warn("Jogosultság hiba: " + User.Identity.Name);
log.Warn("Jogosultság hiba: " + User?.Identity?.Name);
return View("PermissionError");
}
return View(reservation);
@ -273,12 +294,12 @@ namespace ResourcesManager.Controllers
{
try
{
if (!((reservation.User == User.Identity.Name) || User.IsInRole("Admin")))
if (!((reservation.User == User?.Identity?.Name) || User.IsInRole("Admin")))
{
log.Warn("Jogosultsági hiba: " + User.Identity.Name);
log.Warn("Jogosultsági hiba: " + User?.Identity?.Name);
return View("PermissionError");
}
var resource = db.Resources.Include(k => k.Users).FirstOrDefault(k => k.Id == reservation.ResourceId);
var resource = resourceRepo.GetResourceByID(reservation.ResourceId);
if (resource.TimeLimit != null)
{
TimeSpan difference = reservation.End.Subtract(reservation.Begining);
@ -298,7 +319,7 @@ namespace ResourcesManager.Controllers
return View(reservation);
}
var data = db.Reservations.ToList();
var data = reservRepo.GetReservations();
foreach (var item in data)
{
if (item.ResourceId == reservation.ResourceId)
@ -315,11 +336,11 @@ namespace ResourcesManager.Controllers
}
var r = db.Reservations.First(f => f.Id == reservation.Id);
var r = reservRepo.GetReservationByID(reservation.Id);
r.Begining = reservation.Begining;
r.End = reservation.End;
db.Statistic.Add(new StatisticModel()
statRepo.InsertStatistic(new StatisticModel()
{
ReservationId = r.Id,
ResourceId = r.ResourceId,
@ -327,12 +348,11 @@ namespace ResourcesManager.Controllers
StatisticType = StatisticType.ReservartionModified,
DateTime = DateTime.Now
});
db.SaveChanges();
log.Info("Új foglalás: " + r.ToString());
//Értesítés küldés
var users = resource.Users.Select(k => k.UserName).ToList();
string message = string.Format("{0} módosította {1} erőforrás foglalását {2} tól {3}-ig.", User.Identity.Name, resource.Name, reservation.Begining, reservation.End);
string message = string.Format("{0} módosította {1} erőforrás foglalását {2} tól {3}-ig.", User?.Identity?.Name, resource.Name, reservation.Begining, reservation.End);
string url = "/Reservations/Details/" + reservation.Id;
NotificationHelper.Send(users, "Foglalás módosítás", message, resource.ImagePath, url);
return RedirectToAction("Details", "Reservations", new { Id = reservation.Id });
@ -355,10 +375,10 @@ namespace ResourcesManager.Controllers
log.Warn("BadRequest");
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Reservation reservation = db.Reservations.Find(id);
if (!((reservation.User == User.Identity.Name) || User.IsInRole("Admin")))
Reservation reservation = reservRepo.GetReservationByID((int)id);
if (!((reservation.User == User?.Identity?.Name) || User.IsInRole("Admin")))
{
log.Warn("Jogosultsági hiba: " + User.Identity.Name);
log.Warn("Jogosultsági hiba: " + User?.Identity?.Name);
return View("PermissionError");
}
if (reservation == null)
@ -381,19 +401,19 @@ namespace ResourcesManager.Controllers
{
try
{
var reservation = db.Reservations.Include("Resource.Users").First(i => i.Id == id);
if (!((reservation.User == User.Identity.Name) || User.IsInRole("Admin")))
var reservation = reservRepo.GetReservationByID(id);
if (!((reservation.User == User?.Identity?.Name) || User.IsInRole("Admin")))
{
log.Warn("Jogosultsági hiba: " + User.Identity.Name);
log.Warn("Jogosultsági hiba: " + User?.Identity?.Name);
return View("PermissionError");
}
//Értesítés küldés
var users = reservation.Resource.Users.Select(k => k.UserName).ToList();
string message = string.Format("{0} törölte {1} foglalását {2} tól {3}-ig.", User.Identity.Name, reservation.Resource.Name, reservation.Begining, reservation.End);
string message = string.Format("{0} törölte {1} foglalását {2} tól {3}-ig.", User?.Identity?.Name, reservation.Resource.Name, reservation.Begining, reservation.End);
NotificationHelper.Send(users, "Foglalás törlés", message, reservation.Resource.ImagePath, null);
db.Reservations.Remove(reservation);
db.Statistic.Add(new StatisticModel()
reservRepo.DeleteReservation(reservation.Id);
statRepo.InsertStatistic(new StatisticModel()
{
ReservationId = reservation.Id,
ResourceId = reservation.ResourceId,
@ -401,7 +421,6 @@ namespace ResourcesManager.Controllers
StatisticType = StatisticType.ReservationDelete,
DateTime = DateTime.Now
});
db.SaveChanges();
log.Info("Foglalás törölve id: " + id);
}
catch (Exception ex)
@ -417,7 +436,11 @@ namespace ResourcesManager.Controllers
{
if (disposing)
{
db.Dispose();
context.Dispose();
reservRepo.Dispose();
resourceRepo.Dispose();
statRepo.Dispose();
userRepo.Dispose();
}
base.Dispose(disposing);
}

View File

@ -16,15 +16,46 @@ using System.Web.Helpers;
using System.Net.Mime;
using Microsoft.AspNet.SignalR;
using ResourcesManager.Helpers;
using ResourcesManager.Interfaces;
using ResourcesManager.Handlers;
using ResourcesManager.Repositories;
namespace ResourcesManager.Controllers
{
[System.Web.Mvc.Authorize]
public class ResourcesController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
ApplicationDbContext context;
private IResourceRepository resourceRepo;
private IUserRepository userRepo;
private IStatisticRepository statisticRepo;
readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public ResourcesController()
{
context = new ApplicationDbContext();
resourceRepo = new ResourceRepository(context);
userRepo = new UserRepository(context);
statisticRepo = new StatisticRepository(context);
}
public ResourcesController(IResourceRepository resouceRepo)
{
this.resourceRepo = resouceRepo;
}
public ResourcesController(IResourceRepository resouceRepo, IUserRepository userRepo)
{
this.resourceRepo = resouceRepo;
this.userRepo = userRepo;
}
public ResourcesController(IResourceRepository resouceRepo, IUserRepository userRepo, IStatisticRepository statisticRepository)
{
this.resourceRepo = resouceRepo;
this.userRepo = userRepo;
this.statisticRepo = statisticRepository;
}
public ActionResult GetImage(string path)
{
try
@ -59,10 +90,10 @@ namespace ResourcesManager.Controllers
{
try
{
var stream = Request.Files[0].InputStream;
var stream = Request?.Files[0]?.InputStream;
string path;
if (stream.Length != 0)
if (stream != null && stream.Length != 0)
{
var img = new WebImage(stream);
string fileName = Path.GetRandomFileName();
@ -85,13 +116,13 @@ namespace ResourcesManager.Controllers
resource.ImagePath = "~/App_Data/ResourceImages/" + fileName;
stream.Flush();
stream.Close();
}
else
{
resource.ImagePath = "~/App_Data/ResourceImages/DefaultResource.png";
}
stream.Flush();
stream.Close();
return resource;
}
@ -104,7 +135,7 @@ namespace ResourcesManager.Controllers
public ActionResult Index()
{
return View(db.Resources.ToList());
return View(resourceRepo.GetResouces());
}
public ActionResult Details(int? id)
@ -114,7 +145,7 @@ namespace ResourcesManager.Controllers
log.Warn("BadRequest");
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Resource resource = db.Resources.Include("Users").FirstOrDefault(e => e.Id == id);
Resource resource = resourceRepo.GetResourceByID((int)id);
if (resource == null)
{
log.Warn("HttpNotFound");
@ -138,11 +169,16 @@ namespace ResourcesManager.Controllers
{
try
{
if (db.Resources.Any(m => m.AssetTag == resource.AssetTag))
if (resourceRepo.GetResouces().Any(m => m.AssetTag == resource.AssetTag))
{
ModelState.AddModelError("AssetTag", "Ilyen már létezik");
return View(resource);
}
if (string.IsNullOrEmpty(resource.AssetTag))
{
ModelState.AddModelError("AssetTag", "Kötelező mező");
return View(resource);
}
if (resource.TimeLimit < 1)
{
ModelState.AddModelError("TimeLimit", "Nem lehet negatív");
@ -151,16 +187,15 @@ namespace ResourcesManager.Controllers
try
{
resource.Users = db.Users.ToList();
db.Resources.Add(pictureUploadTo(resource));
db.Statistic.Add(new StatisticModel()
resource.Users = userRepo.GetUsers().ToList();
resourceRepo.InsertResouce(pictureUploadTo(resource));
statisticRepo.InsertStatistic(new StatisticModel()
{
ResourceId = resource.Id,
UserId = User.Identity.GetUserId(),
StatisticType = StatisticType.ResourceCreate,
DateTime = DateTime.Now
});
db.SaveChanges();
}
catch (Exception e)
{
@ -168,14 +203,14 @@ namespace ResourcesManager.Controllers
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
}
var allUser = db.Users.Select(k => k.UserName).ToList();
string message = string.Format("{0} létrehozta {1} erőforrást.", User.Identity.Name, resource.Name);
var allUser = userRepo.GetUsers().Select(k => k.UserName).ToList();
string message = string.Format("{0} létrehozta {1} erőforrást.", User?.Identity?.Name, resource.Name);
string url = "/Resources/Details/" + resource.Id;
NotificationHelper.Send(allUser, "Új erőforrás", message, resource.ImagePath, url);
}
catch (Exception ex)
{
log.Error("", ex);
log.Error("", ex);
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
}
@ -193,7 +228,7 @@ namespace ResourcesManager.Controllers
log.Warn("BadRequest");
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Resource resource = db.Resources.Find(id);
Resource resource = resourceRepo.GetResourceByID((int)id);
if (resource == null)
{
log.Warn("HttpNotFound");
@ -212,8 +247,8 @@ namespace ResourcesManager.Controllers
try
{
//Leltári azonosító ellenőrzés
var model = db.Resources.Include("Users").FirstOrDefault(m => m.Id == resource.Id);
var resources = db.Resources.ToList();
var model = resourceRepo.GetResourceByID(resource.Id);
var resources = resourceRepo.GetResouces().ToList();
foreach (var item in resources)
{
if (resource.AssetTag == item.AssetTag && (resource.AssetTag != model.AssetTag))
@ -221,12 +256,17 @@ namespace ResourcesManager.Controllers
ModelState.AddModelError("AssetTag", "Ilyen már létezik");
return View(model);
}
if (string.IsNullOrEmpty(resource.AssetTag))
{
ModelState.AddModelError("AssetTag", "Kötelező mező");
return View(resource);
}
}
//Kép feltöltés ellenörzése
var stream = Request.Files[0].InputStream;
string oldPath = db.Resources.Find(resource.Id).ImagePath;
var stream = Request?.Files[0]?.InputStream;
string oldPath = resourceRepo.GetResourceByID(resource.Id).ImagePath;
string path;
if (stream.Length != 0)
if (stream != null && stream.Length != 0)
{
//Kép mentése
var image = new WebImage(stream);
@ -246,28 +286,27 @@ namespace ResourcesManager.Controllers
pictureDelete(Server.MapPath(oldPath));
}
log.Info("PictureDeleted: " + oldPath);
stream.Flush();
stream.Close();
}
stream.Flush();
stream.Close();
//Adattagok módosítása
model.AssetTag = resource.AssetTag;
model.Description = resource.Description;
model.Name = resource.Name;
model.TimeLimit = resource.TimeLimit;
db.Entry(model).State = EntityState.Modified;
db.Statistic.Add(new StatisticModel()
resourceRepo.UpdateResouce(model);
statisticRepo.InsertStatistic(new StatisticModel()
{
ResourceId = resource.Id,
UserId = User.Identity.GetUserId(),
StatisticType = StatisticType.ResourceModified,
DateTime = DateTime.Now
});
db.SaveChanges();
//Értesítés küldés
var users = model.Users.Select(k => k.UserName).ToList();
string message = string.Format("{0} módosította {1} erőforrást.", User.Identity.Name, resource.Name);
string message = string.Format("{0} módosította {1} erőforrást.", User?.Identity?.Name, resource.Name);
string url = "/Resources/Details/" + resource.Id;
NotificationHelper.Send(users, "Erőforrás módosítás", message, resource.ImagePath, url);
@ -291,7 +330,7 @@ namespace ResourcesManager.Controllers
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Resource resource = db.Resources.Find(id);
Resource resource = resourceRepo.GetResourceByID((int)id);
if (resource == null)
{
log.Warn("HttpNotFound");
@ -308,22 +347,21 @@ namespace ResourcesManager.Controllers
{
try
{
Resource resource = db.Resources.Include("Users").FirstOrDefault(m => m.Id == id);
Resource resource = resourceRepo.GetResourceByID(id);
//Értesítés küldés
var users = resource.Users.Select(k => k.UserName).ToList();
string message = string.Format("{0} törölte {1} erőforrást.", User.Identity.Name, resource.Name);
string message = string.Format("{0} törölte {1} erőforrást.", User?.Identity?.Name, resource.Name);
NotificationHelper.Send(users, "Erőforrás törlés", message, null, null);
db.Resources.Remove(resource);
db.Statistic.Add(new StatisticModel()
resourceRepo.DeleteResouce(resource.Id); ;
statisticRepo.InsertStatistic(new StatisticModel()
{
ResourceId = resource.Id,
UserId = User.Identity.GetUserId(),
StatisticType = StatisticType.ResourceDelete,
DateTime = DateTime.Now
});
db.SaveChanges();
pictureDelete(resource.ImagePath);
}
catch (Exception ex)
@ -340,7 +378,10 @@ namespace ResourcesManager.Controllers
{
if (disposing)
{
db.Dispose();
context.Dispose();
resourceRepo.Dispose();
statisticRepo.Dispose();
userRepo.Dispose();
}
base.Dispose(disposing);
}

View File

@ -9,43 +9,77 @@ using System.Web.Mvc;
using ResourcesManager.Models;
using ResourcesManager.ViewModels;
using System.Data.Entity.Core.Objects;
using ResourcesManager.Interfaces;
using ResourcesManager.Repositories;
using ResourcesManager.Handlers;
namespace ResourcesManager.Controllers
{
public class StatisticsController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
private ApplicationDbContext context;
private IStatisticRepository statisticRepository;
private IResourceRepository resourceRepo;
private IUserRepository userRepo;
readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public StatisticsController()
{
context = new ApplicationDbContext();
statisticRepository = new StatisticRepository(context);
resourceRepo = new ResourceRepository(context);
userRepo = new UserRepository(context);
}
public StatisticsController(IStatisticRepository statisticRepository, IResourceRepository resourceRepo, IUserRepository userRepo)
{
this.statisticRepository = statisticRepository;
this.resourceRepo = resourceRepo;
this.userRepo = userRepo;
}
public ActionResult Index(StatisticType? statTypeId, int? resId)
{
if (statTypeId == null)
try
{
statTypeId = Models.StatisticType.Reserv;
if (statTypeId == null)
{
statTypeId = Models.StatisticType.Reserv;
}
if (resId == null)
{
resId = resourceRepo.GetResouces().FirstOrDefault().Id;
}
var statistics = statisticRepository.GetStatistics();
var model = new StatisticViewModel();
var today = DateTime.Today.AddDays(-30.0);
model.ByType = statistics.Where(k => k.StatisticType == statTypeId && k.DateTime > today)?.GroupBy(l => l.DateTime.Date)?.Select(j => new ByType() { Name = (DateTime)j.Key, Value = j.Count() })?.ToList();
model.ByResource = statistics.Where(k => k.ResourceId == resId & k.DateTime > today)?.GroupBy(l => l.DateTime.Date)?.Select(j => new ByResource() { Name = (DateTime)j.Key, Value = j.Count() })?.ToList();
model.ByTypeCircle = statistics.GroupBy(l => l.StatisticType).Select(j => new ByTypeCircle() { Name = ((StatisticType)j.Key).ToString(), Value = j.Count() }).ToList();
var subscibedUser = resourceRepo.GetResouces().Select(k => k.Users.Count()).Sum();
var allUsers = userRepo.GetUsers().Count() * resourceRepo.GetResouces().Count();
model.Subscribe = new List<Subscribe>();
model.Subscribe.Add(new Subscribe() { Name = "Subscribed user", Value = subscibedUser });
model.Subscribe.Add(new Subscribe() { Name = "Unsubscibed user", Value = allUsers - subscibedUser });
model.Resources = new SelectList(resourceRepo.GetResouces(), "Id", "Name", resId);
model.StatisticType = new SelectList(Enum.GetValues(typeof(StatisticType)).Cast<StatisticType>(), (int)statTypeId);
return View(model);
}
if (resId == null)
catch (Exception ex)
{
resId = db.Resources.FirstOrDefault().Id;
log.Error(ex);
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
}
var model = new StatisticViewModel();
var today = DateTime.Today.AddDays(-30.0);
model.ByType = db.Statistic.Where(k => k.StatisticType == statTypeId && k.DateTime > today).GroupBy(l => DbFunctions.TruncateTime(l.DateTime)).Select(j => new ByType() { Name = (DateTime)j.Key, Value = j.Count() }).ToList();
model.ByResource = db.Statistic.Where(k => k.ResourceId == resId & k.DateTime > today).GroupBy(l => DbFunctions.TruncateTime(l.DateTime)).Select(j => new ByResource() { Name = (DateTime)j.Key, Value = j.Count() }).ToList();
model.ByTypeCircle = db.Statistic.GroupBy(l => l.StatisticType).Select(j => new ByTypeCircle() { Name = ((StatisticType)j.Key).ToString(), Value = j.Count() }).ToList();
var subscibedUser = db.Resources.Select(k => k.Users.Count()).Sum();
var allUsers = db.Users.Count() * db.Resources.Count();
model.Subscribe = new List<Subscribe>();
model.Subscribe.Add(new Subscribe() { Name = "Subscribed user", Value = subscibedUser });
model.Subscribe.Add(new Subscribe() { Name = "Unsubscibed user", Value = allUsers - subscibedUser });
model.Resources = new SelectList(db.Resources, "Id", "Name", resId);
model.StatisticType = new SelectList(Enum.GetValues(typeof(StatisticType)).Cast<StatisticType>(), (int)statTypeId);
return View(model);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
context.Dispose();
statisticRepository.Dispose();
resourceRepo.Dispose();
userRepo.Dispose();
}
base.Dispose(disposing);
}

View File

@ -1,5 +1,8 @@
using Microsoft.AspNet.Identity;
using ResourcesManager.Handlers;
using ResourcesManager.Interfaces;
using ResourcesManager.Models;
using ResourcesManager.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
@ -12,12 +15,30 @@ namespace ResourcesManager.Controllers
[Authorize]
public class SubscribeController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
private ApplicationDbContext context;
private IResourceRepository resourceRepo;
private IUserRepository userRepo;
private IStatisticRepository statisticRepo;
readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public SubscribeController()
{
context = new ApplicationDbContext();
resourceRepo = new ResourceRepository(context);
userRepo = new UserRepository(context);
statisticRepo = new StatisticRepository(context);
}
public SubscribeController(IResourceRepository resouceRepo, IUserRepository userRepo, IStatisticRepository statisticRepository)
{
this.resourceRepo = resouceRepo;
this.userRepo = userRepo;
this.statisticRepo = statisticRepository;
}
public ActionResult Index()
{
return View(db.Resources.ToList());
return View(resourceRepo.GetResouces());
}
public ActionResult Follow(int? resourceId)
@ -30,16 +51,17 @@ namespace ResourcesManager.Controllers
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var user = db.Users.Find(User.Identity.GetUserId());
db.Resources.Find(resourceId).Users.Add(user);
db.Statistic.Add(new StatisticModel()
var user = userRepo.GetUserByID(User.Identity.GetUserId());
var res = resourceRepo.GetResourceByID((int)resourceId);
res.Users.Add(user);
resourceRepo.UpdateResouce(res);
statisticRepo.InsertStatistic(new StatisticModel()
{
ResourceId = (int)resourceId,
UserId = User.Identity.GetUserId(),
StatisticType = StatisticType.Subscribe,
DateTime = DateTime.Now
});
db.SaveChanges();
}
catch (Exception e)
{
@ -54,18 +76,17 @@ namespace ResourcesManager.Controllers
{
try
{
var user = db.Users.Find(User.Identity.GetUserId());
foreach (var item in db.Resources)
var user = userRepo.GetUserByID(User.Identity.GetUserId());
foreach (var item in resourceRepo.GetResouces())
{
item.Users.Remove(user);
}
db.Statistic.Add(new StatisticModel()
statisticRepo.InsertStatistic(new StatisticModel()
{
UserId = User.Identity.GetUserId(),
StatisticType = StatisticType.SubscribeAll,
DateTime = DateTime.Now
});
db.SaveChanges();
}
catch (Exception e)
{
@ -79,18 +100,17 @@ namespace ResourcesManager.Controllers
{
try
{
var user = db.Users.Find(User.Identity.GetUserId());
foreach (var item in db.Resources)
var user = userRepo.GetUserByID(User.Identity.GetUserId());
foreach (var item in resourceRepo.GetResouces())
{
item.Users.Add(user);
}
db.Statistic.Add(new StatisticModel()
statisticRepo.InsertStatistic(new StatisticModel()
{
UserId = User.Identity.GetUserId(),
StatisticType = StatisticType.UnsubscirbeAll,
DateTime = DateTime.Now
});
db.SaveChanges();
}
catch (Exception e)
{
@ -109,16 +129,17 @@ namespace ResourcesManager.Controllers
log.Warn("BadRequest");
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var user = db.Users.Find(User.Identity.GetUserId());
db.Resources.Find(resourceId).Users.Remove(user);
db.Statistic.Add(new StatisticModel()
var user = userRepo.GetUserByID(User.Identity.GetUserId());
var res = resourceRepo.GetResourceByID((int)resourceId);
res.Users.Remove(user);
resourceRepo.UpdateResouce(res);
statisticRepo.InsertStatistic(new StatisticModel()
{
ResourceId = (int)resourceId,
UserId = User.Identity.GetUserId(),
StatisticType = StatisticType.Unsubscirbe,
DateTime = DateTime.Now
});
db.SaveChanges();
}
catch (Exception e)
{
@ -132,7 +153,10 @@ namespace ResourcesManager.Controllers
{
if (disposing)
{
db.Dispose();
context.Dispose();
resourceRepo.Dispose();
statisticRepo.Dispose();
userRepo.Dispose();
}
base.Dispose(disposing);
}

View File

@ -0,0 +1,18 @@
using ResourcesManager.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ResourcesManager.Interfaces
{
public interface INotificationRepository : IDisposable
{
IEnumerable<Notification> GetNotifications();
Notification GetNotificationByID(int id);
bool InsertNotification(Notification notification);
bool DeleteNotification(int id);
bool UpdateNotification(Notification notification);
}
}

View File

@ -0,0 +1,18 @@
using ResourcesManager.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ResourcesManager.Interfaces
{
public interface IReservationRepository : IDisposable
{
IEnumerable<Reservation> GetReservations();
Reservation GetReservationByID(int id);
bool InsertReservation(Reservation reservation);
bool DeleteReservation(int id);
bool UpdateReservation(Reservation reservation);
}
}

View File

@ -0,0 +1,18 @@
using ResourcesManager.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ResourcesManager.Interfaces
{
public interface IResourceRepository : IDisposable
{
IEnumerable<Resource> GetResouces();
Resource GetResourceByID(int id);
bool InsertResouce(Resource resource);
bool DeleteResouce(int id);
bool UpdateResouce(Resource resource);
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ResourcesManager.Models;
namespace ResourcesManager.Interfaces
{
public interface IStatisticRepository : IDisposable
{
IEnumerable<StatisticModel> GetStatistics();
StatisticModel GetStatisticByID(int id);
bool InsertStatistic(StatisticModel statistic);
}
}

View File

@ -0,0 +1,19 @@
using ResourcesManager.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ResourcesManager.Interfaces
{
public interface IUserRepository : IDisposable
{
IEnumerable<ApplicationUser> GetUsers();
ApplicationUser GetUserByID(string id);
void InsertUser(ApplicationUser resource);
void DeleteUser(string id);
void UpdateUser(ApplicationUser resource);
void Save();
}
}

View File

@ -29,7 +29,7 @@ namespace ResourcesManager.Models
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDataContext
{
public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false)
{
@ -37,7 +37,7 @@ namespace ResourcesManager.Models
}
public DbSet<Reservation> Reservations { get; set; }
public DbSet<Resource> Resources { get; set; }
public IDbSet<Resource> Resources { get; set; }
public DbSet<Notification> Notifications { get; set; }
public DbSet<StatisticModel> Statistic { get; set; }
@ -157,4 +157,12 @@ namespace ResourcesManager.Models
base.Seed(context);
}
}
public interface IDataContext
{
DbSet<Reservation> Reservations { get; set; }
IDbSet<Resource> Resources { get; set; }
DbSet<Notification> Notifications { get; set; }
DbSet<StatisticModel> Statistic { get; set; }
}
}

View File

@ -0,0 +1,46 @@
using ResourcesManager.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ResourcesManager.Repositories
{
public class BaseRepository : IDisposable
{
protected ApplicationDbContext Context;
public BaseRepository(ApplicationDbContext context)
{
Context = context;
}
public virtual void Save()
{
Context.SaveChanges();
}
#region IDisposable Support
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
Context.Dispose();
}
}
disposed = true;
}
public void Dispose()
{
if (Context != null)
{
Context.Dispose();
}
}
#endregion
}
}

View File

@ -0,0 +1,47 @@
using ResourcesManager.Interfaces;
using ResourcesManager.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace ResourcesManager.Repositories
{
public class NotificationRepository : BaseRepository, INotificationRepository
{
public NotificationRepository(ApplicationDbContext context) : base(context) { }
public bool DeleteNotification(int id)
{
var notification = Context.Notifications.Find(id);
Context.Notifications.Remove(notification);
Save();
return true;
}
public Notification GetNotificationByID(int id)
{
return Context.Notifications.Find(id);
}
public IEnumerable<Notification> GetNotifications()
{
return Context.Notifications;
}
public bool InsertNotification(Notification notification)
{
Context.Notifications.Add(notification);
Save();
return true;
}
public bool UpdateNotification(Notification notification)
{
Context.Entry(notification).State = EntityState.Modified;
Save();
return true;
}
}
}

View File

@ -0,0 +1,48 @@
using ResourcesManager.Interfaces;
using ResourcesManager.Models;
using ResourcesManager.Repositories;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace ResourcesManager.Handlers
{
public class ResourceRepository : BaseRepository, IResourceRepository
{
public ResourceRepository(ApplicationDbContext context): base(context){}
public bool DeleteResouce(int id)
{
var resource = Context.Resources.Find(id);
Context.Resources.Remove(resource);
Save();
return true;
}
public Resource GetResourceByID(int id)
{
return Context.Resources.Find(id);
}
public IEnumerable<Resource> GetResouces()
{
return Context.Resources;
}
public bool InsertResouce(Resource resource)
{
Context.Resources.Add(resource);
Save();
return true;
}
public bool UpdateResouce(Resource resouce)
{
Context.Entry(resouce).State = EntityState.Modified;
Save();
return true;
}
}
}

View File

@ -0,0 +1,48 @@
using ResourcesManager.Interfaces;
using ResourcesManager.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ResourcesManager.Repositories
{
public class ReservationRepository : BaseRepository, IReservationRepository
{
public ReservationRepository(ApplicationDbContext context) : base(context) { }
public bool DeleteReservation(int id)
{
var reservation = Context.Reservations.Find(id);
Context.Reservations.Remove(reservation);
Save();
return true;
}
public Reservation GetReservationByID(int id)
{
return Context.Reservations.Find(id);
}
public IEnumerable<Reservation> GetReservations()
{
return Context.Reservations;
}
public bool InsertReservation(Reservation reservation)
{
Context.Reservations.Add(reservation);
Save();
return true;
}
public bool UpdateReservation(Reservation reservation)
{
Context.Entry(reservation).State = EntityState.Modified;
Save();
return true;
}
}
}

View File

@ -0,0 +1,31 @@
using ResourcesManager.Interfaces;
using ResourcesManager.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ResourcesManager.Repositories
{
public class StatisticRepository : BaseRepository, IStatisticRepository
{
public StatisticRepository(ApplicationDbContext context) : base(context) { }
public StatisticModel GetStatisticByID(int id)
{
return Context.Statistic.Find(id);
}
public IEnumerable<StatisticModel> GetStatistics()
{
return Context.Statistic;
}
public bool InsertStatistic(StatisticModel statistic)
{
Context.Statistic.Add(statistic);
Save();
return true;
}
}
}

View File

@ -0,0 +1,45 @@
using Microsoft.AspNet.Identity;
using ResourcesManager.Interfaces;
using ResourcesManager.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace ResourcesManager.Repositories
{
public class UserRepository : BaseRepository, IUserRepository
{
public UserRepository(ApplicationDbContext context) : base(context) { }
public void DeleteUser(string id)
{
var user = Context.Users.Find(id);
Context.Users.Remove(user);
Save();
}
public ApplicationUser GetUserByID(string id)
{
return Context.Users.Find(id);
}
public IEnumerable<ApplicationUser> GetUsers()
{
return Context.Users;
}
public void InsertUser(ApplicationUser user)
{
Context.Users.Add(user);
Save();
}
public void UpdateUser(ApplicationUser user)
{
Context.Entry(user).State = EntityState.Modified;
Save();
}
}
}

View File

@ -229,7 +229,18 @@
<Compile Include="Global.asax.cs">
<DependentUpon>Global.asax</DependentUpon>
</Compile>
<Compile Include="Interfaces\INotificationRepository.cs" />
<Compile Include="Interfaces\IReservationRepository.cs" />
<Compile Include="Interfaces\IStatisticRepository.cs" />
<Compile Include="Interfaces\IUserRepository.cs" />
<Compile Include="Repositories\BaseRepository.cs" />
<Compile Include="Repositories\NotificationRepository.cs" />
<Compile Include="Repositories\RescourceRepository.cs" />
<Compile Include="Helpers\NotificationHelper.cs" />
<Compile Include="Interfaces\IResourceRepository.cs" />
<Compile Include="Repositories\ReservationRepository.cs" />
<Compile Include="Repositories\StatisticRepository.cs" />
<Compile Include="Repositories\UserRepository.cs" />
<Compile Include="ViewModels\AccountViewModels.cs" />
<Compile Include="ViewModels\ReservationCreateViewModel.cs" />
<Compile Include="Models\IdentityModels.cs" />
@ -576,7 +587,9 @@
<Content Include="Scripts\jquery-3.1.1.min.map" />
<Content Include="Views\Statistics\Index.cshtml" />
</ItemGroup>
<ItemGroup />
<ItemGroup>
<Folder Include="Services\" />
</ItemGroup>
<ItemGroup>
<Content Include="packages.config" />
<None Include="Project_Readme.html" />

View File

@ -62,7 +62,7 @@
</div>
<p>
<a href="javascript:void(0);" onclick="history.go(-1);" class="btn btn-default">Vissza</a>
@if ((Model.User == User.Identity.Name) || User.IsInRole("Admin"))
@if ((Model.User == User?.Identity?.Name) || User.IsInRole("Admin"))
{
@Html.ActionLink("Módosítás", "Edit", new { id = Model.Id }, new { @class = "btn btn-warning" })
<span></span>

View File

@ -37,7 +37,7 @@
<td>
<div class="btn-group">
@Html.ActionLink("Részletek", "Details", "Reservations", new { id = item.Id }, new { @class = "btn btn-info" })
@if ((item.User == User.Identity.Name) || User.IsInRole("Admin"))
@if ((item.User == User?.Identity?.Name) || User.IsInRole("Admin"))
{
@Html.ActionLink("Módosítás", "Edit", "Reservations", new { id = item.Id }, new { @class = "btn btn-warning" })
@Html.ActionLink("Törlés", "Delete", "Reservations", new { id = item.Id }, new { @class = "btn btn-danger" })

View File

@ -43,7 +43,7 @@
{
<div class="btn-group">
@{
var user = User.Identity.Name;
var user = User?.Identity?.Name;
if (item.Users.Any(e => e.UserName == user))
{
@Html.ActionLink("Leíratkozás", "Unfollow", new { ResourceId = item.Id }, new { @class = "btn btn-default" })