work on tests

This commit is contained in:
bukovenszki.tamas 2019-04-28 21:17:02 +02:00
parent 7910e3687c
commit a9264e99a5
14 changed files with 225 additions and 165 deletions

View File

@ -15,10 +15,15 @@ namespace ResourcesManager.Controllers.Tests
[TestClass()] [TestClass()]
public class NotificationsControllerTests public class NotificationsControllerTests
{ {
List<Notification> expectedNotifications; public List<Notification> expectedNotifications;
Mock<INotificationRepository> mockNotifRepo; public Mock<INotificationRepository> mockNotifRepo;
NotificationsController notifController; NotificationsController notifController;
public NotificationsControllerTests()
{
InitializeTestData();
}
[TestInitialize] [TestInitialize]
public void InitializeTestData() public void InitializeTestData()
{ {
@ -28,6 +33,7 @@ namespace ResourcesManager.Controllers.Tests
new Notification() { Id=3, Title = "Cím", Description = "text text" } new Notification() { Id=3, Title = "Cím", Description = "text text" }
}; };
mockNotifRepo = new Mock<INotificationRepository>() { CallBase = true }; mockNotifRepo = new Mock<INotificationRepository>() { CallBase = true };
notifController = new NotificationsController(mockNotifRepo.Object);
mockNotifRepo.Setup(m => m.GetNotifications()).Returns(expectedNotifications); mockNotifRepo.Setup(m => m.GetNotifications()).Returns(expectedNotifications);
@ -75,23 +81,24 @@ namespace ResourcesManager.Controllers.Tests
public void Notification_Unread_Test() public void Notification_Unread_Test()
{ {
var result = notifController.GetUnread(); var result = notifController.GetUnread();
Assert.IsNotNull((result as ViewResult).Model); Assert.IsNotNull((result as JsonResult).Data);
} }
[TestMethod()] [TestMethod()]
public void Notification_Readed_Test() public void Notification_Readed_Test()
{ {
var result = notifController.Readed(1); notifController.Readed(1);
var result = expectedNotifications.FirstOrDefault(n => n.Id == 1);
Assert.Fail(); Assert.AreEqual(result.Readed, true);
} }
[TestMethod()] [TestMethod()]
public void Notification_MakeReadAll_Test() public void Notification_MakeReadAll_Test()
{ {
var result = notifController.MakeReadAll(); notifController.MakeReadAll();
var result = expectedNotifications.All(n => n.Readed == true);
Assert.Fail(); Assert.IsTrue(result);
} }
[TestCleanup] [TestCleanup]

View File

@ -3,6 +3,7 @@ using Moq;
using ResourcesManager.Controllers; using ResourcesManager.Controllers;
using ResourcesManager.Interfaces; using ResourcesManager.Interfaces;
using ResourcesManager.Models; using ResourcesManager.Models;
using ResourcesManagerTests.RepositoryTests;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -16,25 +17,62 @@ namespace ResourcesManager.Controllers.Tests
public class ReservationsControllerTests public class ReservationsControllerTests
{ {
List<Reservation> expectedReservs; List<Reservation> expectedReservs;
Mock<IReservationRepository> mockReservRepo; public Mock<IReservationRepository> mockReservRepo;
Mock<IUserRepository> mockUserRepo;
Mock<IResourceRepository> mockResourceRepo;
Mock<IStatisticRepository> mockStatRepo;
ReservationsController reservController; ReservationsController reservController;
UserRepositoryTests userRepoTest;
ResourcesControllerTests resourceContTest;
StatisticsControllerTests statContTest;
public ReservationsControllerTests()
{
InitializeTestData();
}
[TestInitialize] [TestInitialize]
public void InitializeTestData() public void InitializeTestData()
{ {
expectedReservs = new List<Reservation> { expectedReservs = new List<Reservation> {
new Reservation() { Id=1, Begining = DateTime.Now, End = DateTime.Now.AddHours(1)}, new Reservation() {
new Reservation() { Id=2, Begining = DateTime.Now, End = DateTime.Now.AddHours(1) }, Id =1,
new Reservation() { Id=3, Begining = DateTime.Now, End = DateTime.Now.AddHours(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 }; mockReservRepo = new Mock<IReservationRepository>() { CallBase = true };
mockUserRepo = new Mock<IUserRepository>() { CallBase = true }; resourceContTest = new ResourcesControllerTests();
mockResourceRepo = new Mock<IResourceRepository>() { CallBase = true }; userRepoTest = new UserRepositoryTests();
mockStatRepo = new Mock<IStatisticRepository>() { CallBase = true }; statContTest = new StatisticsControllerTests();
reservController = new ReservationsController(mockReservRepo.Object, mockUserRepo.Object, mockResourceRepo.Object, mockStatRepo.Object); 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.GetReservations()).Returns(expectedReservs);
@ -107,24 +145,24 @@ namespace ResourcesManager.Controllers.Tests
[TestMethod()] [TestMethod()]
public void Reservation_Post_Create_Ok_Test() public void Reservation_Post_Create_Ok_Test()
{ {
var beforeCount = ((reservController.Index() as ViewResult).Model as IEnumerable<Reservation>).Count(); var beforeCount = ((reservController.Index() as ViewResult).Model as ReservationViewModel).Reservations?.Count();
Assert.AreEqual(3, beforeCount); Assert.AreEqual(3, beforeCount);
reservController.Create(new Reservation() { Id = 4, Begining = DateTime.Now, End = DateTime.Now.AddHours(1) }); 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 IEnumerable<Reservation>).Count(); var afterCount = ((reservController.Index() as ViewResult).Model as ReservationViewModel).Reservations?.Count();
Assert.AreEqual(4, afterCount); Assert.AreEqual(4, afterCount);
} }
[TestMethod()] [TestMethod()]
public void Reservation_Post_Create_Fail_Test() public void Reservation_Post_Create_Fail_Test()
{ {
var beforeCount = ((reservController.Index() as ViewResult).Model as IEnumerable<Reservation>).Count(); var beforeCount = ((reservController.Index() as ViewResult).Model as ReservationViewModel).Reservations?.Count();
Assert.AreEqual(3, beforeCount); Assert.AreEqual(3, beforeCount);
reservController.Create(new Reservation() { Id = 4, Begining = DateTime.Now }); reservController.Create(new Reservation() { Id = 4, Begining = DateTime.Now });
var afterCount = ((reservController.Index() as ViewResult).Model as IEnumerable<Reservation>).Count(); var afterCount = ((reservController.Index() as ViewResult).Model as ReservationViewModel).Reservations?.Count();
Assert.AreEqual(3, afterCount); Assert.AreEqual(3, afterCount);
} }
@ -139,8 +177,8 @@ namespace ResourcesManager.Controllers.Tests
public void Reservation_Post_Edit_Ok_Test() public void Reservation_Post_Edit_Ok_Test()
{ {
var beforeBegin = DateTime.Now.AddDays(2); var beforeBegin = DateTime.Now.AddDays(2);
reservController.Edit(new Reservation() { Id = 3, Begining = DateTime.Now, End = DateTime.Now.AddHours(1) }); reservController.Edit(new Reservation() { Id = 3, Begining = beforeBegin, End = DateTime.Now.AddDays(2).AddHours(4), ResourceId = 1 });
object afterBegin = ((reservController.Details(3) as ViewResult).Model as Reservation).Begining; var afterBegin = ((reservController.Details(3) as ViewResult).Model as Reservation).Begining;
Assert.AreEqual(beforeBegin, afterBegin); Assert.AreEqual(beforeBegin, afterBegin);
} }
@ -148,9 +186,9 @@ namespace ResourcesManager.Controllers.Tests
public void Reservation_Post_Edit_Fail_Test() public void Reservation_Post_Edit_Fail_Test()
{ {
var beforeBegin = DateTime.Now.AddDays(2); var beforeBegin = DateTime.Now.AddDays(2);
reservController.Edit(new Reservation() { Id = 3, Begining = DateTime.Now }); reservController.Edit(new Reservation() { Id = 3, Begining = beforeBegin, ResourceId = 1 });
object afterBegin = ((reservController.Details(3) as ViewResult).Model as Reservation).Begining; var afterBegin = ((reservController.Details(3) as ViewResult).Model as Reservation).Begining;
Assert.AreEqual(beforeBegin, afterBegin); Assert.AreNotEqual(beforeBegin, afterBegin);
} }
[TestMethod()] [TestMethod()]
@ -163,24 +201,24 @@ namespace ResourcesManager.Controllers.Tests
[TestMethod()] [TestMethod()]
public void Reservation_Post_Delete_Ok_Test() public void Reservation_Post_Delete_Ok_Test()
{ {
var beforeCount = ((reservController.Index() as ViewResult).Model as IEnumerable<Reservation>).Count(); var beforeCount = ((reservController.Index() as ViewResult).Model as ReservationViewModel).Reservations?.Count();
Assert.AreEqual(3, beforeCount); Assert.AreEqual(3, beforeCount);
reservController.DeleteConfirmed(1); reservController.DeleteConfirmed(1);
var afterCount = ((reservController.Index() as ViewResult).Model as IEnumerable<Reservation>).Count(); var afterCount = ((reservController.Index() as ViewResult).Model as ReservationViewModel).Reservations?.Count();
Assert.AreEqual(2, afterCount); Assert.AreEqual(2, afterCount);
} }
[TestMethod()] [TestMethod()]
public void Reservation_Post_Delete_Fail_Test() public void Reservation_Post_Delete_Fail_Test()
{ {
var beforeCount = ((reservController.Index() as ViewResult).Model as IEnumerable<Reservation>).Count(); var beforeCount = ((reservController.Index() as ViewResult).Model as ReservationViewModel).Reservations?.Count();
Assert.AreEqual(3, beforeCount); Assert.AreEqual(3, beforeCount);
reservController.DeleteConfirmed(8); reservController.DeleteConfirmed(8);
var afterCount = ((reservController.Index() as ViewResult).Model as IEnumerable<Reservation>).Count(); var afterCount = ((reservController.Index() as ViewResult).Model as ReservationViewModel).Reservations?.Count();
Assert.AreEqual(3, afterCount); Assert.AreEqual(3, afterCount);
} }
@ -189,7 +227,9 @@ namespace ResourcesManager.Controllers.Tests
{ {
expectedReservs = null; expectedReservs = null;
mockReservRepo = null; mockReservRepo = null;
mockUserRepo = null; statContTest.Statistic_CleanUpTestData();
resourceContTest.Resources_CleanUpTestData();
userRepoTest.User_CleanUpTestData();
} }
} }
} }

View File

@ -3,6 +3,7 @@ using Moq;
using ResourcesManager.Controllers; using ResourcesManager.Controllers;
using ResourcesManager.Interfaces; using ResourcesManager.Interfaces;
using ResourcesManager.Models; using ResourcesManager.Models;
using ResourcesManagerTests.RepositoryTests;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data.Entity; using System.Data.Entity;
@ -17,10 +18,15 @@ namespace ResourcesManager.Controllers.Tests
[TestClass()] [TestClass()]
public class ResourcesControllerTests public class ResourcesControllerTests
{ {
List<Resource> expectedResources; public List<Resource> expectedResources;
Mock<IResourceRepository> mockResourceRepo; public Mock<IResourceRepository> mockResourceRepo;
Mock<IUserRepository> mockUserRepo;
ResourcesController resourcesController; ResourcesController resourcesController;
UserRepositoryTests userRepoTest;
public ResourcesControllerTests()
{
InitializeTestData();
}
[TestInitialize] [TestInitialize]
public void InitializeTestData() public void InitializeTestData()
@ -31,8 +37,9 @@ namespace ResourcesManager.Controllers.Tests
new Resource() { Id=3, Name = "Kati", AssetTag = "u547547", IsShared = false } new Resource() { Id=3, Name = "Kati", AssetTag = "u547547", IsShared = false }
}; };
mockResourceRepo = new Mock<IResourceRepository>() { CallBase = true }; mockResourceRepo = new Mock<IResourceRepository>() { CallBase = true };
mockUserRepo = new Mock<IUserRepository>() { CallBase = true }; userRepoTest = new UserRepositoryTests();
resourcesController = new ResourcesController(mockResourceRepo.Object, mockUserRepo.Object);
resourcesController = new ResourcesController(mockResourceRepo.Object, userRepoTest.mockUserRepo.Object);
mockResourceRepo.Setup(m => m.GetResouces()).Returns(expectedResources); mockResourceRepo.Setup(m => m.GetResouces()).Returns(expectedResources);
@ -192,7 +199,7 @@ namespace ResourcesManager.Controllers.Tests
{ {
expectedResources = null; expectedResources = null;
mockResourceRepo = null; mockResourceRepo = null;
mockUserRepo = null; userRepoTest.User_CleanUpTestData();
} }
} }
} }

View File

@ -3,6 +3,7 @@ using Moq;
using ResourcesManager.Controllers; using ResourcesManager.Controllers;
using ResourcesManager.Interfaces; using ResourcesManager.Interfaces;
using ResourcesManager.Models; using ResourcesManager.Models;
using ResourcesManagerTests.RepositoryTests;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -16,8 +17,15 @@ namespace ResourcesManager.Controllers.Tests
public class StatisticsControllerTests public class StatisticsControllerTests
{ {
List<StatisticModel> expectedStat; List<StatisticModel> expectedStat;
Mock<IStatisticRepository> mockStatRepo; public Mock<IStatisticRepository> mockStatRepo;
StatisticsController statController; StatisticsController statController;
ResourcesControllerTests resourcesContTest;
UserRepositoryTests userRepoTest;
public StatisticsControllerTests()
{
InitializeStatisticTestData();
}
[TestInitialize] [TestInitialize]
public void InitializeStatisticTestData() public void InitializeStatisticTestData()
@ -28,7 +36,9 @@ namespace ResourcesManager.Controllers.Tests
new StatisticModel(){ Id= 3, ResourceId = 3, ReservationId = 3, StatisticType = StatisticType.ResourceCreate, 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 }; mockStatRepo = new Mock<IStatisticRepository>() { CallBase = true };
statController = new StatisticsController(mockStatRepo.Object); 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.GetStatistics()).Returns(expectedStat);
@ -50,12 +60,14 @@ namespace ResourcesManager.Controllers.Tests
var result = statController.Index(StatisticType.Login, 1); var result = statController.Index(StatisticType.Login, 1);
Assert.IsNotNull((result as ViewResult).Model); Assert.IsNotNull((result as ViewResult).Model);
} }
//todo: még
[TestCleanup] [TestCleanup]
public void CleanUpTestData() public void Statistic_CleanUpTestData()
{ {
expectedStat = null; expectedStat = null;
mockStatRepo = null; resourcesContTest.Resources_CleanUpTestData();
userRepoTest.User_CleanUpTestData();
} }
} }
} }

View File

@ -3,6 +3,7 @@ using Moq;
using ResourcesManager.Controllers; using ResourcesManager.Controllers;
using ResourcesManager.Interfaces; using ResourcesManager.Interfaces;
using ResourcesManager.Models; using ResourcesManager.Models;
using ResourcesManagerTests.RepositoryTests;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -15,18 +16,22 @@ namespace ResourcesManager.Controllers.Tests
[TestClass()] [TestClass()]
public class SubscribeControllerTests public class SubscribeControllerTests
{ {
Mock<IResourceRepository> mockResourceRepo;
Mock<IUserRepository> mockUserRepo;
Mock<IStatisticRepository> mockStatRepo;
SubscribeController subController; SubscribeController subController;
ResourcesControllerTests resoucesContTest;
UserRepositoryTests userRepoTest;
StatisticsControllerTests statContTest;
public SubscribeControllerTests()
{
InitializeTestData();
}
[TestInitialize] [TestInitialize]
public void InitializeTestData() public void InitializeTestData()
{ {
mockResourceRepo = new Mock<IResourceRepository>() { CallBase = true }; resoucesContTest = new ResourcesControllerTests();
mockUserRepo = new Mock<IUserRepository>() { CallBase = true }; userRepoTest = new UserRepositoryTests();
mockStatRepo = new Mock<IStatisticRepository> { CallBase = true }; statContTest = new StatisticsControllerTests();
subController = new SubscribeController(mockResourceRepo.Object, mockUserRepo.Object, mockStatRepo.Object); subController = new SubscribeController(resoucesContTest.mockResourceRepo.Object, userRepoTest.mockUserRepo.Object, statContTest.mockStatRepo.Object);
} }
[TestMethod()] [TestMethod()]
@ -39,38 +44,34 @@ namespace ResourcesManager.Controllers.Tests
[TestMethod()] [TestMethod()]
public void Subscribe_Follow_Test() public void Subscribe_Follow_Test()
{ {
var result = subController.Follow(1); subController.Follow(1);
var list = ((subController.Index() as ViewResult).Model as List<Resource>); var result = resoucesContTest.expectedResources.FirstOrDefault(r => r.Id == 1);
Assert.Fail(); Assert.IsNotNull(result.Users);
} }
[TestMethod()] [TestMethod()]
public void Subscribe_UnFollowAll_Test() public void Subscribe_UnFollowAll_Test()
{ {
var result = subController.UnFollowAll(); subController.UnFollowAll();
Assert.Fail(); var result = resoucesContTest.expectedResources.All(x => x.Users == null || x.Users.Count == 0);
} Assert.IsTrue(result);
[TestMethod()]
public void Subscribe_FollowAllSubscribeTest()
{
var result = subController.UnFollowAll();
Assert.Fail();
} }
[TestMethod()] [TestMethod()]
public void Subscribe_Unfollow_Test() public void Subscribe_Unfollow_Test()
{ {
var result = subController.Unfollow(1); subController.Unfollow(1);
Assert.Fail(); var result = resoucesContTest.expectedResources.FirstOrDefault(r => r.Id == 1);
var count = result.Users.Count;
Assert.AreEqual(count, 0);
} }
[TestCleanup] [TestCleanup]
public void Resources_CleanUpTestData() public void Resources_CleanUpTestData()
{ {
mockResourceRepo = null; resoucesContTest.Resources_CleanUpTestData();
mockUserRepo = null; userRepoTest.User_CleanUpTestData();
mockStatRepo = null; statContTest = null;
} }
} }
} }

View File

@ -14,7 +14,12 @@ namespace ResourcesManagerTests.RepositoryTests
class UserRepositoryTests class UserRepositoryTests
{ {
List<ApplicationUser> expectedUsers; List<ApplicationUser> expectedUsers;
Mock<IUserRepository> mockUserRepo; public Mock<IUserRepository> mockUserRepo;
public UserRepositoryTests()
{
InitializeTestData();
}
[TestInitialize] [TestInitialize]
public void InitializeTestData() public void InitializeTestData()
@ -27,50 +32,10 @@ namespace ResourcesManagerTests.RepositoryTests
mockUserRepo = new Mock<IUserRepository>() { CallBase = true }; mockUserRepo = new Mock<IUserRepository>() { CallBase = true };
mockUserRepo.Setup(m => m.GetUsers()).Returns(expectedUsers); mockUserRepo.Setup(m => m.GetUsers()).Returns(expectedUsers);
//mockUserRepo.Setup(m => m.GetUserByID(It.IsAny<string>())).Returns((string id) =>
//{
// return expectedUsers.FirstOrDefault(x => x.Id == id);
//});
//mockUserRepo.Setup(m => m.(It.IsAny<Resource>())).Returns((Resource resource) =>
//{
// expectedUsers.Add(resource);
// return true;
//});
//mockUserRepo.Setup(m => m.UpdateResouce(It.IsAny<Resource>())).Returns((Resource target) =>
//{
// var resource = expectedUsers.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;
//});
//mockUserRepo.Setup(m => m.DeleteResouce(It.IsAny<int>())).Returns((int id) =>
//{
// var resource = expectedUsers.FirstOrDefault(x => x.Id == id);
// if (resource == null)
// {
// return false;
// }
// expectedUsers.Remove(resource);
// return true;
//});
} }
[TestCleanup] [TestCleanup]
public void Resources_CleanUpTestData() public void User_CleanUpTestData()
{ {
expectedUsers = null; expectedUsers = null;
mockUserRepo = null; mockUserRepo = null;

View File

@ -45,37 +45,35 @@ namespace ResourcesManager.Controllers
notifRepo.UpdateNotification(notif); notifRepo.UpdateNotification(notif);
if (string.IsNullOrEmpty(link) || link == "null") if (string.IsNullOrEmpty(link) || link == "null")
{ {
return Redirect(Request.UrlReferrer.ToString()); return Redirect(Request?.UrlReferrer?.ToString() ?? "/");
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.Error("", ex); logger.Error("", ex);
} }
return Redirect(link); return Redirect(link ?? "/");
} }
public ActionResult GetUnread() public ActionResult GetUnread()
{ {
using (ApplicationDbContext db = new ApplicationDbContext()) try
{ {
try 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);
{ }
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)
} {
catch (Exception e) logger.Warn("hiba", e);
{ return null;
logger.Warn("hiba", e);
return null;
}
} }
} }
public ActionResult MakeReadAll() public ActionResult MakeReadAll()
{ {
try try
{ {
var list = notifRepo.GetNotifications().Where(k => k.Readed == false && (k.User == User.Identity.Name || k.User == null)).ToList(); var list = notifRepo.GetNotifications().Where(k => k.Readed == false && (k.User == User?.Identity?.Name || k.User == null)).ToList();
foreach (var item in list) foreach (var item in list)
{ {
item.Readed = true; item.Readed = true;
@ -86,7 +84,7 @@ namespace ResourcesManager.Controllers
{ {
logger.Error("", ex); logger.Error("", ex);
} }
return Redirect(HttpContext.Request.UrlReferrer.ToString()); return Redirect(HttpContext?.Request?.UrlReferrer?.ToString() ?? "/");
} }
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)

View File

@ -193,7 +193,7 @@ namespace ResourcesManager.Controllers
try try
{ {
model.Resource = resourceRepo.GetResourceByID(model.ResourceId); model.Resource = resourceRepo.GetResourceByID(model.ResourceId);
model.User = User.Identity.Name; model.User = User?.Identity?.Name;
if (model.Resource.TimeLimit != null) if (model.Resource.TimeLimit != null)
{ {
TimeSpan difference = model.End.Subtract(model.Begining); TimeSpan difference = model.End.Subtract(model.Begining);
@ -245,7 +245,7 @@ namespace ResourcesManager.Controllers
//Értesítés küldés //Értesítés küldés
var users = model.Resource.Users.Select(k => k.UserName).ToList(); 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; string url = "/Reservations/Details/" + model.Id;
NotificationHelper.Send(users, "Foglalás", message, model.Resource.ImagePath, url); NotificationHelper.Send(users, "Foglalás", message, model.Resource.ImagePath, url);
return RedirectToAction("Details", "Reservations", new { Id = model.Id }); return RedirectToAction("Details", "Reservations", new { Id = model.Id });
@ -272,9 +272,9 @@ namespace ResourcesManager.Controllers
log.Warn("HttpNotFound"); log.Warn("HttpNotFound");
return 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("PermissionError");
} }
return View(reservation); return View(reservation);
@ -294,9 +294,9 @@ namespace ResourcesManager.Controllers
{ {
try 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"); return View("PermissionError");
} }
var resource = resourceRepo.GetResourceByID(reservation.ResourceId); var resource = resourceRepo.GetResourceByID(reservation.ResourceId);
@ -352,7 +352,7 @@ namespace ResourcesManager.Controllers
//Értesítés küldés //Értesítés küldés
var users = resource.Users.Select(k => k.UserName).ToList(); 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; string url = "/Reservations/Details/" + reservation.Id;
NotificationHelper.Send(users, "Foglalás módosítás", message, resource.ImagePath, url); NotificationHelper.Send(users, "Foglalás módosítás", message, resource.ImagePath, url);
return RedirectToAction("Details", "Reservations", new { Id = reservation.Id }); return RedirectToAction("Details", "Reservations", new { Id = reservation.Id });
@ -376,9 +376,9 @@ namespace ResourcesManager.Controllers
return new HttpStatusCodeResult(HttpStatusCode.BadRequest); return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
} }
Reservation reservation = reservRepo.GetReservationByID((int)id); Reservation reservation = reservRepo.GetReservationByID((int)id);
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"); return View("PermissionError");
} }
if (reservation == null) if (reservation == null)
@ -402,14 +402,14 @@ namespace ResourcesManager.Controllers
try try
{ {
var reservation = reservRepo.GetReservationByID(id); var reservation = reservRepo.GetReservationByID(id);
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"); return View("PermissionError");
} }
//Értesítés küldés //Értesítés küldés
var users = reservation.Resource.Users.Select(k => k.UserName).ToList(); 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); NotificationHelper.Send(users, "Foglalás törlés", message, reservation.Resource.ImagePath, null);
reservRepo.DeleteReservation(reservation.Id); reservRepo.DeleteReservation(reservation.Id);

View File

@ -90,10 +90,10 @@ namespace ResourcesManager.Controllers
{ {
try try
{ {
var stream = Request.Files[0].InputStream; var stream = Request?.Files[0]?.InputStream;
string path; string path;
if (stream.Length != 0) if (stream != null && stream.Length != 0)
{ {
var img = new WebImage(stream); var img = new WebImage(stream);
string fileName = Path.GetRandomFileName(); string fileName = Path.GetRandomFileName();
@ -116,13 +116,13 @@ namespace ResourcesManager.Controllers
resource.ImagePath = "~/App_Data/ResourceImages/" + fileName; resource.ImagePath = "~/App_Data/ResourceImages/" + fileName;
stream.Flush();
stream.Close();
} }
else else
{ {
resource.ImagePath = "~/App_Data/ResourceImages/DefaultResource.png"; resource.ImagePath = "~/App_Data/ResourceImages/DefaultResource.png";
} }
stream.Flush();
stream.Close();
return resource; return resource;
} }
@ -174,6 +174,11 @@ namespace ResourcesManager.Controllers
ModelState.AddModelError("AssetTag", "Ilyen már létezik"); ModelState.AddModelError("AssetTag", "Ilyen már létezik");
return View(resource); return View(resource);
} }
if (string.IsNullOrEmpty(resource.AssetTag))
{
ModelState.AddModelError("AssetTag", "Kötelező mező");
return View(resource);
}
if (resource.TimeLimit < 1) if (resource.TimeLimit < 1)
{ {
ModelState.AddModelError("TimeLimit", "Nem lehet negatív"); ModelState.AddModelError("TimeLimit", "Nem lehet negatív");
@ -251,6 +256,11 @@ namespace ResourcesManager.Controllers
ModelState.AddModelError("AssetTag", "Ilyen már létezik"); ModelState.AddModelError("AssetTag", "Ilyen már létezik");
return View(model); 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 //Kép feltöltés ellenörzése
var stream = Request?.Files[0]?.InputStream; var stream = Request?.Files[0]?.InputStream;
@ -296,7 +306,7 @@ namespace ResourcesManager.Controllers
//Értesítés küldés //Értesítés küldés
var users = model.Users.Select(k => k.UserName).ToList(); 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; string url = "/Resources/Details/" + resource.Id;
NotificationHelper.Send(users, "Erőforrás módosítás", message, resource.ImagePath, url); NotificationHelper.Send(users, "Erőforrás módosítás", message, resource.ImagePath, url);

View File

@ -11,6 +11,7 @@ using ResourcesManager.ViewModels;
using System.Data.Entity.Core.Objects; using System.Data.Entity.Core.Objects;
using ResourcesManager.Interfaces; using ResourcesManager.Interfaces;
using ResourcesManager.Repositories; using ResourcesManager.Repositories;
using ResourcesManager.Handlers;
namespace ResourcesManager.Controllers namespace ResourcesManager.Controllers
{ {
@ -18,42 +19,57 @@ namespace ResourcesManager.Controllers
{ {
private ApplicationDbContext context; private ApplicationDbContext context;
private IStatisticRepository statisticRepository; private IStatisticRepository statisticRepository;
private IResourceRepository resourceRepo;
private IUserRepository userRepo;
readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public StatisticsController() public StatisticsController()
{ {
context = new ApplicationDbContext(); context = new ApplicationDbContext();
this.statisticRepository = new StatisticRepository(context); statisticRepository = new StatisticRepository(context);
resourceRepo = new ResourceRepository(context);
userRepo = new UserRepository(context);
} }
public StatisticsController(IStatisticRepository statisticRepository) public StatisticsController(IStatisticRepository statisticRepository, IResourceRepository resourceRepo, IUserRepository userRepo)
{ {
this.statisticRepository = statisticRepository; this.statisticRepository = statisticRepository;
this.resourceRepo = resourceRepo;
this.userRepo = userRepo;
} }
public ActionResult Index(StatisticType? statTypeId, int? resId) 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 = context.Resources.FirstOrDefault().Id; log.Error(ex);
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
} }
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 => DbFunctions.TruncateTime(l.DateTime)).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 => DbFunctions.TruncateTime(l.DateTime)).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 = context.Resources.Select(k => k.Users.Count()).Sum();
var allUsers = context.Users.Count() * context.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(context.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) protected override void Dispose(bool disposing)
@ -61,6 +77,9 @@ namespace ResourcesManager.Controllers
if (disposing) if (disposing)
{ {
context.Dispose(); context.Dispose();
statisticRepository.Dispose();
resourceRepo.Dispose();
userRepo.Dispose();
} }
base.Dispose(disposing); base.Dispose(disposing);
} }

View File

@ -1,4 +1,5 @@
using ResourcesManager.Interfaces; using Microsoft.AspNet.Identity;
using ResourcesManager.Interfaces;
using ResourcesManager.Models; using ResourcesManager.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;

View File

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

View File

@ -37,7 +37,7 @@
<td> <td>
<div class="btn-group"> <div class="btn-group">
@Html.ActionLink("Részletek", "Details", "Reservations", new { id = item.Id }, new { @class = "btn btn-info" }) @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("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" }) @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"> <div class="btn-group">
@{ @{
var user = User.Identity.Name; var user = User?.Identity?.Name;
if (item.Users.Any(e => e.UserName == user)) if (item.Users.Any(e => e.UserName == user))
{ {
@Html.ActionLink("Leíratkozás", "Unfollow", new { ResourceId = item.Id }, new { @class = "btn btn-default" }) @Html.ActionLink("Leíratkozás", "Unfollow", new { ResourceId = item.Id }, new { @class = "btn btn-default" })