diff --git a/AssemblyInfo.General.cs b/AssemblyInfo.General.cs index 22c996d..3dc431f 100644 --- a/AssemblyInfo.General.cs +++ b/AssemblyInfo.General.cs @@ -3,5 +3,5 @@ [assembly: AssemblyCompany("Национальный Исследовательский Ядерный Университет МИФИ")] [assembly: AssemblyProduct("GraphLabs")] -[assembly: AssemblyCopyright("Copyright © 2012-2016")] +[assembly: AssemblyCopyright("Copyright © 2012-2018")] [assembly: AssemblyTrademark("")] \ No newline at end of file diff --git a/Class1.cs b/Class1.cs new file mode 100644 index 0000000..d555ecb --- /dev/null +++ b/Class1.cs @@ -0,0 +1,8 @@ +using System; + +public class Class1 +{ + public Class1() + { + } +} diff --git a/GraphLabs.Dal.Ef/GraphLabs.Dal.Ef.csproj b/GraphLabs.Dal.Ef/GraphLabs.Dal.Ef.csproj index 2f4ed58..389fd55 100644 --- a/GraphLabs.Dal.Ef/GraphLabs.Dal.Ef.csproj +++ b/GraphLabs.Dal.Ef/GraphLabs.Dal.Ef.csproj @@ -233,6 +233,10 @@ {3e515720-d0a1-4b01-a3e0-c82412b2d663} GraphLabs.DomainModel + + {d0a05aef-dc7e-4b2b-a82a-9a23eaa0af95} + GraphLabs.Guard + {d62cc3f4-3ea1-44ff-b9e2-492582788b3b} GraphLabs.Site.Core diff --git a/GraphLabs.Dal.Ef/GraphLabsContextImpl.cs b/GraphLabs.Dal.Ef/GraphLabsContextImpl.cs index 74acc5f..059413f 100644 --- a/GraphLabs.Dal.Ef/GraphLabsContextImpl.cs +++ b/GraphLabs.Dal.Ef/GraphLabsContextImpl.cs @@ -5,6 +5,7 @@ using GraphLabs.DomainModel.Contexts; using GraphLabs.DomainModel.Infrastructure; + namespace GraphLabs.Dal.Ef { class GraphLabsContextImpl : IGraphLabsContext, IEntityQuery, IEntityFactory @@ -34,7 +35,7 @@ public GraphLabsContextImpl(GraphLabsContext ctx) private Type GetEntityTypeFor(Type type) { - Contract.Assert(typeof(AbstractEntity).IsAssignableFrom(type)); + Guard.AreAssignedTypes(typeof(AbstractEntity), type); var baseType = type.BaseType; if (baseType == typeof(AbstractEntity)) diff --git a/GraphLabs.Dal.Ef/Infrastructure/ChangesTracker.cs b/GraphLabs.Dal.Ef/Infrastructure/ChangesTracker.cs index f5f9e33..1a9bcba 100644 --- a/GraphLabs.Dal.Ef/Infrastructure/ChangesTracker.cs +++ b/GraphLabs.Dal.Ef/Infrastructure/ChangesTracker.cs @@ -17,7 +17,7 @@ public class ChangesTracker : IChangesTracker /// Менеджер изменений public ChangesTracker(GraphLabsContext context) { - Contract.Requires(context != null); + Guard.IsNotNull(nameof(context), context ); _context = context; } diff --git a/GraphLabs.Dal.Ef/Infrastructure/EntityChange.cs b/GraphLabs.Dal.Ef/Infrastructure/EntityChange.cs index 9204f71..3c644f6 100644 --- a/GraphLabs.Dal.Ef/Infrastructure/EntityChange.cs +++ b/GraphLabs.Dal.Ef/Infrastructure/EntityChange.cs @@ -27,17 +27,25 @@ public EntityChange(DbEntityEntry entry) /// Изменилось ли свойство? public bool PropertyChanged(string propertyName) { + Guard.IsNotNullOrWhiteSpace(propertyName); return _entry.CurrentValues[propertyName] != _entry.OriginalValues[propertyName]; } public IReadOnlyDictionary OriginalValues { - get { return _originalValues.Value; } + + get + { + return _originalValues.Value; + } } public IReadOnlyDictionary CurrentValues { - get { return _currentValues.Value; } + get + { + return _currentValues.Value; + } } } } diff --git a/GraphLabs.Dal.Ef/Infrastructure/EntitySet.cs b/GraphLabs.Dal.Ef/Infrastructure/EntitySet.cs index 00bab96..dd079a9 100644 --- a/GraphLabs.Dal.Ef/Infrastructure/EntitySet.cs +++ b/GraphLabs.Dal.Ef/Infrastructure/EntitySet.cs @@ -29,6 +29,7 @@ public TEntity Find(params object[] keyValues) /// Не удалось найти сущность с заданным ключом public TEntity Get(params object[] keyValues) { + Guard.IsPositive(keyValues.Length, nameof(keyValues)); var entity = _ctx.Set().Find(keyValues); if (entity == null) throw new EntityNotFoundException(typeof(TEntity), keyValues); @@ -42,7 +43,7 @@ public TDerivedEntity CreateNew() where TDerivedEntity : TEntity var set = _ctx.Set(); var entity = set.Create(); set.Add(entity); - + Guard.IsNotNull(entity); return entity; } @@ -52,7 +53,7 @@ public TEntity CreateNew() var set = _ctx.Set(); var entity = set.Create(); set.Add(entity); - + Guard.IsNotNull(entity, "entity"); return entity; } } diff --git a/GraphLabs.Dal.Ef/IoC/DalConfiguration.cs b/GraphLabs.Dal.Ef/IoC/DalConfiguration.cs index 7e927f4..ff44890 100644 --- a/GraphLabs.Dal.Ef/IoC/DalConfiguration.cs +++ b/GraphLabs.Dal.Ef/IoC/DalConfiguration.cs @@ -8,6 +8,7 @@ using GraphLabs.Site.Core.OperationContext; using GraphLabs.Site.Utils.IoC; using Microsoft.Practices.Unity; +using GraphLabs; namespace GraphLabs.Dal.Ef.IoC { @@ -17,6 +18,7 @@ public sealed class DalConfiguration : IUnityRegistry /// Сконфигурировать public void ConfigureContainer(IUnityContainer container) { + Guard.IsNotNull(nameof(container), container); // Сам EF-контекст container.RegisterType(new HierarchicalLifetimeManager()); diff --git a/GraphLabs.Dal.Ef/Repositories/CategoryRepository.cs b/GraphLabs.Dal.Ef/Repositories/CategoryRepository.cs index 79a0027..437d3f5 100644 --- a/GraphLabs.Dal.Ef/Repositories/CategoryRepository.cs +++ b/GraphLabs.Dal.Ef/Repositories/CategoryRepository.cs @@ -17,22 +17,27 @@ public CategoryRepository(GraphLabsContext context) /// Получить категорию по id public Category GetById(long id) { + Guard.IsPositive(id, nameof(id) ); CheckNotDisposed(); - return Context.Categories.Single(c => c.Id == id); + var result = Context.Categories.Single(c => c.Id == id); + Guard.IsNotNull(result); + return (result); } /// Получить все категории public Category[] GetAllCategories() { CheckNotDisposed(); - - return Context.Categories.ToArray(); + var result = Context.Categories.ToArray(); + Guard.IsNotNull(result); + return result; } /// Сохранение категории public void SaveCategory(Category category) { + Guard.IsNotNull(nameof(category), category); CheckNotDisposed(); Context.Categories.Add(category); @@ -42,7 +47,8 @@ public void SaveCategory(Category category) /// Редактирование категории public void EditCategory(Category category) { - CheckNotDisposed(); + Guard.IsNotNull(nameof(category), category); + CheckNotDisposed(); Context.Entry(category).State = EntityState.Modified; Context.SaveChanges(); diff --git a/GraphLabs.Dal.Ef/Repositories/GroupRepository.cs b/GraphLabs.Dal.Ef/Repositories/GroupRepository.cs index 6dc5d1c..bf69683 100644 --- a/GraphLabs.Dal.Ef/Repositories/GroupRepository.cs +++ b/GraphLabs.Dal.Ef/Repositories/GroupRepository.cs @@ -19,24 +19,28 @@ public GroupRepository(GraphLabsContext context) public Group[] GetAllGroups() { CheckNotDisposed(); - - return Context.Groups.ToArray(); + var result = Context.Groups.ToArray(); + Guard.IsNotNull(result); + return result; } /// Получить группы, открытые для регистрации public Group[] GetOpenGroups() { CheckNotDisposed(); - - return Context.Groups.Where(g => g.IsOpen).ToArray(); + var result = Context.Groups.Where(g => g.IsOpen).ToArray(); + Guard.IsNotNull(result); + return result; } /// Получить группу по id public Group GetGroupById(long id) { + Guard.IsPositive(id, "id"); CheckNotDisposed(); - - return Context.Groups.Where(g => g.Id == id).Single(); + var result = Context.Groups.Where(g => g.Id == id).Single(); + Guard.IsNotNull(result); + return result; } } } diff --git a/GraphLabs.Dal.Ef/Repositories/LabRepository.cs b/GraphLabs.Dal.Ef/Repositories/LabRepository.cs index 67c457b..5b2d044 100644 --- a/GraphLabs.Dal.Ef/Repositories/LabRepository.cs +++ b/GraphLabs.Dal.Ef/Repositories/LabRepository.cs @@ -35,22 +35,27 @@ public LabVariant[] GetLabVariantsByLabWorkId(long id) /// Получить ознакомительные варианты лабораторной работы по id лабораторной работы public LabVariant[] GetDemoLabVariantsByLabWorkId(long labId) { + Guard.IsPositive(labId,nameof(labId)); CheckNotDisposed(); - - return Context.LabVariants + var result = Context.LabVariants .Where(lv => lv.LabWork.Id == labId) .Where(lv => lv.IntroducingVariant) .ToArray(); + Guard.IsNotNull(result); + return result; + } /// Получить готовые ознакомительные варианты лабораторной работы по id лабораторной работы public LabVariant[] GetCompleteDemoLabVariantsByLabWorkId(long labId) { + Guard.IsPositive(labId, nameof(labId)); CheckNotDisposed(); - - return GetDemoLabVariantsByLabWorkId(labId) + var result = GetDemoLabVariantsByLabWorkId(labId) .Where(lv => VerifyCompleteVariant(lv.Id)) .ToArray(); + Guard.IsNotNull(result); + return result; } #endregion @@ -60,6 +65,7 @@ public LabVariant[] GetCompleteDemoLabVariantsByLabWorkId(long labId) /// Проверить существование лабораторной работы public bool CheckLabWorkExist(long id) { + Guard.IsPositive(id, nameof(id)); CheckNotDisposed(); LabWork lab = Context.LabWorks.SingleOrDefault(l => l.Id == id); @@ -70,6 +76,7 @@ public bool CheckLabWorkExist(long id) /// Проверить существование лабораторной работы по имени public bool CheckLabWorkExist(string name) { + Guard.IsTrueAssertion(name != ""); CheckNotDisposed(); LabWork lab = Context.LabWorks.SingleOrDefault(l => l.Name == name); @@ -80,6 +87,7 @@ public bool CheckLabWorkExist(string name) /// Проверить существование варианта лабораторной работы по Id public bool CheckLabVariantExist(long id) { + Guard.IsPositive(id, nameof(id)); CheckNotDisposed(); LabVariant labVariant = Context.LabVariants.SingleOrDefault(l => l.Id == id); @@ -90,7 +98,10 @@ public bool CheckLabVariantExist(long id) /// Проверить существование варианта лабораторной работы по имени public bool CheckLabVariantExist(long labId, string name) { - CheckNotDisposed(); + Guard.IsPositive(labId, nameof(labId)); + Guard.IsTrueAssertion(name != ""); + + CheckNotDisposed(); LabVariant labVariant = Context.LabVariants .Where(lv => lv.LabWork.Id == labId) @@ -102,6 +113,8 @@ public bool CheckLabVariantExist(long labId, string name) /// Проверить принадлежность варианта л.р. лабораторной работе public bool CheckLabVariantBelongLabWork(long labId, long labVarId) { + Guard.IsPositive(labId, nameof(labId)); + Guard.IsPositive(labVarId, nameof(labVarId)); CheckNotDisposed(); LabVariant labVariant = Context.LabVariants.Where(lv => lv.Id == labVarId).SingleOrDefault(lv => lv.LabWork.Id == labId); @@ -112,6 +125,7 @@ public bool CheckLabVariantBelongLabWork(long labId, long labVarId) /// Проверка соответствия варианта лабораторной работы содержанию работы public bool VerifyCompleteVariant(long variantId) { + Guard.IsPositive(variantId, nameof(variantId)); CheckNotDisposed(); long labWorkId = Context.LabVariants @@ -140,24 +154,29 @@ public bool VerifyCompleteVariant(long variantId) /// Получить лабораторную работу по id public LabWork GetLabWorkById(long id) { + Guard.IsPositive(id, nameof(id)); CheckNotDisposed(); - - return Context.LabWorks.SingleOrDefault(l => l.Id == id); + var result = Context.LabWorks.SingleOrDefault(l => l.Id == id); + Guard.IsNotNull(result); + return result; } /// Получить вариант л.р. по id public LabVariant GetLabVariantById(long id) { - CheckNotDisposed(); - - return Context.LabVariants - .Include(lv => lv.LabWork) - .SingleOrDefault(lv => lv.Id == id); + Guard.IsPositive(id, nameof(id)); + CheckNotDisposed(); + var result = Context.LabVariants + .Include(lv => lv.LabWork) + .SingleOrDefault(lv => lv.Id == id); + Guard.IsNotNull(result); + return result; } /// Найти вариант лабораторной работы по id public LabVariant FindLabVariantById(long id) { + Guard.IsPositive(id, nameof(id)); CheckNotDisposed(); return Context.LabVariants.SingleOrDefault(lv => lv.Id == id); @@ -166,13 +185,15 @@ public LabVariant FindLabVariantById(long id) /// Получить варианты заданий с заданиями варианта лабораторной работы public TaskVariant[] GetTaskVariantsByLabVarId(long labVarId) { + Guard.IsPositive(labVarId, nameof(labVarId)); CheckNotDisposed(); - - return Context.LabVariants + var result = Context.LabVariants .Where(v => v.Id == labVarId) .SelectMany(v => v.TaskVariants) .Include(v => v.Task) .ToArray(); + Guard.IsNotNull(result); + return result; } #endregion @@ -182,6 +203,7 @@ public TaskVariant[] GetTaskVariantsByLabVarId(long labVarId) /// Удаление содержания лабораторной работы public void DeleteEntries(long labWorkId) { + Guard.IsPositive(labWorkId, nameof(labWorkId)); CheckNotDisposed(); var entries = (from e in Context.LabEntries @@ -198,6 +220,7 @@ public void DeleteEntries(long labWorkId) /// Сохранение лабораторной работы public void SaveLabWork(LabWork lab) { + Guard.IsNotNull(nameof(lab), lab); CheckNotDisposed(); Context.LabWorks.Add(lab); @@ -207,7 +230,9 @@ public void SaveLabWork(LabWork lab) /// Изменение лабораторной работы public void ModifyLabWork(LabWork lab) { - CheckNotDisposed(); + Guard.IsNotNull(nameof(lab), lab); + Guard.IsPositive(lab.Id, nameof(lab)); + CheckNotDisposed(); Context.Entry(lab).State = EntityState.Modified; Context.SaveChanges(); @@ -216,7 +241,9 @@ public void ModifyLabWork(LabWork lab) /// Сохранение содержания лабораторной работы public void SaveLabEntries(long labWorkId, long[] tasksId) { - CheckNotDisposed(); + Guard.IsPositive(labWorkId, nameof(labWorkId)); + Guard.IsNotNull(nameof(tasksId), tasksId); + CheckNotDisposed(); int i = 0; LabWork lab = GetLabWorkById(labWorkId); @@ -237,7 +264,8 @@ public void SaveLabEntries(long labWorkId, long[] tasksId) /// Удаляет лишние варианты заданий из вариантов лабораторной работы для соответствия содержанию public void DeleteExcessTaskVariantsFromLabVariants(long labWorkId) { - CheckNotDisposed(); + Guard.IsPositive(labWorkId, nameof(labWorkId)); + CheckNotDisposed(); bool flag; var labTasks = (from e in Context.LabEntries @@ -272,6 +300,7 @@ public void DeleteExcessTaskVariantsFromLabVariants(long labWorkId) /// Сохранение варианта л.р. public void SaveLabVariant(LabVariant labVar) { + Guard.IsNotNull(nameof(labVar), labVar); CheckNotDisposed(); Context.LabVariants.Add(labVar); @@ -281,7 +310,8 @@ public void SaveLabVariant(LabVariant labVar) /// Изменение варианта л.р. public void ModifyLabVariant(LabVariant labVar) { - CheckNotDisposed(); + Guard.IsNotNull(nameof(labVar), labVar); + CheckNotDisposed(); Context.Entry(labVar).State = EntityState.Modified; Context.SaveChanges(); @@ -294,15 +324,19 @@ public void ModifyLabVariant(LabVariant labVar) /// Получить id лабораторной работы по ее имени public long GetLabWorkIdByName(string name) { + Guard.IsTrueAssertion(name != ""); CheckNotDisposed(); - - return Context.LabWorks.Single(l => l.Name == name).Id; + var result = Context.LabWorks.Single(l => l.Name == name).Id; + Guard.IsTrueAssertion(result != 0); + return result; } /// Получить id варианта л.р. по его имени public long GetLabVariantIdByNumber(long labId, string number) { - CheckNotDisposed(); + Guard.IsPositive(labId, nameof(labId)); + Guard.IsTrueAssertion(number != ""); + CheckNotDisposed(); return Context.LabVariants .Where(lv => lv.LabWork.Id == labId) diff --git a/GraphLabs.Dal.Ef/Repositories/RepositoryBase.cs b/GraphLabs.Dal.Ef/Repositories/RepositoryBase.cs index 1babb2e..e533ae2 100644 --- a/GraphLabs.Dal.Ef/Repositories/RepositoryBase.cs +++ b/GraphLabs.Dal.Ef/Repositories/RepositoryBase.cs @@ -13,7 +13,7 @@ public abstract class RepositoryBase : IDisposable /// Базовый репозиторий protected RepositoryBase(GraphLabsContext context) { - Contract.Requires(context != null); + Guard.IsNotNull(nameof(context), context); _disposed = false; Context = context; diff --git a/GraphLabs.Dal.Ef/Repositories/RepositoryFactory.cs b/GraphLabs.Dal.Ef/Repositories/RepositoryFactory.cs index ec1befd..f0ab806 100644 --- a/GraphLabs.Dal.Ef/Repositories/RepositoryFactory.cs +++ b/GraphLabs.Dal.Ef/Repositories/RepositoryFactory.cs @@ -17,7 +17,7 @@ public sealed class RepositoryFactory /// Фабрика репозиториев public RepositoryFactory(GraphLabsContext context, ISystemDateService systemDateService, ITasksContext tasksContext) { - Contract.Requires(context != null); + Guard.IsNotNull(nameof(context), context); _context = context; _systemDateService = systemDateService; _tasksContext = tasksContext; @@ -27,60 +27,60 @@ public RepositoryFactory(GraphLabsContext context, ISystemDateService systemDate [NotNull] public IGroupRepository GetGroupRepository() { - Contract.Ensures(Contract.Result() != null); - - return new GroupRepository(_context); + var groupRepository = new GroupRepository(_context); + Guard.IsNotNull(nameof(groupRepository), groupRepository); + return groupRepository; } /// Получить репозиторий с группами [NotNull] public IUserRepository GetUserRepository() { - Contract.Ensures(Contract.Result() != null); - - return new UserRepository(_context); + var userRepository = new UserRepository(_context); + Guard.IsNotNull(nameof(userRepository), userRepository); + return userRepository; } /// Получить репозиторий с группами [NotNull] public ISessionRepository GetSessionRepository() { - Contract.Ensures(Contract.Result() != null); - - return new SessionRepository(_context, _systemDateService); + var sessionRepository = new SessionRepository(_context, _systemDateService); + Guard.IsNotNull(nameof(sessionRepository), sessionRepository); + return sessionRepository; } /// Получить репозиторий с лабораторными работами [NotNull] public ILabRepository GetLabRepository() { - Contract.Ensures(Contract.Result() != null); - - return new LabRepository(_context, _tasksContext); + var labRepository = new LabRepository(_context, _tasksContext); + Guard.IsNotNull(nameof(labRepository), labRepository); + return labRepository; } [NotNull] public ICategoryRepository GetCategoryRepository() { - Contract.Ensures(Contract.Result() != null); - - return new CategoryRepository(_context); + var categoryRepository = new CategoryRepository(_context); + Guard.IsNotNull(nameof(categoryRepository), categoryRepository); + return categoryRepository; } [NotNull] public ISurveyRepository GetSurveyRepository() { - Contract.Ensures(Contract.Result() != null); - - return new SurveyRepository(_context); + var surveyRepository = new SurveyRepository(_context); + Guard.IsNotNull(nameof(surveyRepository), surveyRepository); + return surveyRepository; } [NotNull] public ITestPoolRepository GetTestPoolRepository() { - Contract.Ensures(Contract.Result() != null); - - return new TestPoolRepository(_context); + var testPoolRepository = new TestPoolRepository(_context); + Guard.IsNotNull(nameof(testPoolRepository), testPoolRepository); + return testPoolRepository; } } } \ No newline at end of file diff --git a/GraphLabs.Dal.Ef/Repositories/SessionRepository.cs b/GraphLabs.Dal.Ef/Repositories/SessionRepository.cs index 57d6a7f..249dd2f 100644 --- a/GraphLabs.Dal.Ef/Repositories/SessionRepository.cs +++ b/GraphLabs.Dal.Ef/Repositories/SessionRepository.cs @@ -5,6 +5,7 @@ using GraphLabs.DomainModel; using GraphLabs.Dal.Ef.Services; using GraphLabs.DomainModel.Repositories; +using GraphLabs.Site.Utils; namespace GraphLabs.Dal.Ef.Repositories { @@ -34,14 +35,18 @@ public Session FindByGuid(Guid guid) /// Найти сессии по пользователю public Session[] FindByUser(User user) { + Guard.IsNotNull(user); CheckNotDisposed(); - - return Context.Sessions.Where(s => s.User.Id == user.Id).ToArray(); + var result = Context.Sessions.Where(s => s.User.Id == user.Id).ToArray(); + Guard.IsNotNull(result); + return result; } /// Создать сессию public Session Create(User user, string ip) { + Guard.IsNotNull(nameof(user), user); + Guard.IsTrueAssertion(IpHelper.CheckIsValidIP(ip)); CheckNotDisposed(); var now = _systemDateService.Now(); @@ -52,13 +57,15 @@ public Session Create(User user, string ip) session.CreationTime = now; session.LastAction = now; Context.Sessions.Add(session); - + Guard.IsNotNull(nameof(session), session); + return session; } /// Удалить сессию public void Remove(Session session) { + Guard.IsNotNull(nameof(session), session); CheckNotDisposed(); Context.Sessions.Remove(session); @@ -67,6 +74,7 @@ public void Remove(Session session) /// Удалить несколько сессий public void RemoveRange(IEnumerable sessions) { + Guard.IsNotNull(nameof(sessions), sessions); CheckNotDisposed(); Context.Sessions.RemoveRange(sessions); diff --git a/GraphLabs.Dal.Ef/Repositories/SurveyRepository.cs b/GraphLabs.Dal.Ef/Repositories/SurveyRepository.cs index 9661091..424a9cd 100644 --- a/GraphLabs.Dal.Ef/Repositories/SurveyRepository.cs +++ b/GraphLabs.Dal.Ef/Repositories/SurveyRepository.cs @@ -20,23 +20,27 @@ public SurveyRepository(GraphLabsContext context) public TestQuestion[] GetAllQuestions() { CheckNotDisposed(); - - return Context.TestQuestions.ToArray(); + var result = Context.TestQuestions.ToArray(); + Guard.IsNotNull(result); + return result; } /// Получить все вопросы в заданной категории public TestQuestion[] GetQuestionByCategory(long categoryId) { - CheckNotDisposed(); - - return Context.TestQuestions.Where(tq => tq.Category.Id == categoryId).ToArray(); + Guard.IsPositive(categoryId, nameof(categoryId)); + CheckNotDisposed(); + var result = Context.TestQuestions.Where(tq => tq.Category.Id == categoryId).ToArray(); + Guard.IsNotNull(result); + return result; } public TestQuestion[] GetQuestionsSimilarToString(string criteria) { CheckNotDisposed(); - - return Context.TestQuestions.Where(tq => tq.Question.StartsWith(criteria)).ToArray(); + var result = Context.TestQuestions.Where(tq => tq.Question.StartsWith(criteria)).ToArray(); + Guard.IsNotNull(result); + return result; } #endregion @@ -67,6 +71,7 @@ public void SaveQuestion(string question, Dictionary questionOptio /// Получить количество вопросов в категории с id == CategoryId public int GetCategorizesTestQuestionCount(long CategoryId) { + Guard.IsPositive(CategoryId, nameof(CategoryId)); CheckNotDisposed(); return Context.TestQuestions.Count(tq => tq.Category.Id == CategoryId); diff --git a/GraphLabs.Dal.Ef/Repositories/TestPoolRepository.cs b/GraphLabs.Dal.Ef/Repositories/TestPoolRepository.cs index 5f4c819..da55db2 100644 --- a/GraphLabs.Dal.Ef/Repositories/TestPoolRepository.cs +++ b/GraphLabs.Dal.Ef/Repositories/TestPoolRepository.cs @@ -15,6 +15,7 @@ public TestPoolRepository(GraphLabsContext context) public TestPool GetTestPoolById(long id) { + Guard.IsPositive(id, nameof(id)); CheckNotDisposed(); return Context.TestPools.SingleOrDefault(l => l.Id == id); } diff --git a/GraphLabs.Dal.Ef/Repositories/UserRepository.cs b/GraphLabs.Dal.Ef/Repositories/UserRepository.cs index 09e3909..70e2701 100644 --- a/GraphLabs.Dal.Ef/Repositories/UserRepository.cs +++ b/GraphLabs.Dal.Ef/Repositories/UserRepository.cs @@ -19,6 +19,7 @@ public UserRepository(GraphLabsContext context) /// т.е. подтверждённого, не отчисленного и не удалённого. public User FindActiveUserByEmail(string email) { + Guard.IsNotNullOrWhiteSpace(email); CheckNotDisposed(); return Context.Users.SingleOrDefault(u => u.Email == email && @@ -28,6 +29,11 @@ public User FindActiveUserByEmail(string email) /// Создать нового студента public Student CreateNotVerifiedStudent(string email, string name, string fatherName, string surname, string passwordHash, Group group) { + Guard.IsNotNullOrWhiteSpace(email); + Guard.IsNotNullOrWhiteSpace(name); + Guard.IsNotNullOrWhiteSpace(surname); + Guard.IsNotNullOrWhiteSpace(passwordHash); + Guard.IsTrueAssertion(group != null && group.IsOpen); CheckNotDisposed(); var student = Context.Users.Create(); @@ -42,6 +48,7 @@ public Student CreateNotVerifiedStudent(string email, string name, string father student.Group = group; Context.Users.Add(student); + Guard.IsNotNull(student); return student; } @@ -51,65 +58,72 @@ public Student CreateNotVerifiedStudent(string email, string name, string father public User[] GetAllUsers() { CheckNotDisposed(); - - return Context.Users.ToArray(); + + var result = Context.Users.ToArray(); + Guard.IsNotNull(result); + return result; } /// Получить массив пользователей-администраторов public User[] GetAdministrators() { CheckNotDisposed(); - - return Context.Users.Where(user => user.Role == UserRole.Administrator).ToArray(); + var result = Context.Users.Where(user => user.Role == UserRole.Administrator).ToArray(); + Guard.IsNotNull(result); + return result; } /// Получить массив пользователей-преподавателей public User[] GetTeachers() { CheckNotDisposed(); - - return Context.Users.Where(user => user.Role == UserRole.Teacher).ToArray(); + var result = Context.Users.Where(user => user.Role == UserRole.Teacher).ToArray(); + Guard.IsNotNull(result); + return result; } /// Получить массив исключенных студентов public Student[] GetDismissedStudents() { CheckNotDisposed(); - - return Context.Users - .Where(user => user.Role == UserRole.Student) - .ToArray() - .Select(user => (Student)user) - .Where(student => student.IsDismissed == true) - .ToArray(); + var result = Context.Users + .Where(user => user.Role == UserRole.Student) + .ToArray() + .Select(user => (Student)user) + .Where(student => student.IsDismissed == true) + .ToArray(); + Guard.IsNotNull(result); + return result; } /// Получить массив подтвержденных студентов public Student[] GetVerifiedStudents() { CheckNotDisposed(); - - return Context.Users - .Where(user => user.Role == UserRole.Student) - .ToArray() - .Select(user => (Student)user) - .Where(student => student.IsDismissed == false) - .Where(student => student.IsVerified == true) - .ToArray(); + var result = Context.Users + .Where(user => user.Role == UserRole.Student) + .ToArray() + .Select(user => (Student)user) + .Where(student => student.IsDismissed == false) + .Where(student => student.IsVerified == true) + .ToArray(); + Guard.IsNotNull(result); + return result; } /// Получить массив неподтвержденных студентов public Student[] GetUnverifiedStudents() { CheckNotDisposed(); - - return Context.Users - .Where(user => user.Role == UserRole.Student) - .ToArray() - .Select(user => (Student)user) - .Where(student => student.IsDismissed == false) - .Where(student => student.IsVerified == false) - .ToArray(); + var result = Context.Users + .Where(user => user.Role == UserRole.Student) + .ToArray() + .Select(user => (Student)user) + .Where(student => student.IsDismissed == false) + .Where(student => student.IsVerified == false) + .ToArray(); + Guard.IsNotNull(result); + return result; } #endregion @@ -117,7 +131,10 @@ public Student[] GetUnverifiedStudents() /// Получить пользователя по Id public User GetUserById(long Id) { - return Context.Users.Find(Id); + Guard.IsPositive(Id, nameof(Id)); + var result = Context.Users.Find(Id); + Guard.IsNotNull(result); + return result; } #region Сохранение и редактирование @@ -125,6 +142,7 @@ public User GetUserById(long Id) /// Попытка сохранить нового пользователя public bool TrySaveUser(User user) { + Guard.IsNotNull(nameof(user), user); CheckNotDisposed(); try @@ -143,7 +161,8 @@ public bool TrySaveUser(User user) /// Попытка изменить пользователя public bool TryEditUser(User user) { - CheckNotDisposed(); + Guard.IsNotNull(nameof(user), user); + CheckNotDisposed(); try { @@ -161,6 +180,7 @@ public bool TryEditUser(User user) /// Утвердить аккаунт студента public void VerifyStudent(long Id) { + Guard.IsPositive(Id, nameof(Id)); CheckNotDisposed(); var user = Context.Users.Find(Id); @@ -175,7 +195,8 @@ public void VerifyStudent(long Id) /// Исключить студента public void DismissStudent(long Id) { - CheckNotDisposed(); + Guard.IsPositive(Id, nameof(Id)); + CheckNotDisposed(); var user = Context.Users.Find(Id); if (user.Role != UserRole.Student) @@ -189,7 +210,8 @@ public void DismissStudent(long Id) /// Восстановить исключенного студента public void RestoreStudent(long Id) { - CheckNotDisposed(); + Guard.IsPositive(Id, nameof(Id)); + CheckNotDisposed(); var user = Context.Users.Find(Id); if (user.Role != UserRole.Student) diff --git a/GraphLabs.Dal.Ef/Services/SystemDateService.cs b/GraphLabs.Dal.Ef/Services/SystemDateService.cs index 1a380e1..2bfa6b3 100644 --- a/GraphLabs.Dal.Ef/Services/SystemDateService.cs +++ b/GraphLabs.Dal.Ef/Services/SystemDateService.cs @@ -27,7 +27,7 @@ public void SetDate(DateTime newDateTime) var currentDate = GetDate(); var newDate = newDateTime.Date; - Contract.Assume(newDate > currentDate, "Новая дата должна быть больше предыдущей."); + Guard.IsTrueAssertion("Новая дата должна быть больше предыдущей.", newDate > currentDate); var settings = _context.Settings.Single(); settings.SystemDate = newDate; diff --git a/GraphLabs.DomainModel/GraphLabs.DomainModel.csproj b/GraphLabs.DomainModel/GraphLabs.DomainModel.csproj index 57e75c8..17d8822 100644 --- a/GraphLabs.DomainModel/GraphLabs.DomainModel.csproj +++ b/GraphLabs.DomainModel/GraphLabs.DomainModel.csproj @@ -305,6 +305,10 @@ + + {d0a05aef-dc7e-4b2b-a82a-9a23eaa0af95} + GraphLabs.Guard + {d62cc3f4-3ea1-44ff-b9e2-492582788b3b} GraphLabs.Site.Core diff --git a/GraphLabs.DomainModel/Infrastructure/AbstractEntity.cs b/GraphLabs.DomainModel/Infrastructure/AbstractEntity.cs index 620cd77..6f95d02 100644 --- a/GraphLabs.DomainModel/Infrastructure/AbstractEntity.cs +++ b/GraphLabs.DomainModel/Infrastructure/AbstractEntity.cs @@ -14,13 +14,16 @@ public virtual void OnInsert() /// Перед сохранением изменённой сущности в базу public virtual void OnChange(IEntityChange change) { + Guard.IsNotNull(nameof(change), change); } /// Валидация /// Для переопределения валидации конеретных сущностей перекрывайте OnEntityValidating public IEnumerable OnValidating() { - return OnEntityValidating(); + var result = OnEntityValidating(); + Guard.IsNotNull(nameof(result), result); + return result; } /// Валидация diff --git a/GraphLabs.DomainModel/Infrastructure/IEntityChange.cs b/GraphLabs.DomainModel/Infrastructure/IEntityChange.cs index ad6e1f4..7c006fc 100644 --- a/GraphLabs.DomainModel/Infrastructure/IEntityChange.cs +++ b/GraphLabs.DomainModel/Infrastructure/IEntityChange.cs @@ -5,7 +5,7 @@ namespace GraphLabs.DomainModel.Infrastructure { /// Интерфейс, описывающий изменение сущности - [ContractClass(typeof(EntityChangeContracts))] + //[ContractClass(typeof(EntityChangeContracts))] public interface IEntityChange { /// Изменилось ли свойство? @@ -17,36 +17,38 @@ public interface IEntityChange /// Текущие значения свойств IReadOnlyDictionary CurrentValues { get; } } +} /// Контракты для - [ContractClassFor(typeof(IEntityChange))] - abstract class EntityChangeContracts : IEntityChange - { - /// Изменилось ли свойство? - public bool PropertyChanged(string propertyName) - { - Contract.Requires(string.IsNullOrWhiteSpace(propertyName)); - return default(bool); - } +// [ContractClassFor(typeof(IEntityChange))] +// abstract class EntityChangeContracts : IEntityChange +// { +// /// Изменилось ли свойство? +// public bool PropertyChanged(string propertyName) +// { +// Contract.Requires(string.IsNullOrWhiteSpace(propertyName)); +// Guard.IsNotNullOrWhiteSpace(propertyName); +// return default(bool); +// } - /// Исходные значения свойств - public IReadOnlyDictionary OriginalValues - { - get - { - Contract.Ensures(Contract.Result>() != null); - return default(IReadOnlyDictionary); - } - } +// /// Исходные значения свойств +// public IReadOnlyDictionary OriginalValues +// { +// get +// { +// Contract.Ensures(Contract.Result>() != null);//переписать сразу у наследников +// return default(IReadOnlyDictionary); +// } +// } - /// Текущие значения свойств - public IReadOnlyDictionary CurrentValues - { - get - { - Contract.Ensures(Contract.Result>() != null); - return default(IReadOnlyDictionary); - } - } - } -} \ No newline at end of file +// /// Текущие значения свойств +// public IReadOnlyDictionary CurrentValues +// { +// get +// { +// Contract.Ensures(Contract.Result>() != null);// у наследников +// return default(IReadOnlyDictionary); +// } +// } +// } +//} \ No newline at end of file diff --git a/GraphLabs.DomainModel/Infrastructure/IEntitySet.cs b/GraphLabs.DomainModel/Infrastructure/IEntitySet.cs index b539f42..af3b47e 100644 --- a/GraphLabs.DomainModel/Infrastructure/IEntitySet.cs +++ b/GraphLabs.DomainModel/Infrastructure/IEntitySet.cs @@ -34,47 +34,48 @@ public interface IEntitySet } /// Контракты - [ContractClassFor(typeof(IEntitySet<>))] - abstract class EntitySetContracts : IEntitySet where TEntity : AbstractEntity - { - /// Поиск необходимых сущностей - public IQueryable Query - { - get - { - Contract.Ensures(Contract.Result>() != null); - return default(IQueryable); - } - } + //[ContractClassFor(typeof(IEntitySet<>))] + //abstract class EntitySetContracts : IEntitySet where TEntity : AbstractEntity + //{ + // /// Поиск необходимых сущностей + // public IQueryable Query + // { + // get + // { + // return default(IQueryable); + // } + // } - /// Ищет сущность по ключу - /// Не удалось найти сущность с заданным ключом - public TEntity Get(params object[] keyValues) - { - Contract.Requires(keyValues.Length > 0); - Contract.Ensures(Contract.Result() != null); - return default(TEntity); - } + // /// Ищет сущность по ключу + // /// Не удалось найти сущность с заданным ключом + // public TEntity Get(params object[] keyValues) + // { + // Contract.Requires(keyValues.Length > 0); + // Guard.IsPositive(keyValues.Length, "keyValue"); + // Contract.Ensures(Contract.Result() != null); + // return default(TEntity); + // } - /// Создаёт новый экземпляр сущности - public TDerivedEntity CreateNew() where TDerivedEntity : TEntity - { - Contract.Ensures(Contract.Result() != null); - return default(TDerivedEntity); - } + // /// Создаёт новый экземпляр сущности + // public TDerivedEntity CreateNew() where TDerivedEntity : TEntity + // { + // Contract.Ensures(Contract.Result() != null); + // return default(TDerivedEntity); + // } - /// Создаёт новый экземпляр сущности - public TEntity CreateNew() - { - Contract.Ensures(Contract.Result() != null); - return default(TEntity); - } + // /// Создаёт новый экземпляр сущности + // public TEntity CreateNew() + // { + // Contract.Ensures(Contract.Result() != null); + // return default(TEntity); + // } - /// Ищет сущность по ключу - public TEntity Find(params object[] keyValue) - { - Contract.Requires(keyValue.Length > 0); - return default(TEntity); - } - } + // /// Ищет сущность по ключу + // public TEntity Find(params object[] keyValue) + // { + // Contract.Requires(keyValue.Length > 0); + // Guard.IsPositive(keyValue.Length, "keyValue"); + // return default(TEntity); + // } + //} } diff --git a/GraphLabs.DomainModel/Infrastructure/ITrackableEntity.cs b/GraphLabs.DomainModel/Infrastructure/ITrackableEntity.cs index 63099b1..349c315 100644 --- a/GraphLabs.DomainModel/Infrastructure/ITrackableEntity.cs +++ b/GraphLabs.DomainModel/Infrastructure/ITrackableEntity.cs @@ -6,7 +6,7 @@ namespace GraphLabs.DomainModel.Infrastructure { /// Отслеживаемые сущности - [ContractClass(typeof(TrackableEntityContracts))] + // [ContractClass(typeof(TrackableEntityContracts))] public interface ITrackableEntity { /// Перед сохранением новой сущности в базу @@ -20,25 +20,25 @@ public interface ITrackableEntity } /// Контракты для - [ContractClassFor(typeof(ITrackableEntity))] - abstract class TrackableEntityContracts : ITrackableEntity - { - /// Перед сохранением новой сущности в базу - public void OnInsert() - { - } + //[ContractClassFor(typeof(ITrackableEntity))] + //abstract class TrackableEntityContracts : ITrackableEntity + //{ + // /// Перед сохранением новой сущности в базу + // public void OnInsert() + // { + // } - /// Перед сохранением изменённой сущности в базу - public void OnChange(IEntityChange change) - { - Contract.Requires(change != null); - } + // /// Перед сохранением изменённой сущности в базу + // public void OnChange(IEntityChange change) + // { + // Contract.Requires(change != null); + // } - /// Валидация - public IEnumerable OnValidating() - { - Contract.Ensures(Contract.Result>() != null); - return default(IEnumerable); - } - } + // /// Валидация + // public IEnumerable OnValidating() + // { + // Contract.Ensures(Contract.Result>() != null); + // return default(IEnumerable); + // } + //} } \ No newline at end of file diff --git a/GraphLabs.DomainModel/Repositories/ICategoryRepository.cs b/GraphLabs.DomainModel/Repositories/ICategoryRepository.cs index d1baab8..a16ff04 100644 --- a/GraphLabs.DomainModel/Repositories/ICategoryRepository.cs +++ b/GraphLabs.DomainModel/Repositories/ICategoryRepository.cs @@ -4,7 +4,7 @@ namespace GraphLabs.DomainModel.Repositories { /// Репозиторий с группами - [ContractClass(typeof(CategoryRepositoryContracts))] + //[ContractClass(typeof(CategoryRepositoryContracts))] [Obsolete("Использовать глобальный контекст IGraphLabsContext")] public interface ICategoryRepository : IDisposable { @@ -22,37 +22,37 @@ public interface ICategoryRepository : IDisposable } /// Репозиторий с группами - [ContractClassFor(typeof(ICategoryRepository))] - internal abstract class CategoryRepositoryContracts : ICategoryRepository - { - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - public void Dispose() - { - } - - public Category GetById(long id) - { - Contract.Requires(id > 0); - Contract.Ensures(Contract.Result() != null); - - return default(Category); - } - - public Category[] GetAllCategories() - { - Contract.Ensures(Contract.Result() != null); - - return new Category[0]; - } - - public void SaveCategory(Category category) - { - Contract.Requires(category != null); - } - - public void EditCategory(Category category) - { - Contract.Requires(category != null); - } - } + //[ContractClassFor(typeof(ICategoryRepository))] + //internal abstract class CategoryRepositoryContracts : ICategoryRepository + //{ + // /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + // public void Dispose() + // { + // } + + // public Category GetById(long id) + // { + // Contract.Requires(id > 0); + // Contract.Ensures(Contract.Result() != null); + + // return default(Category); + // } + + // public Category[] GetAllCategories() + // { + // Contract.Ensures(Contract.Result() != null); + + // return new Category[0]; + // } + + // public void SaveCategory(Category category) + // { + // Contract.Requires(category != null); + // } + + // public void EditCategory(Category category) + // { + // Contract.Requires(category != null); + // } + //} } diff --git a/GraphLabs.DomainModel/Repositories/IGroupsRepository.cs b/GraphLabs.DomainModel/Repositories/IGroupsRepository.cs index b937a82..bfb0d0c 100644 --- a/GraphLabs.DomainModel/Repositories/IGroupsRepository.cs +++ b/GraphLabs.DomainModel/Repositories/IGroupsRepository.cs @@ -5,7 +5,7 @@ namespace GraphLabs.DomainModel.Repositories { /// Репозиторий с группами - [ContractClass(typeof(GroupRepositoryContracts))] + // [ContractClass(typeof(GroupRepositoryContracts))] [Obsolete("Использовать глобальный контекст IGraphLabsContext")] public interface IGroupRepository : IDisposable { @@ -25,39 +25,39 @@ public interface IGroupRepository : IDisposable } /// Репозиторий с группами - [ContractClassFor(typeof(IGroupRepository))] - internal abstract class GroupRepositoryContracts : IGroupRepository - { - // ReSharper disable AssignNullToNotNullAttribute - - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - public void Dispose() - { - } - - /// Репозиторий с группами - public Group[] GetAllGroups() - { - Contract.Ensures(Contract.Result() != null); - - return new Group[0]; - } - - /// Репозиторий с группами - public Group[] GetOpenGroups() - { - Contract.Ensures(Contract.Result() != null); - - return new Group[0]; - } - - /// Репозиторий с группами - public Group GetGroupById(long id) - { - Contract.Requires(id > 0); - Contract.Ensures(Contract.Result() != null); - - return default(Group); - } - } + //[ContractClassFor(typeof(IGroupRepository))] + //internal abstract class GroupRepositoryContracts : IGroupRepository + //{ + // // ReSharper disable AssignNullToNotNullAttribute + + // /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + // public void Dispose() + // { + // } + + // /// Репозиторий с группами + // public Group[] GetAllGroups() + // { + // Contract.Ensures(Contract.Result() != null); + + // return new Group[0]; + // } + + // /// Репозиторий с группами + // public Group[] GetOpenGroups() + // { + // Contract.Ensures(Contract.Result() != null); + + // return new Group[0]; + // } + + // /// Репозиторий с группами + // public Group GetGroupById(long id) + // { + // Contract.Requires(id > 0); + // Contract.Ensures(Contract.Result() != null); + + // return default(Group); + // } + //} } diff --git a/GraphLabs.DomainModel/Repositories/ILabRepository.cs b/GraphLabs.DomainModel/Repositories/ILabRepository.cs index b78f0c5..b1b2f8e 100644 --- a/GraphLabs.DomainModel/Repositories/ILabRepository.cs +++ b/GraphLabs.DomainModel/Repositories/ILabRepository.cs @@ -5,7 +5,7 @@ namespace GraphLabs.DomainModel.Repositories { /// Репозиторий с лабораторными работами - [ContractClass(typeof(LabRepositoryContracts))] + // [ContractClass(typeof(LabRepositoryContracts))] [Obsolete("Использовать глобальный контекст IGraphLabsContext")] public interface ILabRepository : IDisposable { @@ -120,205 +120,205 @@ public interface ILabRepository : IDisposable #endregion } - /// Репозиторий с лаораторными работами - контракты - [ContractClassFor(typeof(ILabRepository))] - internal abstract class LabRepositoryContracts : ILabRepository - { - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - public void Dispose() - { - } + // /// Репозиторий с лаораторными работами - контракты + // [ContractClassFor(typeof(ILabRepository))] + // internal abstract class LabRepositoryContracts : ILabRepository + // { + // /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + // public void Dispose() + // { + // } - #region Получение массива лабораторных работ + // #region Получение массива лабораторных работ - public LabWork[] GetLabWorks() - { - Contract.Ensures(Contract.Result() != null); + // public LabWork[] GetLabWorks() + // { + // Contract.Ensures(Contract.Result() != null); - return new LabWork[0]; - } + // return new LabWork[0]; + // } - public LabWork[] GetDemoLabs(DateTime currentDate) - { - Contract.Requires(currentDate != null); - Contract.Ensures(Contract.Result() != null); + // public LabWork[] GetDemoLabs(DateTime currentDate) + // { + // Contract.Requires(currentDate != null); + // Contract.Ensures(Contract.Result() != null); - return new LabWork[0]; - } + // return new LabWork[0]; + // } - #endregion + // #endregion - #region Получение массива вариантов лабораторной работы + // #region Получение массива вариантов лабораторной работы - public LabVariant[] GetLabVariantsByLabWorkId(long id) - { - Contract.Requires(id > 0); - Contract.Ensures(Contract.Result() != null); + // public LabVariant[] GetLabVariantsByLabWorkId(long id) + // { + // Contract.Requires(id > 0); + // Contract.Ensures(Contract.Result() != null); - return new LabVariant[0]; - } + // return new LabVariant[0]; + // } - public LabVariant[] GetDemoLabVariantsByLabWorkId(long labId) - { - Contract.Requires(labId > 0); - Contract.Ensures(Contract.Result() != null); + // public LabVariant[] GetDemoLabVariantsByLabWorkId(long labId) + // { + // Contract.Requires(labId > 0); + // Contract.Ensures(Contract.Result() != null); - return new LabVariant[0]; - } + // return new LabVariant[0]; + // } - public LabVariant[] GetCompleteDemoLabVariantsByLabWorkId(long labId) - { - Contract.Requires(labId > 0); - Contract.Ensures(Contract.Result() != null); + // public LabVariant[] GetCompleteDemoLabVariantsByLabWorkId(long labId) + // { + // Contract.Requires(labId > 0); + // Contract.Ensures(Contract.Result() != null); - return new LabVariant[0]; - } + // return new LabVariant[0]; + // } - #endregion + // #endregion - #region Проверки + // #region Проверки - public bool CheckLabWorkExist(long id) - { - Contract.Requires(id > 0); + // public bool CheckLabWorkExist(long id) + // { + // Contract.Requires(id > 0); - return false; - } + // return false; + // } - public bool CheckLabWorkExist(string name) - { - Contract.Requires(name != ""); + // public bool CheckLabWorkExist(string name) + // { + // Contract.Requires(name != ""); - return false; - } + // return false; + // } - public bool CheckLabVariantExist(long id) - { - Contract.Requires(id > 0); + // public bool CheckLabVariantExist(long id) + // { + // Contract.Requires(id > 0); - return false; - } + // return false; + // } - public bool CheckLabVariantExist(long labId, string name) - { - Contract.Requires(labId > 0); - Contract.Requires(name != ""); + // public bool CheckLabVariantExist(long labId, string name) + // { + // Contract.Requires(labId > 0); + // Contract.Requires(name != ""); - return false; - } + // return false; + // } - public bool CheckLabVariantBelongLabWork(long labId, long labVarId) - { - Contract.Requires(labId > 0); - Contract.Requires(labVarId > 0); + // public bool CheckLabVariantBelongLabWork(long labId, long labVarId) + // { + // Contract.Requires(labId > 0); + // Contract.Requires(labVarId > 0); - return false; - } + // return false; + // } - public bool VerifyCompleteVariant(long variantId) - { - Contract.Requires(variantId > 0); + // public bool VerifyCompleteVariant(long variantId) + // { + // Contract.Requires(variantId > 0); - return false; - } + // return false; + // } - #endregion + // #endregion - #region Получение разнородной информации по id + // #region Получение разнородной информации по id - public LabWork GetLabWorkById(long id) - { - Contract.Requires(id > 0); - Contract.Ensures(Contract.Result() != null); + // public LabWork GetLabWorkById(long id) + // { + // Contract.Requires(id > 0); + // Contract.Ensures(Contract.Result() != null); - return default(LabWork); - } + // return default(LabWork); + // } - public LabVariant GetLabVariantById(long id) - { - Contract.Requires(id > 0); - Contract.Ensures(Contract.Result() != null); + // public LabVariant GetLabVariantById(long id) + // { + // Contract.Requires(id > 0); + // Contract.Ensures(Contract.Result() != null); - return default(LabVariant); - } + // return default(LabVariant); + // } - public LabVariant FindLabVariantById(long id) - { - Contract.Requires(id > 0); + // public LabVariant FindLabVariantById(long id) + // { + // Contract.Requires(id > 0); - return default(LabVariant); - } + // return default(LabVariant); + // } - public TaskVariant[] GetTaskVariantsByLabVarId(long labVarId) - { - Contract.Requires(labVarId > 0); - Contract.Ensures(Contract.Result() != null); + // public TaskVariant[] GetTaskVariantsByLabVarId(long labVarId) + // { + // Contract.Requires(labVarId > 0); + // Contract.Ensures(Contract.Result() != null); - return new TaskVariant[0]; - } + // return new TaskVariant[0]; + // } - #endregion + // #endregion - #region Изменение в БД + // #region Изменение в БД - public void DeleteEntries(long labWorkId) - { - Contract.Requires(labWorkId > 0); - } - - public void SaveLabWork(LabWork lab) - { - Contract.Requires(lab != null); - } - - public void ModifyLabWork(LabWork lab) - { - Contract.Requires(lab != null); - Contract.Requires(lab.Id > 0); - } - - public void SaveLabEntries(long labWorkId, long[] tasksId) - { - Contract.Requires(labWorkId > 0); - Contract.Requires(tasksId != null); - } - - public void DeleteExcessTaskVariantsFromLabVariants(long labWorkId) - { - Contract.Requires(labWorkId > 0); - } - - public void SaveLabVariant(LabVariant labVar) - { - Contract.Requires(labVar != null); - } - - public void ModifyLabVariant(LabVariant labVar) - { - Contract.Requires(labVar != null); - } + // public void DeleteEntries(long labWorkId) + // { + // Contract.Requires(labWorkId > 0); + // } - #endregion + // public void SaveLabWork(LabWork lab) + // { + // Contract.Requires(lab != null); + // } - #region Получение Id экземпляров + // public void ModifyLabWork(LabWork lab) + // { + // Contract.Requires(lab != null); + // Contract.Requires(lab.Id > 0); + // } - public long GetLabWorkIdByName(string name) - { - Contract.Requires(name != ""); - Contract.Ensures(Contract.Result() != 0); + // public void SaveLabEntries(long labWorkId, long[] tasksId) + // { + // Contract.Requires(labWorkId > 0); + // Contract.Requires(tasksId != null); + // } - return 0; - } + // public void DeleteExcessTaskVariantsFromLabVariants(long labWorkId) + // { + // Contract.Requires(labWorkId > 0); + // } - public long GetLabVariantIdByNumber(long labId, string number) - { - Contract.Requires(labId > 0); - Contract.Requires(number != ""); - Contract.Ensures(Contract.Result() != 0); + // public void SaveLabVariant(LabVariant labVar) + // { + // Contract.Requires(labVar != null); + // } - return 0; - } + // public void ModifyLabVariant(LabVariant labVar) + // { + // Contract.Requires(labVar != null); + // } - #endregion - } + // #endregion + + // #region Получение Id экземпляров + + // public long GetLabWorkIdByName(string name) + // { + // Contract.Requires(name != ""); + // Contract.Ensures(Contract.Result() != 0); + + // return 0; + // } + + // public long GetLabVariantIdByNumber(long labId, string number) + // { + // Contract.Requires(labId > 0); + // Contract.Requires(number != ""); + // Contract.Ensures(Contract.Result() != 0); + + // return 0; + // } + + // #endregion + //} } diff --git a/GraphLabs.DomainModel/Repositories/IResultsRepository.cs b/GraphLabs.DomainModel/Repositories/IResultsRepository.cs index bd95312..3dfc5cd 100644 --- a/GraphLabs.DomainModel/Repositories/IResultsRepository.cs +++ b/GraphLabs.DomainModel/Repositories/IResultsRepository.cs @@ -5,7 +5,7 @@ namespace GraphLabs.DomainModel.Repositories { /// Репозиторий результатов - [ContractClass(typeof(ResultsRepositoryContracts))] + // [ContractClass(typeof(ResultsRepositoryContracts))] [Obsolete("Использовать глобальный контекст IGraphLabsContext")] public interface IResultsRepository { @@ -18,24 +18,24 @@ public interface IResultsRepository } /// Репозиторий результатов - контракты - [ContractClassFor(typeof(IResultsRepository))] - internal abstract class ResultsRepositoryContracts : IResultsRepository - { - // ReSharper disable AssignNullToNotNullAttribute + //[ContractClassFor(typeof(IResultsRepository))] + //internal abstract class ResultsRepositoryContracts : IResultsRepository + //{ + // // ReSharper disable AssignNullToNotNullAttribute - /// Записать результат в БД - public void Insert(Result result) - { - Contract.Requires(result != null); - } + // /// Записать результат в БД + // public void Insert(Result result) + // { + // Contract.Requires(result != null); + // } - /// Найти неоконченные результаты выполнения - public Result[] FindNotFinishedResults(Student student) - { - Contract.Requires(student != null); - Contract.Ensures(Contract.Result() != null); + // /// Найти неоконченные результаты выполнения + // public Result[] FindNotFinishedResults(Student student) + // { + // Contract.Requires(student != null); + // Contract.Ensures(Contract.Result() != null); - return default(Result[]); - } - } + // return default(Result[]); + // } + //} } \ No newline at end of file diff --git a/GraphLabs.DomainModel/Repositories/ISessionRepository.cs b/GraphLabs.DomainModel/Repositories/ISessionRepository.cs index fc3c2d1..c839c82 100644 --- a/GraphLabs.DomainModel/Repositories/ISessionRepository.cs +++ b/GraphLabs.DomainModel/Repositories/ISessionRepository.cs @@ -7,7 +7,7 @@ namespace GraphLabs.DomainModel.Repositories { /// Репозиторий с сессиями - [ContractClass(typeof(SessionRepositoryContracts))] + //[ContractClass(typeof(SessionRepositoryContracts))] [Obsolete("Использовать глобальный контекст IGraphLabsContext")] public interface ISessionRepository { @@ -30,48 +30,48 @@ public interface ISessionRepository void RemoveRange(IEnumerable sessions); } - /// Репозиторий с сессиями - контракты - [ContractClassFor(typeof(ISessionRepository))] - internal abstract class SessionRepositoryContracts : ISessionRepository - { - // ReSharper disable AssignNullToNotNullAttribute + ///// Репозиторий с сессиями - контракты + //[ContractClassFor(typeof(ISessionRepository))] + //internal abstract class SessionRepositoryContracts : ISessionRepository + //{ + // // ReSharper disable AssignNullToNotNullAttribute - /// Найти сессию по идентификатору - public Session FindByGuid(Guid guid) - { - return default(Session); - } + // /// Найти сессию по идентификатору + // public Session FindByGuid(Guid guid) + // { + // return default(Session); + // } - /// Найти сессии по пользователю - public Session[] FindByUser(User user) - { - Contract.Requires(user != null); - Contract.Ensures(Contract.Result() != null); + // /// Найти сессии по пользователю + // public Session[] FindByUser(User user) + // { + // Contract.Requires(user != null); + // Contract.Ensures(Contract.Result() != null); - return default(Session[]); - } + // return default(Session[]); + // } - /// Создать сессию - public Session Create(User user, string ip) - { - Contract.Requires(user != null); - Contract.Requires(IpHelper.CheckIsValidIP(ip)); + // /// Создать сессию + // public Session Create(User user, string ip) + // { + // Contract.Requires(user != null); + // Contract.Requires(IpHelper.CheckIsValidIP(ip)); - Contract.Ensures(Contract.Result() != null); + // Contract.Ensures(Contract.Result() != null); - return default(Session); - } + // return default(Session); + // } - /// Удалить сессию - public void Remove(Session session) - { - Contract.Requires(session != null); - } + // /// Удалить сессию + // public void Remove(Session session) + // { + // Contract.Requires(session != null); + // } - /// Удалить несколько сессий - public void RemoveRange(IEnumerable sessions) - { - Contract.Requires(sessions != null); - } - } + // /// Удалить несколько сессий + // public void RemoveRange(IEnumerable sessions) + // { + // Contract.Requires(sessions != null); + // } + //} } \ No newline at end of file diff --git a/GraphLabs.DomainModel/Repositories/ISurveyRepository.cs b/GraphLabs.DomainModel/Repositories/ISurveyRepository.cs index b553eb8..dcfe788 100644 --- a/GraphLabs.DomainModel/Repositories/ISurveyRepository.cs +++ b/GraphLabs.DomainModel/Repositories/ISurveyRepository.cs @@ -6,7 +6,7 @@ namespace GraphLabs.DomainModel.Repositories { /// Репозиторий с вопросами - [ContractClass(typeof(SurveyRepositoryContracts))] + //[ContractClass(typeof(SurveyRepositoryContracts))] [Obsolete("Использовать глобальный контекст IGraphLabsContext")] public interface ISurveyRepository : IDisposable { @@ -35,50 +35,50 @@ public interface ISurveyRepository : IDisposable } - /// Репозиторий с вопросами - [ContractClassFor(typeof(ISurveyRepository))] - internal abstract class SurveyRepositoryContracts : ISurveyRepository - { - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - public void Dispose() - { - } + // /// Репозиторий с вопросами + //[ContractClassFor(typeof(ISurveyRepository))] + // internal abstract class SurveyRepositoryContracts : ISurveyRepository + //{ + // /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + // public void Dispose() + // { + // } - #region Получение массивов вопросов + // #region Получение массивов вопросов - public TestQuestion[] GetAllQuestions() - { - Contract.Ensures(Contract.Result() != null); + // public TestQuestion[] GetAllQuestions() + // { + // Contract.Ensures(Contract.Result() != null); - return new TestQuestion[0]; - } + // return new TestQuestion[0]; + // } - public TestQuestion[] GetQuestionByCategory(long CategoryId) - { - Contract.Requires(CategoryId > 0); - Contract.Ensures(Contract.Result() != null); + // public TestQuestion[] GetQuestionByCategory(long CategoryId) + // { + // Contract.Requires(CategoryId > 0); + // Contract.Ensures(Contract.Result() != null); - return new TestQuestion[0]; - } + // return new TestQuestion[0]; + // } - public TestQuestion[] GetQuestionsSimilarToString(string criteria) - { - Contract.Ensures(Contract.Result() != null); - return new TestQuestion[0]; - } + // public TestQuestion[] GetQuestionsSimilarToString(string criteria) + // { + // Contract.Ensures(Contract.Result() != null); + // return new TestQuestion[0]; + // } - #endregion + // #endregion - public void SaveQuestion(string question, Dictionary questionOptions, long categoryId) - { + // public void SaveQuestion(string question, Dictionary questionOptions, long categoryId) + // { - } + // } - public int GetCategorizesTestQuestionCount(long CategoryId) - { - Contract.Requires(CategoryId > 0); + // public int GetCategorizesTestQuestionCount(long CategoryId) + // { + // Contract.Requires(CategoryId > 0); - return default(int); - } - } + // return default(int); + // } + //} } diff --git a/GraphLabs.DomainModel/Repositories/ITestPoolRepository.cs b/GraphLabs.DomainModel/Repositories/ITestPoolRepository.cs index 3fadab3..6f323c0 100644 --- a/GraphLabs.DomainModel/Repositories/ITestPoolRepository.cs +++ b/GraphLabs.DomainModel/Repositories/ITestPoolRepository.cs @@ -5,7 +5,7 @@ namespace GraphLabs.DomainModel.Repositories { /// Репозиторий с тестпулами - [ContractClass(typeof(TestPoolRepositoryContracts))] + //[ContractClass(typeof(TestPoolRepositoryContracts))] [Obsolete("Использовать глобальный контекст IGraphLabsContext")] public interface ITestPoolRepository : IDisposable { @@ -14,20 +14,20 @@ public interface ITestPoolRepository : IDisposable TestPool GetTestPoolById(long id); } - /// Репозиторий с тестпулами - [ContractClassFor(typeof(ITestPoolRepository))] - internal abstract class TestPoolRepositoryContracts : ITestPoolRepository - { - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - public void Dispose() - { - } + ///// Репозиторий с тестпулами + //[ContractClassFor(typeof(ITestPoolRepository))] + //internal abstract class TestPoolRepositoryContracts : ITestPoolRepository + //{ + // /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + // public void Dispose() + // { + // } - public TestPool GetTestPoolById(long id) - { - Contract.Requires(id > 0); - return default(TestPool); - } + // public TestPool GetTestPoolById(long id) + // { + // Contract.Requires(id > 0); + // return default(TestPool); + // } - } + //} } \ No newline at end of file diff --git a/GraphLabs.DomainModel/Repositories/IUserRepository.cs b/GraphLabs.DomainModel/Repositories/IUserRepository.cs index 7a1062a..603c31e 100644 --- a/GraphLabs.DomainModel/Repositories/IUserRepository.cs +++ b/GraphLabs.DomainModel/Repositories/IUserRepository.cs @@ -5,7 +5,7 @@ namespace GraphLabs.DomainModel.Repositories { /// Репозиторий с пользователями - [ContractClass(typeof(UserRepositoryContracts))] + // [ContractClass(typeof(UserRepositoryContracts))] [Obsolete("Использовать глобальный контекст IGraphLabsContext")] public interface IUserRepository : IDisposable { @@ -65,124 +65,124 @@ public interface IUserRepository : IDisposable #region Контракты - /// Репозиторий с пользователями - контракты - [ContractClassFor(typeof(IUserRepository))] - internal abstract class UserRepositoryContracts : IUserRepository - { - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - public void Dispose() - { - } + ///// Репозиторий с пользователями - контракты + // [ContractClassFor(typeof(IUserRepository))] + // internal abstract class UserRepositoryContracts : IUserRepository + // { + // /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + // public void Dispose() + // { + // } - public User FindActiveUserByEmail(string email) - { - Contract.Requires(!string.IsNullOrWhiteSpace(email)); + // public User FindActiveUserByEmail(string email) + // { + // Contract.Requires(!string.IsNullOrWhiteSpace(email)); - return default(User); - } + // return default(User); + // } - public Student CreateNotVerifiedStudent(string email, string name, string fatherName, string surname, string passwordHash, Group group) - { - Contract.Requires(!string.IsNullOrWhiteSpace(email)); - Contract.Requires(!string.IsNullOrWhiteSpace(name)); - Contract.Requires(!string.IsNullOrWhiteSpace(surname)); - Contract.Requires(!string.IsNullOrWhiteSpace(passwordHash)); - Contract.Requires(group != null && group.IsOpen); + // public Student CreateNotVerifiedStudent(string email, string name, string fatherName, string surname, string passwordHash, Group group) + // { + // Contract.Requires(!string.IsNullOrWhiteSpace(email)); + // Contract.Requires(!string.IsNullOrWhiteSpace(name)); + // Contract.Requires(!string.IsNullOrWhiteSpace(surname)); + // Contract.Requires(!string.IsNullOrWhiteSpace(passwordHash)); + // Contract.Requires(group != null && group.IsOpen); - Contract.Ensures(Contract.Result() != null); + // Contract.Ensures(Contract.Result() != null); - return null; - } + // return null; + // } - #region Получение массивов пользователей + // #region Получение массивов пользователей - public User[] GetAllUsers() - { - Contract.Ensures(Contract.Result() != null); + // public User[] GetAllUsers() + // { + // Contract.Ensures(Contract.Result() != null); - return new User[0]; - } + // return new User[0]; + // } - public User[] GetAdministrators() - { - Contract.Ensures(Contract.Result() != null); + // public User[] GetAdministrators() + // { + // Contract.Ensures(Contract.Result() != null); - return new User[0]; - } + // return new User[0]; + // } - public User[] GetTeachers() - { - Contract.Ensures(Contract.Result() != null); + // public User[] GetTeachers() + // { + // Contract.Ensures(Contract.Result() != null); - return new User[0]; - } + // return new User[0]; + // } - public Student[] GetDismissedStudents() - { - Contract.Ensures(Contract.Result() != null); + // public Student[] GetDismissedStudents() + // { + // Contract.Ensures(Contract.Result() != null); - return new Student[0]; - } + // return new Student[0]; + // } - public Student[] GetVerifiedStudents() - { - Contract.Ensures(Contract.Result() != null); + // public Student[] GetVerifiedStudents() + // { + // Contract.Ensures(Contract.Result() != null); - return new Student[0]; - } + // return new Student[0]; + // } - public Student[] GetUnverifiedStudents() - { - Contract.Ensures(Contract.Result() != null); + // public Student[] GetUnverifiedStudents() + // { + // Contract.Ensures(Contract.Result() != null); - return new Student[0]; - } + // return new Student[0]; + // } - #endregion + // #endregion - public User GetUserById(long Id) - { - Contract.Requires(Id > 0); - Contract.Ensures(Contract.Result() != null); + // public User GetUserById(long Id) + // { + // Contract.Requires(Id > 0); + // Contract.Ensures(Contract.Result() != null); - return default(User); - } + // return default(User); + // } - #region Сохранение и редактирование + // #region Сохранение и редактирование - public bool TrySaveUser(User user) - { - Contract.Requires(user != null); - - return false; - } - - public bool TryEditUser(User user) - { - Contract.Requires(user != null); - return false; - } - - public void VerifyStudent(long Id) - { - Contract.Requires(Id > 0); - return; - } - - public void DismissStudent(long Id) - { - Contract.Requires(Id > 0); - return; - } - - public void RestoreStudent(long Id) - { - Contract.Requires(Id > 0); - return; - } + // public bool TrySaveUser(User user) + // { + // Contract.Requires(user != null); - #endregion - } + // return false; + // } + + // public bool TryEditUser(User user) + // { + // Contract.Requires(user != null); + // return false; + // } + + // public void VerifyStudent(long Id) + // { + // Contract.Requires(Id > 0); + // return; + // } + + // public void DismissStudent(long Id) + // { + // Contract.Requires(Id > 0); + // return; + // } + + // public void RestoreStudent(long Id) + // { + // Contract.Requires(Id > 0); + // return; + // } + + // #endregion + //} #endregion } diff --git a/GraphLabs.Guard/ClassDiagram2.cd b/GraphLabs.Guard/ClassDiagram2.cd new file mode 100644 index 0000000..7b89419 --- /dev/null +++ b/GraphLabs.Guard/ClassDiagram2.cd @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/GraphLabs.Guard/GraphLabs.Guard.csproj b/GraphLabs.Guard/GraphLabs.Guard.csproj new file mode 100644 index 0000000..f829f75 --- /dev/null +++ b/GraphLabs.Guard/GraphLabs.Guard.csproj @@ -0,0 +1,412 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Debug + AnyCPU + {D0A05AEF-DC7E-4B2B-A82A-9A23EAA0AF95} + Library + Properties + GraphLabs + GraphLabs.Guard + v4.5.2 + 512 + + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\Antlr2.Runtime.2.7.7.02\lib\antlr.runtime.dll + True + + + ..\packages\Appccelerate.StateMachine.3.3.0\lib\netstandard1.0\Appccelerate.StateMachine.dll + True + + + ..\packages\xmlrpcnet.2.5.0\lib\net20\CookComputing.XmlRpcV2.dll + True + + + ..\packages\JetBrains.Platform.Lib.DevExpress.2.0.20170610\lib\net20\DevExpress.Data.v7.1.dll + True + + + ..\packages\JetBrains.Platform.Lib.DevExpress.2.0.20170610\lib\net20\DevExpress.Utils.v7.1.dll + True + + + ..\packages\JetBrains.Platform.Lib.DevExpress.2.0.20170610\lib\net20\DevExpress.XtraEditors.v7.1.dll + True + + + ..\packages\JetBrains.Platform.Lib.DevExpress.2.0.20170610\lib\net20\DevExpress.XtraTreeList.v7.1.dll + True + + + ..\packages\DotNetZip.1.10.1\lib\net20\DotNetZip.dll + True + + + ..\packages\JetBrains.SharpZipLib.Stripped.0.87.20170720.14\lib\net40\ICSharpCode.SharpZipLib.dll + True + + + ..\packages\JetBrains.Annotations.11.1.0\lib\net20\JetBrains.Annotations.dll + True + + + ..\packages\JetBrains.Platform.MSBuild.Logger.Api.1.0.20170809\lib\net\JetBrains.MSBuild.Logger.Api.dll + True + + + ..\packages\JetBrains.System.Reflection.Metadata.20170417.0.0.0\lib\net45\JetBrains.System.Reflection.Metadata.dll + True + + + ..\packages\JetBrains.Toolset.ScriptSourcesCompiler.Interface.1.0.20170420.0\lib\net\JetBrains.Toolset.ScriptSourcesCompiler.Interface.dll + True + + + ..\packages\JetBrains.MahApps.Metro.1.5.0.1\lib\net45\MahApps.Metro.dll + True + + + + ..\packages\JetBrains.Microsoft.Deployment.Compression.Cab.3.11.0\lib\net20\Microsoft.Deployment.Compression.dll + True + + + ..\packages\JetBrains.Microsoft.Deployment.Compression.Cab.3.11.0\lib\net20\Microsoft.Deployment.Compression.Cab.dll + True + + + ..\packages\Microsoft.Owin.3.0.1\lib\net45\Microsoft.Owin.dll + True + + + ..\packages\Microsoft.Owin.FileSystems.3.0.1\lib\net45\Microsoft.Owin.FileSystems.dll + True + + + ..\packages\Microsoft.Owin.Host.HttpListener.3.0.1\lib\net45\Microsoft.Owin.Host.HttpListener.dll + True + + + ..\packages\Microsoft.Owin.Hosting.3.0.1\lib\net45\Microsoft.Owin.Hosting.dll + True + + + ..\packages\Microsoft.Owin.StaticFiles.3.0.1\lib\net45\Microsoft.Owin.StaticFiles.dll + True + + + ..\packages\JetBrains.Platform.Lib.VisualStudio.AnyVs.ShellInterop.PrivateBuild.2.0.20141005.1\lib\net20\Microsoft.VisualStudio.Shell.Interop.dll + True + + + ..\packages\Microsoft.Web.Xdt.2.1.1\lib\net40\Microsoft.Web.XmlTransform.dll + True + + + ..\packages\Windows7APICodePack.JetBrains.Stripped.1.1.20150225.0\lib\Net\Microsoft.WindowsAPICodePack.dll + True + + + ..\packages\Windows7APICodePack.JetBrains.Stripped.1.1.20150225.0\lib\Net\Microsoft.WindowsAPICodePack.Shell.dll + True + + + ..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll + True + + + ..\packages\JetBrains.NuGet.Ultimate.4.5.0.20180215\lib\net45\NuGet.Commands.dll + True + + + ..\packages\JetBrains.NuGet.Ultimate.4.5.0.20180215\lib\net45\NuGet.Common.dll + True + + + ..\packages\JetBrains.NuGet.Ultimate.4.5.0.20180215\lib\net45\NuGet.Configuration.dll + True + + + ..\packages\JetBrains.NuGet.Core.2.14.1.20180215\lib\net40-Client\NuGet.Core.dll + True + + + ..\packages\JetBrains.NuGet.Ultimate.4.5.0.20180215\lib\net45\NuGet.DependencyResolver.Core.dll + True + + + ..\packages\JetBrains.NuGet.Frameworks.4.5.0.20180215\lib\net45\NuGet.Frameworks.dll + True + + + ..\packages\JetBrains.NuGet.Ultimate.4.5.0.20180215\lib\net45\NuGet.LibraryModel.dll + True + + + ..\packages\JetBrains.NuGet.Ultimate.4.5.0.20180215\lib\net45\NuGet.PackageManagement.dll + True + + + ..\packages\JetBrains.NuGet.Ultimate.4.5.0.20180215\lib\net45\NuGet.Packaging.dll + True + + + ..\packages\JetBrains.NuGet.Ultimate.4.5.0.20180215\lib\net45\NuGet.Packaging.Core.dll + True + + + ..\packages\JetBrains.NuGet.Ultimate.4.5.0.20180215\lib\net45\NuGet.ProjectModel.dll + True + + + ..\packages\JetBrains.NuGet.Ultimate.4.5.0.20180215\lib\net45\NuGet.Protocol.dll + True + + + ..\packages\JetBrains.NuGet.Ultimate.4.5.0.20180215\lib\net45\NuGet.Resolver.dll + True + + + ..\packages\JetBrains.NuGet.Versioning.4.5.0.20180215\lib\net45\NuGet.Versioning.dll + True + + + ..\packages\NUnit.2.6.4\lib\nunit.framework.dll + True + + + ..\packages\NVelocity.1.0.3\lib\NVelocity.dll + True + + + ..\packages\Owin.1.0\lib\net40\Owin.dll + True + + + ..\packages\sharpcompress.0.11.6\lib\net40\SharpCompress.dll + True + + + ..\packages\JetBrains.Should.1.1.20\lib\Should.dll + True + + + ..\packages\Sprache.JetBrains.2.1.0\lib\net40\Sprache.dll + True + + + + + + + + + + + ..\packages\System.ValueTuple.4.4.0\lib\netstandard1.0\System.ValueTuple.dll + True + + + ..\packages\JetBrains.System.Windows.Interactivity.3.0.40218.0\lib\net45\System.Windows.Interactivity.dll + True + + + + + + + + + ..\packages\Vestris.ResourceLib.JetBrains.1.4.20150303.0\lib\Net\Vestris.ResourceLib.dll + True + + + ..\packages\JetBrains.Platform.Lib.WpfContrib.2.0.20170610\lib\net20\WpfContrib.dll + True + + + ..\packages\xunit.JetBrains.1.9.2\lib\net20\xunit.dll + True + + + ..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + True + + + ..\packages\xunit.runner.utility.2.3.1\lib\net452\xunit.runner.utility.net452.dll + True + + + ..\packages\YamlDotNet.Signed.4.2.1\lib\net35\YamlDotNet.dll + True + + + + + Properties\AssemblyInfo.General.cs + + + Properties\AssemblyVersion.cs + + + + + + + + + + + cd "$(SolutionDir)" +powershell "& ""$(SolutionDir)\generateVersionInfo.ps1""" + + + + + 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}. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/GraphLabs.Guard/Guard.cs b/GraphLabs.Guard/Guard.cs new file mode 100644 index 0000000..45667f4 --- /dev/null +++ b/GraphLabs.Guard/Guard.cs @@ -0,0 +1,178 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using JetBrains.Annotations; +using System.Runtime.CompilerServices; + +namespace GraphLabs +{ + public static class Guard + { + + private sealed class ContractException : Exception + { + public ContractException(string description, string memberName, string filePath, int lineNumber ) : base(FormatErrorMessage(description, memberName, filePath, lineNumber)) { } + + private static string FormatErrorMessage(string description, string memberName, string filePath, int lineNumber ) + { + return ($"{description} in method {memberName}, source file path: {filePath}, line {lineNumber}."); + } + } + + [Conditional("DEBUG")] + public static void IsNotNull( + [InvokerParameterName]string argName, + T argument, + [CallerMemberName]string memberName = null, + [CallerFilePath]string filePath = null, + [CallerLineNumber]int lineNumber = 0 + ) + where T : class + { + if (argument == null) + { + throw new ContractException($"Argument {argName} shoud be not null ", memberName, filePath, lineNumber); + } + } + + [Conditional("DEBUG")] + public static void IsNotNull( + T argument, + [CallerMemberName]string memberName = null, + [CallerFilePath]string filePath = null, + [CallerLineNumber]int lineNumber = 0 + ) + where T : class + { + if (argument == null) + { + throw new ContractException($"Argument shoud be not null ", memberName, filePath, lineNumber); + } + } + + [Conditional("DEBUG")] + public static void AreAssignedTypes( + Type defaultType, + Type type, + [CallerMemberName]string memberName = null, + [CallerFilePath]string filePath = null, + [CallerLineNumber]int lineNumber = 0 + ) + { + if (!defaultType.IsAssignableFrom(type)) + { + throw new ContractException($"Type should be assigned to the default type", memberName, filePath, lineNumber); + } + } + + [Conditional("DEBUG")] + public static void AreEqual( + T a, + T b, + [InvokerParameterName]string argName1, + [InvokerParameterName]string argName2, + [CallerMemberName]string memberName = null, + [CallerFilePath]string filePath = null, + [CallerLineNumber]int lineNumber = 0 + ) + { + if (!Equals(a, b)) + { + throw new ContractException($"{argName1} should be equal to the {argName2} ", memberName, filePath, lineNumber); + } + } + + + [Conditional("DEBUG")] + public static void IsNotNullOrWhiteSpace( + string argument, + [CallerMemberName]string memberName = null, + [CallerFilePath]string filePath = null, + [CallerLineNumber]int lineNumber = 0 + ) + { + if (string.IsNullOrWhiteSpace(argument)) + { + throw new ContractException($"String argument should not be null or white space ", memberName, filePath, lineNumber); + } + } + + [Conditional("DEBUG")] + public static void IsPositive( + long num, + [InvokerParameterName]string argName, + [CallerMemberName]string memberName = null, + [CallerFilePath]string filePath = null, + [CallerLineNumber]int lineNumber = 0 + ) + { + if (num <= 0) + { + throw new ContractException($"Long argument {argName} should be positive ", memberName, filePath, lineNumber); + } + } + + [Conditional("DEBUG")] + public static void IsPositive( + int num, + [InvokerParameterName]string argName, + [CallerMemberName]string memberName = null, + [CallerFilePath]string filePath = null, + [CallerLineNumber]int lineNumber = 0 + ) + { + if (num <= 0) + { + throw new ContractException($"Int argument {argName} should be positive ", memberName, filePath, lineNumber); + } + } + + [Conditional("DEBUG")] + public static void IsNotEmpty( + string argument, + [InvokerParameterName]string argName, + [CallerMemberName]string memberName = null, + [CallerFilePath]string filePath = null, + [CallerLineNumber]int lineNumber = 0 + ) + { + if (argument == string.Empty) + { + throw new ContractException($"String {argName} shoud not be empty ", memberName, filePath, lineNumber); + } + } + + [Conditional("DEBUG")] + public static void IsTrueAssertion( + [NotNull] string message, + bool argument, + + [CallerMemberName]string memberName = null, + [CallerFilePath]string filePath = null, + [CallerLineNumber]int lineNumber = 0) + { + if (argument == false) + { + throw new ContractException(message, memberName, filePath, lineNumber); + } + } + + [Conditional("DEBUG")] + public static void IsTrueAssertion( + bool argument, + [CallerMemberName]string memberName = null, + [CallerFilePath]string filePath = null, + [CallerLineNumber]int lineNumber = 0) + { + if (argument == false) + { + throw new ContractException("Assertion should be true", memberName, filePath, lineNumber); + } + } + + } + +} diff --git a/GraphLabs.Guard/Properties/AssemblyInfo.cs b/GraphLabs.Guard/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..efbb2f2 --- /dev/null +++ b/GraphLabs.Guard/Properties/AssemblyInfo.cs @@ -0,0 +1,18 @@ +using System.Reflection; +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("GraphLabs.Guard")] +[assembly: AssemblyDescription("Утилиты для проверки утверждений.")] +[assembly: AssemblyConfiguration("")] +[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("d0a05aef-dc7e-4b2b-a82a-9a23eaa0af95")] diff --git a/GraphLabs.Guard/packages.config b/GraphLabs.Guard/packages.config new file mode 100644 index 0000000..7523386 --- /dev/null +++ b/GraphLabs.Guard/packages.config @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/GraphLabs.Site.Core/GraphLabs.Site.Core.csproj b/GraphLabs.Site.Core/GraphLabs.Site.Core.csproj index 9747804..c3957f2 100644 --- a/GraphLabs.Site.Core/GraphLabs.Site.Core.csproj +++ b/GraphLabs.Site.Core/GraphLabs.Site.Core.csproj @@ -142,6 +142,12 @@ + + + {d0a05aef-dc7e-4b2b-a82a-9a23eaa0af95} + GraphLabs.Guard + + cd "$(SolutionDir)" diff --git a/GraphLabs.Site.Core/GraphLabsException.cs b/GraphLabs.Site.Core/GraphLabsException.cs index ee0825b..b67f627 100644 --- a/GraphLabs.Site.Core/GraphLabsException.cs +++ b/GraphLabs.Site.Core/GraphLabsException.cs @@ -10,7 +10,7 @@ public class GraphLabsException : Exception public GraphLabsException(Exception innerException) { - Contract.Requires(innerException != null); + Guard.IsNotNull(nameof(innerException), innerException); this.innerException = innerException; } diff --git a/GraphLabs.Site.Logic/GraphLabs.Site.Logic.csproj b/GraphLabs.Site.Logic/GraphLabs.Site.Logic.csproj index 26ef12d..720901c 100644 --- a/GraphLabs.Site.Logic/GraphLabs.Site.Logic.csproj +++ b/GraphLabs.Site.Logic/GraphLabs.Site.Logic.csproj @@ -219,6 +219,10 @@ {3e515720-d0a1-4b01-a3e0-c82412b2d663} GraphLabs.DomainModel + + {d0a05aef-dc7e-4b2b-a82a-9a23eaa0af95} + GraphLabs.Guard + {d62cc3f4-3ea1-44ff-b9e2-492582788b3b} GraphLabs.Site.Core diff --git a/GraphLabs.Site.Logic/IoC/SiteLogicConfiguration.cs b/GraphLabs.Site.Logic/IoC/SiteLogicConfiguration.cs index 787c7d2..64bbd83 100644 --- a/GraphLabs.Site.Logic/IoC/SiteLogicConfiguration.cs +++ b/GraphLabs.Site.Logic/IoC/SiteLogicConfiguration.cs @@ -12,6 +12,7 @@ using GraphLabs.Site.Utils.IoC; using GraphLabs.Tasks.Contract; using Microsoft.Practices.Unity; +using GraphLabs; namespace GraphLabs.Site.Logic.IoC { @@ -19,6 +20,7 @@ public class SiteLogicConfiguration : IUnityRegistry { public void ConfigureContainer(IUnityContainer container) { + Guard.IsNotNull(nameof(container), container); // Сервисы для сайта container.RegisterType(new PerResolveLifetimeManager()); container.RegisterType(new PerResolveLifetimeManager()); diff --git a/GraphLabs.Site.Logic/Security/FormsAuthenticationSavingService.cs b/GraphLabs.Site.Logic/Security/FormsAuthenticationSavingService.cs index f3cd608..c479f57 100644 --- a/GraphLabs.Site.Logic/Security/FormsAuthenticationSavingService.cs +++ b/GraphLabs.Site.Logic/Security/FormsAuthenticationSavingService.cs @@ -126,8 +126,8 @@ private SessionInfo() /// Информация о сессии public SessionInfo(string email, Guid guid) { - Contract.Requires(!string.IsNullOrWhiteSpace(email)); - Contract.Requires(guid != Guid.Empty); + Guard.IsNotNullOrWhiteSpace(email); + Guard.IsTrueAssertion(guid != Guid.Empty, "Сессия не должна быть null." ); Email = email; SessionGuid = guid; diff --git a/GraphLabs.Site.Logic/Security/GraphLabsPrincipal.cs b/GraphLabs.Site.Logic/Security/GraphLabsPrincipal.cs index d3768aa..8c96c4a 100644 --- a/GraphLabs.Site.Logic/Security/GraphLabsPrincipal.cs +++ b/GraphLabs.Site.Logic/Security/GraphLabsPrincipal.cs @@ -41,8 +41,8 @@ private GraphLabsIdentity() /// Личность public GraphLabsIdentity(string email, string displayName) { - Contract.Requires(!string.IsNullOrWhiteSpace(email)); - Contract.Requires(!string.IsNullOrWhiteSpace(displayName)); + Guard.IsNotNullOrWhiteSpace(email); + Guard.IsNotNullOrWhiteSpace(displayName); Name = email; DisplayName = displayName; } @@ -54,7 +54,7 @@ public GraphLabsIdentity(string email, string displayName) /// Determines whether the current principal belongs to the specified role. bool IPrincipal.IsInRole(string role) { - Contract.Assert(!string.IsNullOrWhiteSpace(role)); + Guard.IsNotNullOrWhiteSpace(role); UserRole actualRole; if (!Enum.TryParse(role, false, out actualRole)) diff --git a/GraphLabs.Site.Logic/Security/Interfaces/IAuthenticationSavingService.cs b/GraphLabs.Site.Logic/Security/Interfaces/IAuthenticationSavingService.cs index 0bd93a9..6dccfae 100644 --- a/GraphLabs.Site.Logic/Security/Interfaces/IAuthenticationSavingService.cs +++ b/GraphLabs.Site.Logic/Security/Interfaces/IAuthenticationSavingService.cs @@ -5,7 +5,7 @@ namespace GraphLabs.Site { /// Сервис фиксации результата аутентификации - [ContractClass(typeof(AuthenticationSavingServiceContracts))] + // [ContractClass(typeof(AuthenticationSavingServiceContracts))] public interface IAuthenticationSavingService { /// Пишем в cookies, что вошли @@ -33,28 +33,28 @@ public interface ISessionInfo } /// Сервис фиксации результата аутентификации - контракты - [ContractClassFor(typeof(IAuthenticationSavingService))] - internal abstract class AuthenticationSavingServiceContracts : IAuthenticationSavingService - { - // ReSharper disable AssignNullToNotNullAttribute - - /// Пишем в cookies, что вошли - public void SignIn(string email, Guid sessionGuid) - { - Contract.Requires(!string.IsNullOrWhiteSpace(email)); - Contract.Requires(sessionGuid != Guid.Empty); - } - - /// Пишем в cookies, что вышли - public void SignOut() - { - } - - /// Получить текущую сессию из cookies - public ISessionInfo GetSessionInfo() - { - return default(ISessionInfo); - } - - } + //[ContractClassFor(typeof(IAuthenticationSavingService))] + //internal abstract class AuthenticationSavingServiceContracts : IAuthenticationSavingService + //{ + // // ReSharper disable AssignNullToNotNullAttribute + + // /// Пишем в cookies, что вошли + // public void SignIn(string email, Guid sessionGuid) + // { + // Contract.Requires(!string.IsNullOrWhiteSpace(email)); + // Contract.Requires(sessionGuid != Guid.Empty); + // } + + // /// Пишем в cookies, что вышли + // public void SignOut() + // { + // } + + // /// Получить текущую сессию из cookies + // public ISessionInfo GetSessionInfo() + // { + // return default(ISessionInfo); + // } + + //} } \ No newline at end of file diff --git a/GraphLabs.Site.Logic/Security/Interfaces/IMembershipEngine.cs b/GraphLabs.Site.Logic/Security/Interfaces/IMembershipEngine.cs index 9d21911..a742b30 100644 --- a/GraphLabs.Site.Logic/Security/Interfaces/IMembershipEngine.cs +++ b/GraphLabs.Site.Logic/Security/Interfaces/IMembershipEngine.cs @@ -5,7 +5,7 @@ namespace GraphLabs.Site.Logic.Security { /// Работа с пользователями - [ContractClass(typeof(MembershipEngineContracts))] + // [ContractClass(typeof(MembershipEngineContracts))] public interface IMembershipEngine { /// Выполняет вход @@ -29,64 +29,79 @@ public interface IMembershipEngine } /// Контракты для - [ContractClassFor(typeof(IMembershipEngine))] - internal abstract class MembershipEngineContracts : IMembershipEngine - { - /// Выполняет вход - public LoginResult TryLogin(string email, string password, string clientIp, out Guid sessionGuid) - { - Contract.Requires(IpHelper.CheckIsValidIP(clientIp)); - Contract.Ensures( - Contract.Result() != LoginResult.Success & Contract.ValueAtReturn(out sessionGuid) == Guid.Empty || - Contract.Result() == LoginResult.Success & Contract.ValueAtReturn(out sessionGuid) != Guid.Empty); - - return default(LoginResult); - } - - /// Выполняет вход - public LoginResult TryForceLogin(string email, string password, string clientIp, out Guid sessionGuid) - { - Contract.Requires(IpHelper.CheckIsValidIP(clientIp)); - Contract.Ensures( - Contract.Result() != LoginResult.Success & Contract.ValueAtReturn(out sessionGuid) == Guid.Empty || - Contract.Result() == LoginResult.Success & Contract.ValueAtReturn(out sessionGuid) != Guid.Empty); - - return default(LoginResult); - } - - /// Выход - public void Logout(string email, Guid sessionGuid, string clientIp) - { - } - - /// Зарегистрировать нового студента - public bool RegisterNewStudent(string email, string name, string fatherName, string surname, string password, long groupId) - { - Contract.Requires(!string.IsNullOrWhiteSpace(email)); - Contract.Requires(!string.IsNullOrWhiteSpace(name)); - Contract.Requires(!string.IsNullOrWhiteSpace(surname)); - Contract.Requires(!string.IsNullOrWhiteSpace(password)); - Contract.Requires(groupId > 0); - - return default(bool); - } - - /// Проверяем пользователя - public bool TryAuthenticate(string email, Guid sessionGuid, string clientIp) - { - return default(bool); - } - - /// Поменять пароль - public bool ChangePassword(string email, Guid sessionGuid, string clientIp, string currentPassword, string newPassword) - { - Contract.Requires(!string.IsNullOrWhiteSpace(email)); - Contract.Requires(sessionGuid != Guid.Empty); - Contract.Requires(IpHelper.CheckIsValidIP(clientIp)); - Contract.Requires(!string.IsNullOrWhiteSpace(currentPassword)); - Contract.Requires(!string.IsNullOrWhiteSpace(newPassword)); - - return default(bool); - } - } + //[ContractClassFor(typeof(IMembershipEngine))] + //internal abstract class MembershipEngineContracts : IMembershipEngine + //{ + // /// Выполняет вход + // public LoginResult TryLogin(string email, string password, string clientIp, out Guid sessionGuid) + // { + // Contract.Requires(IpHelper.CheckIsValidIP(clientIp)); + // Guard.IsTrueAssertion(IpHelper.CheckIsValidIP(clientIp)); + // Contract.Ensures( + // Contract.Result() != LoginResult.Success & Contract.ValueAtReturn(out sessionGuid) == Guid.Empty || + // Contract.Result() == LoginResult.Success & Contract.ValueAtReturn(out sessionGuid) != Guid.Empty); + // Guard.IsTrueAssertion(default(LoginResult) != LoginResult.Success & sessionGuid == Guid.Empty || + // default(LoginResult) == LoginResult.Success & sessionGuid != Guid.Empty); + + // return default(LoginResult); + // } + + // /// Выполняет вход + // public LoginResult TryForceLogin(string email, string password, string clientIp, out Guid sessionGuid) + // { + // Contract.Requires(IpHelper.CheckIsValidIP(clientIp)); + // Guard.IsTrueAssertion(IpHelper.CheckIsValidIP(clientIp)); + // Contract.Ensures( + // Contract.Result() != LoginResult.Success & Contract.ValueAtReturn(out sessionGuid) == Guid.Empty || + // Contract.Result() == LoginResult.Success & Contract.ValueAtReturn(out sessionGuid) != Guid.Empty); + // Guard.IsTrueAssertion(default(LoginResult) != LoginResult.Success & sessionGuid == Guid.Empty || + // default(LoginResult) == LoginResult.Success & sessionGuid != Guid.Empty); + // return default(LoginResult); + // } + + // /// Выход + // public void Logout(string email, Guid sessionGuid, string clientIp) + // { + // } + + // /// Зарегистрировать нового студента + // public bool RegisterNewStudent(string email, string name, string fatherName, string surname, string password, long groupId) + // { + // Contract.Requires(!string.IsNullOrWhiteSpace(email)); + // Guard.IsNotNullOrWhiteSpace(email); + // Contract.Requires(!string.IsNullOrWhiteSpace(name)); + // Guard.IsNotNullOrWhiteSpace(name); + // Contract.Requires(!string.IsNullOrWhiteSpace(surname)); + // Guard.IsNotNullOrWhiteSpace(surname); + // Contract.Requires(!string.IsNullOrWhiteSpace(password)); + // Guard.IsNotNullOrWhiteSpace(password); + // Contract.Requires(groupId > 0); + // Guard.IsTrueAssertion(groupId > 0); + + // return default(bool); + // } + + // /// Проверяем пользователя + // public bool TryAuthenticate(string email, Guid sessionGuid, string clientIp) + // { + // return default(bool); + // } + + // /// Поменять пароль + // public bool ChangePassword(string email, Guid sessionGuid, string clientIp, string currentPassword, string newPassword) + // { + // Contract.Requires(!string.IsNullOrWhiteSpace(email)); + // Guard.IsNotNullOrWhiteSpace(email); + // Contract.Requires(sessionGuid != Guid.Empty); + // Guard.IsTrueAssertion(sessionGuid != Guid.Empty); + // Contract.Requires(IpHelper.CheckIsValidIP(clientIp)); + // Guard.IsTrueAssertion(IpHelper.CheckIsValidIP(clientIp)); + // Contract.Requires(!string.IsNullOrWhiteSpace(currentPassword)); + // Guard.IsNotNullOrWhiteSpace(currentPassword); + // Contract.Requires(!string.IsNullOrWhiteSpace(newPassword)); + // Guard.IsNotNullOrWhiteSpace(newPassword); + + // return default(bool); + // } + //} } \ No newline at end of file diff --git a/GraphLabs.Site.Logic/Security/MembershipEngine.cs b/GraphLabs.Site.Logic/Security/MembershipEngine.cs index 8ff8081..200b58a 100644 --- a/GraphLabs.Site.Logic/Security/MembershipEngine.cs +++ b/GraphLabs.Site.Logic/Security/MembershipEngine.cs @@ -12,6 +12,7 @@ using GraphLabs.DomainModel.Extensions; using GraphLabs.Site.Core.OperationContext; using log4net; +using GraphLabs.Site.Utils; namespace GraphLabs.Site.Logic.Security { @@ -31,8 +32,8 @@ public MembershipEngine( ISystemDateService systemDateService, IOperationContextFactory operationFactory) { - Contract.Requires(hashCalculator != null); - Contract.Requires(systemDateService != null); + Guard.IsNotNull(nameof(hashCalculator), hashCalculator); + Guard.IsNotNull(nameof(systemDateService), systemDateService); _hashCalculator = hashCalculator; _systemDateService = systemDateService; @@ -40,15 +41,23 @@ public MembershipEngine( } /// Выполняет вход - public LoginResult TryLogin(string email, string password, string clientIp, out Guid sessionGuid) + public LoginResult TryLogin(string email, string password, string clientIp, out Guid sessionGuid) { - return TryLoginImpl(email, password, clientIp, out sessionGuid, force: false); + Guard.IsTrueAssertion(IpHelper.CheckIsValidIP(clientIp)); + var result = TryLoginImpl(email, password, clientIp, out sessionGuid, force: false); + Guard.IsTrueAssertion(result != LoginResult.Success & sessionGuid == Guid.Empty || + result == LoginResult.Success & sessionGuid != Guid.Empty); + return result; } /// Выполняет вход, убивая все сессии на других браузерах/компьютерах public LoginResult TryForceLogin(string email, string password, string clientIp, out Guid sessionGuid) { - return TryLoginImpl(email, password, clientIp, out sessionGuid, force: true); + Guard.IsTrueAssertion(IpHelper.CheckIsValidIP(clientIp)); + var result = TryLoginImpl(email, password, clientIp, out sessionGuid, force: true); + Guard.IsTrueAssertion(result != LoginResult.Success & sessionGuid == Guid.Empty || + result == LoginResult.Success & sessionGuid != Guid.Empty); + return result; } private LoginResult TryLoginImpl(string email, string password, string clientIp, out Guid sessionGuid, bool force) @@ -58,7 +67,7 @@ private LoginResult TryLoginImpl(string email, string password, string clientIp, var user = operation.QueryOf() .SingleOrDefault(u => u.Email == email && (!(u is Student) || ((u as Student).IsVerified && !(u as Student).IsDismissed))); - + if (user == null || !UserIsValid(user, password)) { _log.InfoFormat("Неудачный вход, e-mail: {0}, ip: {1}", email, clientIp); @@ -165,6 +174,12 @@ public bool TryAuthenticate(string email, Guid sessionGuid, string clientIp) /// Поменять пароль public bool ChangePassword(string email, Guid sessionGuid, string clientIp, string currentPassword, string newPassword) { + Guard.IsNotNullOrWhiteSpace(email); + Guard.IsTrueAssertion(sessionGuid != Guid.Empty); + Guard.IsTrueAssertion(IpHelper.CheckIsValidIP(clientIp)); + Guard.IsNotNullOrWhiteSpace(currentPassword); + Guard.IsNotNullOrWhiteSpace(newPassword); + using (var operation = _operationFactory.Create()) { var session = FindSession(operation.DataContext.Query, email, sessionGuid, clientIp); @@ -193,6 +208,12 @@ public bool ChangePassword(string email, Guid sessionGuid, string clientIp, stri /// false, если такой пользователь уже есть (с таким email), иначе true public bool RegisterNewStudent(string email, string name, string fatherName, string surname, string password, long groupId) { + Guard.IsNotNullOrWhiteSpace(email); + Guard.IsNotNullOrWhiteSpace(name); + Guard.IsNotNullOrWhiteSpace(surname); + Guard.IsNotNullOrWhiteSpace(password); + Guard.IsTrueAssertion(groupId > 0); + var passHash = _hashCalculator.Crypt(password); using (var operation = _operationFactory.Create()) diff --git a/GraphLabs.Site.Logic/Security/SecurityExtensions.cs b/GraphLabs.Site.Logic/Security/SecurityExtensions.cs index 17c820b..a337a62 100644 --- a/GraphLabs.Site.Logic/Security/SecurityExtensions.cs +++ b/GraphLabs.Site.Logic/Security/SecurityExtensions.cs @@ -13,8 +13,8 @@ public static class SecurityExtensions /// Есть ли у пользователя роль? public static bool IsInRole(this IPrincipal principal, UserRole role) { - Contract.Requires(principal != null); - Contract.Requires(principal is IGraphLabsPrincipal); + Guard.IsNotNull(nameof(principal), principal); + Guard.IsTrueAssertion(principal is IGraphLabsPrincipal); return ((IGraphLabsPrincipal)principal).IsInRole(role); } @@ -22,9 +22,9 @@ public static bool IsInRole(this IPrincipal principal, UserRole role) /// Есть ли у пользователя какая-либо из ролей? public static bool IsInAnyRole(this IPrincipal principal, params UserRole[] roles) { - Contract.Requires(principal != null); - Contract.Requires(principal is IGraphLabsPrincipal); - Contract.Requires(roles != null && roles.Any()); + Guard.IsNotNull(nameof(principal), principal); + Guard.IsTrueAssertion(principal is IGraphLabsPrincipal); + Guard.IsTrueAssertion(roles != null && roles.Any()); return roles.Any(role => ((IGraphLabsPrincipal)principal).IsInRole(role)); } @@ -32,8 +32,8 @@ public static bool IsInAnyRole(this IPrincipal principal, params UserRole[] role /// Отображаемое имя public static string DisplayName(this IIdentity identity) { - Contract.Requires(identity != null); - Contract.Requires(identity is IGraphLabsIdentity); + Guard.IsNotNull(nameof(identity), identity); + Guard.IsTrueAssertion(identity is IGraphLabsPrincipal); return ((IGraphLabsIdentity)identity).DisplayName; } diff --git a/GraphLabs.Site.Logic/XapParsing/XapProcessor.cs b/GraphLabs.Site.Logic/XapParsing/XapProcessor.cs index c82da0f..725326d 100644 --- a/GraphLabs.Site.Logic/XapParsing/XapProcessor.cs +++ b/GraphLabs.Site.Logic/XapParsing/XapProcessor.cs @@ -51,7 +51,7 @@ private class XapInfo : IXapInfo /// null, если во время обработки произошла ошибка; иначе - новую сущность public IXapInfo Parse(Stream stream) { - Contract.Assert(stream != null); + Guard.IsNotNull(nameof(stream), stream); // Парсим примерно следующее (AppManifest.xaml): /* @@ -83,8 +83,8 @@ public IXapInfo Parse(Stream stream) { var deploymentSection = XDocument.Load(reader).Root; - Contract.Assume(deploymentSection != null); - Contract.Assume(deploymentSection.Name.LocalName == DEPLOYMENT_SECTION_NAME); + Guard.IsNotNull(deploymentSection); + Guard.IsTrueAssertion(deploymentSection.Name.LocalName == DEPLOYMENT_SECTION_NAME); var entryPointAssemblyName = deploymentSection .Attributes() diff --git a/GraphLabs.Site.Models/AvailableLab/DemoLabModelLoader.cs b/GraphLabs.Site.Models/AvailableLab/DemoLabModelLoader.cs index c823f3a..f2ccbe2 100644 --- a/GraphLabs.Site.Models/AvailableLab/DemoLabModelLoader.cs +++ b/GraphLabs.Site.Models/AvailableLab/DemoLabModelLoader.cs @@ -16,8 +16,8 @@ public DemoLabModelLoader(IEntityQuery query) : base(query) { } /// Загрузить по сущности-прототипу public override DemoLabModel Load(AbstractLabSchedule sch) { - Contract.Requires(sch != null); - Contract.Requires(sch.Mode == LabExecutionMode.IntroductoryMode); + Guard.IsNotNull(nameof(sch), sch); + Guard.IsTrueAssertion(sch.Mode == LabExecutionMode.IntroductoryMode); var model = new DemoLabModel { diff --git a/GraphLabs.Site.Models/AvailableLab/TestingLabModelLoader.cs b/GraphLabs.Site.Models/AvailableLab/TestingLabModelLoader.cs index 466ecd9..5286784 100644 --- a/GraphLabs.Site.Models/AvailableLab/TestingLabModelLoader.cs +++ b/GraphLabs.Site.Models/AvailableLab/TestingLabModelLoader.cs @@ -13,8 +13,8 @@ public TestingLabModelLoader(IEntityQuery query) : base(query) { } /// - public override TestingLabModel Load(AbstractLabSchedule sch) { - Contract.Requires(sch != null); - Contract.Requires(sch.Mode == LabExecutionMode.TestMode); + Guard.IsNotNull(nameof(sch), sch); + Guard.IsTrueAssertion(sch.Mode == LabExecutionMode.TestMode); var model = new TestingLabModel { diff --git a/GraphLabs.Site.Models/CreateLab/CreateLabModelLoader.cs b/GraphLabs.Site.Models/CreateLab/CreateLabModelLoader.cs index c5d9e3f..d66b2ee 100644 --- a/GraphLabs.Site.Models/CreateLab/CreateLabModelLoader.cs +++ b/GraphLabs.Site.Models/CreateLab/CreateLabModelLoader.cs @@ -16,7 +16,7 @@ public CreateLabModelLoader(IEntityQuery query) : base(query) { } /// Загрузить по сущности-прототипу public override CreateLabModel Load(LabWork labWork) { - Contract.Requires(labWork != null); + Guard.IsNotNull(nameof(labWork), labWork); var model = new CreateLabModel { diff --git a/GraphLabs.Site.Models/GraphLabs.Site.Models.csproj b/GraphLabs.Site.Models/GraphLabs.Site.Models.csproj index 113a141..a9bb429 100644 --- a/GraphLabs.Site.Models/GraphLabs.Site.Models.csproj +++ b/GraphLabs.Site.Models/GraphLabs.Site.Models.csproj @@ -247,6 +247,10 @@ {3e515720-d0a1-4b01-a3e0-c82412b2d663} GraphLabs.DomainModel + + {d0a05aef-dc7e-4b2b-a82a-9a23eaa0af95} + GraphLabs.Guard + {d62cc3f4-3ea1-44ff-b9e2-492582788b3b} GraphLabs.Site.Core diff --git a/GraphLabs.Site.Models/Groups/GroupModelLoader.cs b/GraphLabs.Site.Models/Groups/GroupModelLoader.cs index 2d24ed8..52b19f4 100644 --- a/GraphLabs.Site.Models/Groups/GroupModelLoader.cs +++ b/GraphLabs.Site.Models/Groups/GroupModelLoader.cs @@ -20,7 +20,7 @@ public GroupModelLoader(IEntityQuery query, ISystemDateService dateService) /// Загрузить по сущности-прототипу public override GroupModel Load(Group group) { - Contract.Requires(group != null); + Guard.IsNotNull(nameof(group), group); var model = new GroupModel { diff --git a/GraphLabs.Site.Models/Infrastructure/AbstractModelSaver.cs b/GraphLabs.Site.Models/Infrastructure/AbstractModelSaver.cs index f431006..0c98718 100644 --- a/GraphLabs.Site.Models/Infrastructure/AbstractModelSaver.cs +++ b/GraphLabs.Site.Models/Infrastructure/AbstractModelSaver.cs @@ -33,7 +33,7 @@ public TEntity CreateOrUpdate(TModel model) if (!ExistsInDatabase(model)) { var type = GetEntityType(model); - Contract.Assert(typeof(TEntity).IsAssignableFrom(type)); + Guard.AreAssignedTypes(typeof(TEntity), type); entity = (TEntity)operation.DataContext.Factory.Create( type, o => GetEntityInitializer(model, operation.DataContext.Query)((TEntity)o)); diff --git a/GraphLabs.Site.Models/Infrastructure/EntityRemover.cs b/GraphLabs.Site.Models/Infrastructure/EntityRemover.cs index d70a19e..a6af3f0 100644 --- a/GraphLabs.Site.Models/Infrastructure/EntityRemover.cs +++ b/GraphLabs.Site.Models/Infrastructure/EntityRemover.cs @@ -25,12 +25,12 @@ public EntityRemover(IOperationContextFactory operationContex public RemovalStatus Remove(object id) { - Contract.Requires(id != null); + Guard.IsNotNull(nameof(id), id); using (var operation = _operationContextFactory.Create()) { var entityToDelete = operation.DataContext.Query.Find(id); if (entityToDelete == null) return RemovalStatus.ElementDoesNotExist; - Contract.Assert(typeof (TEntity).IsAssignableFrom(typeof (TEntity))); + Guard.AreAssignedTypes(typeof(TEntity), typeof(TEntity)); try { operation.DataContext.Factory.Delete(entityToDelete); diff --git a/GraphLabs.Site.Models/IoC/ModelsConfiguration.cs b/GraphLabs.Site.Models/IoC/ModelsConfiguration.cs index 9312818..f28de76 100644 --- a/GraphLabs.Site.Models/IoC/ModelsConfiguration.cs +++ b/GraphLabs.Site.Models/IoC/ModelsConfiguration.cs @@ -28,6 +28,7 @@ public class ModelsConfiguration : IUnityRegistry { public void ConfigureContainer(IUnityContainer container) { + Guard.IsNotNull(nameof(container), container); container.RegisterType(new HierarchicalLifetimeManager()); // группы diff --git a/GraphLabs.Site.Models/Lab/LabModelLoader.cs b/GraphLabs.Site.Models/Lab/LabModelLoader.cs index b0064a1..4f0758b 100644 --- a/GraphLabs.Site.Models/Lab/LabModelLoader.cs +++ b/GraphLabs.Site.Models/Lab/LabModelLoader.cs @@ -13,7 +13,7 @@ public LabModelLoader(IEntityQuery query) : base(query) { } /// Загрузить по сущности-прототипу public override LabModel Load(LabWork labWork) { - Contract.Requires(labWork != null); + Guard.IsNotNull(nameof(labWork), labWork); var model = new LabModel { diff --git a/GraphLabs.Site.Models/LabExecution/Operations/LoadVariantForExecutionBase.cs b/GraphLabs.Site.Models/LabExecution/Operations/LoadVariantForExecutionBase.cs index 412e888..6f60de0 100644 --- a/GraphLabs.Site.Models/LabExecution/Operations/LoadVariantForExecutionBase.cs +++ b/GraphLabs.Site.Models/LabExecution/Operations/LoadVariantForExecutionBase.cs @@ -239,7 +239,7 @@ private TModel CreateModelHeader(Result result, Task currentTask) private VariantExecutionModelBase CompleteVariant(Result result) { - Contract.Assert(result.AbstractResultEntries.All(r => r.Status == ExecutionStatus.Complete)); + Guard.IsTrueAssertion(result.AbstractResultEntries.All(r => r.Status == ExecutionStatus.Complete)); var mark = GetMark(result.AbstractResultEntries); result.Score = mark; diff --git a/GraphLabs.Site.Models/Question/QuestionModelLoader.cs b/GraphLabs.Site.Models/Question/QuestionModelLoader.cs index cce838d..6aeff9b 100644 --- a/GraphLabs.Site.Models/Question/QuestionModelLoader.cs +++ b/GraphLabs.Site.Models/Question/QuestionModelLoader.cs @@ -13,7 +13,7 @@ public QuestionModelLoader(IEntityQuery query) : base(query) { } /// Загрузить по сущности-прототипу public override QuestionModel Load(TestQuestion question) { - Contract.Requires(question != null); + Guard.IsNotNull(nameof(question), question); var model = new QuestionModel { diff --git a/GraphLabs.Site.Models/Results/ResultModelLoader.cs b/GraphLabs.Site.Models/Results/ResultModelLoader.cs index 0fcd9d8..ed05427 100644 --- a/GraphLabs.Site.Models/Results/ResultModelLoader.cs +++ b/GraphLabs.Site.Models/Results/ResultModelLoader.cs @@ -16,8 +16,8 @@ public ResultModelLoader(IEntityQuery query): base(query) { } public override ResultModel Load(Result result) { - Contract.Requires(result != null); - + Guard.IsNotNull(nameof(result), result); + var model = new ResultModel() { Id = result.Id, diff --git a/GraphLabs.Site.Models/ResultsWithTaskInfo/ResultWithTaskInfoModelLoader.cs b/GraphLabs.Site.Models/ResultsWithTaskInfo/ResultWithTaskInfoModelLoader.cs index bf63b8c..d1eddc1 100644 --- a/GraphLabs.Site.Models/ResultsWithTaskInfo/ResultWithTaskInfoModelLoader.cs +++ b/GraphLabs.Site.Models/ResultsWithTaskInfo/ResultWithTaskInfoModelLoader.cs @@ -28,7 +28,7 @@ public ResultWithTaskInfoModelLoader(IEntityQuery query, public override ResultWithTaskInfoModel Load(Result result) { - Contract.Requires(result != null); + Guard.IsNotNull(nameof(result), result); var name = result.Student.GetShortName(); var model = new ResultWithTaskInfoModel() { diff --git a/GraphLabs.Site.Models/Schedule/Edit/EditLabScheduleModelSaver.cs b/GraphLabs.Site.Models/Schedule/Edit/EditLabScheduleModelSaver.cs index b389217..34634ea 100644 --- a/GraphLabs.Site.Models/Schedule/Edit/EditLabScheduleModelSaver.cs +++ b/GraphLabs.Site.Models/Schedule/Edit/EditLabScheduleModelSaver.cs @@ -29,7 +29,7 @@ protected override Action GetEntityInitializer(EditLabSched var groupSch = sch as GroupLabSchedule; if (groupSch != null) { - Contract.Assert(model.ScheduleKind == EditLabScheduleModelBase.Kind.Group); + Guard.IsTrueAssertion(model.ScheduleKind == EditLabScheduleModelBase.Kind.Group); groupSch.Group = query.Get(model.GetDoerId()); return; } @@ -37,7 +37,7 @@ protected override Action GetEntityInitializer(EditLabSched var studentSch = sch as IndividualLabSchedule; if (studentSch != null) { - Contract.Assert(model.ScheduleKind == EditLabScheduleModelBase.Kind.Individual); + Guard.IsTrueAssertion(model.ScheduleKind == EditLabScheduleModelBase.Kind.Individual); studentSch.Student = query.Get(model.GetDoerId()); return; } diff --git a/GraphLabs.Site.Models/StudentActions/StudentActionModelLoader.cs b/GraphLabs.Site.Models/StudentActions/StudentActionModelLoader.cs index 4fe3645..fb276e6 100644 --- a/GraphLabs.Site.Models/StudentActions/StudentActionModelLoader.cs +++ b/GraphLabs.Site.Models/StudentActions/StudentActionModelLoader.cs @@ -10,7 +10,7 @@ public StudentActionModelLoader(IEntityQuery query) : base(query) { } public override StudentActionModel Load(StudentAction studentAction) { - Contract.Requires(studentAction != null); + Guard.IsNotNull(nameof(studentAction), studentAction); var model = new StudentActionModel() { diff --git a/GraphLabs.Site.Models/TaskResults/TaskResultModelLoader.cs b/GraphLabs.Site.Models/TaskResults/TaskResultModelLoader.cs index 0aaa4f3..623b23e 100644 --- a/GraphLabs.Site.Models/TaskResults/TaskResultModelLoader.cs +++ b/GraphLabs.Site.Models/TaskResults/TaskResultModelLoader.cs @@ -12,7 +12,7 @@ public TaskResultModelLoader(IEntityQuery query) : base(query) { } public override TaskResultModel Load(TaskResult taskResult) { - Contract.Requires(taskResult != null); + Guard.IsNotNull(nameof(taskResult), taskResult); var model = new TaskResultModel() { diff --git a/GraphLabs.Site.Models/TaskResultsWithActions/TaskResultWithActionsModelLoader.cs b/GraphLabs.Site.Models/TaskResultsWithActions/TaskResultWithActionsModelLoader.cs index 2519a52..dc533dd 100644 --- a/GraphLabs.Site.Models/TaskResultsWithActions/TaskResultWithActionsModelLoader.cs +++ b/GraphLabs.Site.Models/TaskResultsWithActions/TaskResultWithActionsModelLoader.cs @@ -19,7 +19,7 @@ public TaskResultWithActionsModelLoader(IEntityQuery query, public override TaskResultWithActionsModel Load(TaskResult taskResult) { - Contract.Requires(taskResult != null); + Guard.IsNotNull(nameof(taskResult), taskResult); var model = new TaskResultWithActionsModel() { diff --git a/GraphLabs.Site.Models/TestPool/TestPoolModelLoader.cs b/GraphLabs.Site.Models/TestPool/TestPoolModelLoader.cs index 89f2329..84146ba 100644 --- a/GraphLabs.Site.Models/TestPool/TestPoolModelLoader.cs +++ b/GraphLabs.Site.Models/TestPool/TestPoolModelLoader.cs @@ -26,7 +26,7 @@ public TestPoolModelLoader( /// Загрузить по сущности-прототипу public override TestPoolModel Load(DomainModel.TestPool testPool) { - Contract.Requires(testPool != null); + Guard.IsNotNull(nameof(TestPool), testPool); var array = testPool.TestPoolEntries.Select(a => new TestPoolEntryModel { diff --git a/GraphLabs.Site.Models/TestPoolEntry/TestPoolEntryModelLoader.cs b/GraphLabs.Site.Models/TestPoolEntry/TestPoolEntryModelLoader.cs index 9a568a4..2463ac2 100644 --- a/GraphLabs.Site.Models/TestPoolEntry/TestPoolEntryModelLoader.cs +++ b/GraphLabs.Site.Models/TestPoolEntry/TestPoolEntryModelLoader.cs @@ -27,7 +27,7 @@ IEntityQuery query /// Загрузить по сущности-прототипу public override TestPoolEntryModel Load(DomainModel.TestPoolEntry testPoolEntry) { - Contract.Requires(testPoolEntry != null); + Guard.IsNotNull(nameof(testPoolEntry), testPoolEntry); var model = new TestPoolEntryModel() { diff --git a/GraphLabs.Site.sln b/GraphLabs.Site.sln index 998866c..6fec885 100644 --- a/GraphLabs.Site.sln +++ b/GraphLabs.Site.sln @@ -41,6 +41,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GraphLabs.Tests.Site", "Gra EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GraphLabs.Tests.Site.Models", "GraphLabs.Tests.Site.Models\GraphLabs.Tests.Site.Models.csproj", "{47FC998C-4129-4D8B-A5DC-12D1288C788C}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GraphLabs.Guard", "GraphLabs.Guard\GraphLabs.Guard.csproj", "{D0A05AEF-DC7E-4B2B-A82A-9A23EAA0AF95}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GraphLabs.Tests.Guard", "UnitTestProject1\GraphLabs.Tests.Guard.csproj", "{D0089CEE-F5BC-45C8-84B9-448DA06F4EDE}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -277,6 +281,38 @@ Global {47FC998C-4129-4D8B-A5DC-12D1288C788C}.Release|x64.Build.0 = Release|Any CPU {47FC998C-4129-4D8B-A5DC-12D1288C788C}.Release|x86.ActiveCfg = Release|Any CPU {47FC998C-4129-4D8B-A5DC-12D1288C788C}.Release|x86.Build.0 = Release|Any CPU + {D0A05AEF-DC7E-4B2B-A82A-9A23EAA0AF95}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D0A05AEF-DC7E-4B2B-A82A-9A23EAA0AF95}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D0A05AEF-DC7E-4B2B-A82A-9A23EAA0AF95}.Debug|ARM.ActiveCfg = Debug|Any CPU + {D0A05AEF-DC7E-4B2B-A82A-9A23EAA0AF95}.Debug|ARM.Build.0 = Debug|Any CPU + {D0A05AEF-DC7E-4B2B-A82A-9A23EAA0AF95}.Debug|x64.ActiveCfg = Debug|Any CPU + {D0A05AEF-DC7E-4B2B-A82A-9A23EAA0AF95}.Debug|x64.Build.0 = Debug|Any CPU + {D0A05AEF-DC7E-4B2B-A82A-9A23EAA0AF95}.Debug|x86.ActiveCfg = Debug|Any CPU + {D0A05AEF-DC7E-4B2B-A82A-9A23EAA0AF95}.Debug|x86.Build.0 = Debug|Any CPU + {D0A05AEF-DC7E-4B2B-A82A-9A23EAA0AF95}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D0A05AEF-DC7E-4B2B-A82A-9A23EAA0AF95}.Release|Any CPU.Build.0 = Release|Any CPU + {D0A05AEF-DC7E-4B2B-A82A-9A23EAA0AF95}.Release|ARM.ActiveCfg = Release|Any CPU + {D0A05AEF-DC7E-4B2B-A82A-9A23EAA0AF95}.Release|ARM.Build.0 = Release|Any CPU + {D0A05AEF-DC7E-4B2B-A82A-9A23EAA0AF95}.Release|x64.ActiveCfg = Release|Any CPU + {D0A05AEF-DC7E-4B2B-A82A-9A23EAA0AF95}.Release|x64.Build.0 = Release|Any CPU + {D0A05AEF-DC7E-4B2B-A82A-9A23EAA0AF95}.Release|x86.ActiveCfg = Release|Any CPU + {D0A05AEF-DC7E-4B2B-A82A-9A23EAA0AF95}.Release|x86.Build.0 = Release|Any CPU + {D0089CEE-F5BC-45C8-84B9-448DA06F4EDE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D0089CEE-F5BC-45C8-84B9-448DA06F4EDE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D0089CEE-F5BC-45C8-84B9-448DA06F4EDE}.Debug|ARM.ActiveCfg = Debug|Any CPU + {D0089CEE-F5BC-45C8-84B9-448DA06F4EDE}.Debug|ARM.Build.0 = Debug|Any CPU + {D0089CEE-F5BC-45C8-84B9-448DA06F4EDE}.Debug|x64.ActiveCfg = Debug|Any CPU + {D0089CEE-F5BC-45C8-84B9-448DA06F4EDE}.Debug|x64.Build.0 = Debug|Any CPU + {D0089CEE-F5BC-45C8-84B9-448DA06F4EDE}.Debug|x86.ActiveCfg = Debug|Any CPU + {D0089CEE-F5BC-45C8-84B9-448DA06F4EDE}.Debug|x86.Build.0 = Debug|Any CPU + {D0089CEE-F5BC-45C8-84B9-448DA06F4EDE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D0089CEE-F5BC-45C8-84B9-448DA06F4EDE}.Release|Any CPU.Build.0 = Release|Any CPU + {D0089CEE-F5BC-45C8-84B9-448DA06F4EDE}.Release|ARM.ActiveCfg = Release|Any CPU + {D0089CEE-F5BC-45C8-84B9-448DA06F4EDE}.Release|ARM.Build.0 = Release|Any CPU + {D0089CEE-F5BC-45C8-84B9-448DA06F4EDE}.Release|x64.ActiveCfg = Release|Any CPU + {D0089CEE-F5BC-45C8-84B9-448DA06F4EDE}.Release|x64.Build.0 = Release|Any CPU + {D0089CEE-F5BC-45C8-84B9-448DA06F4EDE}.Release|x86.ActiveCfg = Release|Any CPU + {D0089CEE-F5BC-45C8-84B9-448DA06F4EDE}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -290,5 +326,7 @@ Global {406B1579-80A6-4C94-AC1D-3DAD87A12404} = {B67F78D5-C980-4F1E-8AD0-DD98594D2530} {7B12EB52-6778-405C-A644-48ACDC750296} = {4E833B0F-C7CB-425C-913D-13ED833B9F5A} {47FC998C-4129-4D8B-A5DC-12D1288C788C} = {4E833B0F-C7CB-425C-913D-13ED833B9F5A} + {D0A05AEF-DC7E-4B2B-A82A-9A23EAA0AF95} = {B67F78D5-C980-4F1E-8AD0-DD98594D2530} + {D0089CEE-F5BC-45C8-84B9-448DA06F4EDE} = {4E833B0F-C7CB-425C-913D-13ED833B9F5A} EndGlobalSection EndGlobal diff --git a/GraphLabs.Site/Controllers/Attributes/GLAuthorizeAttribute.cs b/GraphLabs.Site/Controllers/Attributes/GLAuthorizeAttribute.cs index ff3e667..4baad6f 100644 --- a/GraphLabs.Site/Controllers/Attributes/GLAuthorizeAttribute.cs +++ b/GraphLabs.Site/Controllers/Attributes/GLAuthorizeAttribute.cs @@ -24,7 +24,7 @@ public GLAuthorizeAttribute(params UserRole[] allowedRoles) /// Обрабатывает HTTP-запрос, не прошедший авторизацию. protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { - Contract.Assert(filterContext != null); + Guard.IsNotNull(nameof(filterContext), filterContext); var httpContext = filterContext.HttpContext; if (httpContext.User.Identity.IsAuthenticated) diff --git a/GraphLabs.Site/GraphLabs.Site.csproj b/GraphLabs.Site/GraphLabs.Site.csproj index 87f5730..c48952f 100644 --- a/GraphLabs.Site/GraphLabs.Site.csproj +++ b/GraphLabs.Site/GraphLabs.Site.csproj @@ -557,6 +557,10 @@ {3e515720-d0a1-4b01-a3e0-c82412b2d663} GraphLabs.DomainModel + + {d0a05aef-dc7e-4b2b-a82a-9a23eaa0af95} + GraphLabs.Guard + {d62cc3f4-3ea1-44ff-b9e2-492582788b3b} GraphLabs.Site.Core diff --git a/GraphLabs.Site/Models/TaskModel.cs b/GraphLabs.Site/Models/TaskModel.cs index dceb0de..9932b9a 100644 --- a/GraphLabs.Site/Models/TaskModel.cs +++ b/GraphLabs.Site/Models/TaskModel.cs @@ -56,7 +56,7 @@ public TaskModel() /// Ctor. public TaskModel(Task task, bool loadForTableView = false) { - Contract.Requires(task != null); + Guard.IsNotNull(nameof(task), task); Id = task.Id; Name = task.Name; diff --git a/GraphLabs.Site/Models/TaskVariantModel.cs b/GraphLabs.Site/Models/TaskVariantModel.cs index f797150..9c03b4e 100644 --- a/GraphLabs.Site/Models/TaskVariantModel.cs +++ b/GraphLabs.Site/Models/TaskVariantModel.cs @@ -28,7 +28,7 @@ public TaskVariantModel() /// Ctor. public TaskVariantModel(TaskVariant variant) { - Contract.Requires(variant != null); + Guard.IsNotNull(nameof(variant), variant); Id = variant.Id; Number = variant.Number; diff --git a/GraphLabs.Site/RequestUnitOfWork.cs b/GraphLabs.Site/RequestUnitOfWork.cs index 1051ca3..05fa598 100644 --- a/GraphLabs.Site/RequestUnitOfWork.cs +++ b/GraphLabs.Site/RequestUnitOfWork.cs @@ -28,7 +28,7 @@ private void OnRequestEnding() /// Успешное выполнение запроса public void OnRequestSuccess() { - Contract.Assert(Container != null, "Один из методов завершения запроса уже был вызван."); + Guard.IsTrueAssertion("Один из методов завершения запроса уже был вызван.",Container != null ); Container.Resolve().SaveChanges(); @@ -38,8 +38,7 @@ public void OnRequestSuccess() /// Ошибка при выполнении запроса public void OnRequestFailure() { - Contract.Assert(Container != null, "Один из методов завершения запроса уже был вызван."); - + Guard.IsTrueAssertion("Один из методов завершения запроса уже был вызван.", Container != null); OnRequestEnding(); } } diff --git a/GraphLabs.Tests.Guard/GraphLabs.Tests.Guard.csproj b/GraphLabs.Tests.Guard/GraphLabs.Tests.Guard.csproj new file mode 100644 index 0000000..fec79e9 --- /dev/null +++ b/GraphLabs.Tests.Guard/GraphLabs.Tests.Guard.csproj @@ -0,0 +1,54 @@ + + + + + Debug + AnyCPU + {EFFC3AA3-9708-4AAD-85BB-40C096614662} + Library + Properties + GraphLabs.Tests.Guard + GraphLabs.Tests.Guard + v4.5.2 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/GraphLabs.Tests.Guard/GuardTest.cs b/GraphLabs.Tests.Guard/GuardTest.cs new file mode 100644 index 0000000..1c6674b --- /dev/null +++ b/GraphLabs.Tests.Guard/GuardTest.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GraphLabs.Tests.Guard +{ + public class GuardTest + { + } +} diff --git a/GraphLabs.Tests.Guard/Properties/AssemblyInfo.cs b/GraphLabs.Tests.Guard/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..b2c20a3 --- /dev/null +++ b/GraphLabs.Tests.Guard/Properties/AssemblyInfo.cs @@ -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("GraphLabs.Tests.Guard")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("GraphLabs.Tests.Guard")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[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("effc3aa3-9708-4aad-85bb-40c096614662")] + +// 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")] diff --git a/GraphLabs.Utils/Extensions/EnumerableExtensions.cs b/GraphLabs.Utils/Extensions/EnumerableExtensions.cs index 6790a73..636390d 100644 --- a/GraphLabs.Utils/Extensions/EnumerableExtensions.cs +++ b/GraphLabs.Utils/Extensions/EnumerableExtensions.cs @@ -10,7 +10,7 @@ public static class EnumerableExtensions /// Сравнивает два списка, порядок элементов значения не имеет public static bool ContainsSameSet(this IEnumerable list1, IEnumerable list2) { - Contract.Requires(list1 != null && list2 != null); + Guard.IsTrueAssertion(list1 != null && list2 != null); if (list1.Count() != list2.Count()) { diff --git a/GraphLabs.Utils/GraphLabs.Site.Utils.csproj b/GraphLabs.Utils/GraphLabs.Site.Utils.csproj index 888cec5..4d547f9 100644 --- a/GraphLabs.Utils/GraphLabs.Site.Utils.csproj +++ b/GraphLabs.Utils/GraphLabs.Site.Utils.csproj @@ -171,6 +171,12 @@ + + + {d0a05aef-dc7e-4b2b-a82a-9a23eaa0af95} + GraphLabs.Guard + + cd "$(SolutionDir)" diff --git a/GraphLabs.Utils/IoC/IUnityRegistry.cs b/GraphLabs.Utils/IoC/IUnityRegistry.cs index 2dbb46e..3a51ead 100644 --- a/GraphLabs.Utils/IoC/IUnityRegistry.cs +++ b/GraphLabs.Utils/IoC/IUnityRegistry.cs @@ -6,21 +6,21 @@ namespace GraphLabs.Site.Utils.IoC { /// Реестр конфигурации Unity - [ContractClass(typeof(UnityRegistryContracts))] + // [ContractClass(typeof(UnityRegistryContracts))] public interface IUnityRegistry { /// Сконфигурировать void ConfigureContainer([NotNull]IUnityContainer container); } - /// Контракты для - [ContractClassFor(typeof(IUnityRegistry))] - abstract class UnityRegistryContracts : IUnityRegistry - { - /// Сконфигурировать - public void ConfigureContainer(IUnityContainer container) - { - Contract.Requires(container != null); - } - } + ///// Контракты для + //[ContractClassFor(typeof(IUnityRegistry))] + //abstract class UnityRegistryContracts : IUnityRegistry + //{ + // /// Сконфигурировать + // public void ConfigureContainer(IUnityContainer container) + // { + // Contract.Requires(container != null); + // } + //} } diff --git a/GraphLabs.Utils/Results/ResultMessage.cs b/GraphLabs.Utils/Results/ResultMessage.cs index c90acdd..c4e1062 100644 --- a/GraphLabs.Utils/Results/ResultMessage.cs +++ b/GraphLabs.Utils/Results/ResultMessage.cs @@ -61,7 +61,7 @@ private ResultMessage(string message, bool isFailure) /// Создает результат работы метода без ошибки, с информационным сообщением public static ResultMessage Info(string messageFormat, params object[] args) { - Contract.Requires(!string.IsNullOrWhiteSpace(messageFormat)); + Guard.IsNotNullOrWhiteSpace(messageFormat); return new ResultMessage(string.Format(messageFormat, args), false); } @@ -69,7 +69,7 @@ public static ResultMessage Info(string messageFormat, params object[] args) /// Создает результат работы метода с сообщением об ошибке public static ResultMessage Failure(string errorFormat, params object[] args) { - Contract.Requires(!string.IsNullOrWhiteSpace(errorFormat)); + Guard.IsNotNullOrWhiteSpace(errorFormat); return new ResultMessage(string.Format(errorFormat, args), true); } diff --git a/GraphLabs.Utils/Results/ResultOrError.cs b/GraphLabs.Utils/Results/ResultOrError.cs index 51f4a68..ddc101a 100644 --- a/GraphLabs.Utils/Results/ResultOrError.cs +++ b/GraphLabs.Utils/Results/ResultOrError.cs @@ -94,7 +94,7 @@ public static ResultOrError Success(TResult result) /// Создает результат работы метода с ошибкой public static ResultOrError Failure(string errorFormat, params object[] args) { - Contract.Requires(!string.IsNullOrWhiteSpace(errorFormat)); + Guard.IsNotNullOrWhiteSpace(errorFormat); return new ResultOrError(string.Format(errorFormat, args)); } diff --git a/GraphLabs.WcfServices/GraphLabs.WcfServices.csproj b/GraphLabs.WcfServices/GraphLabs.WcfServices.csproj index b14183b..b619e7f 100644 --- a/GraphLabs.WcfServices/GraphLabs.WcfServices.csproj +++ b/GraphLabs.WcfServices/GraphLabs.WcfServices.csproj @@ -251,6 +251,10 @@ {3e515720-d0a1-4b01-a3e0-c82412b2d663} GraphLabs.DomainModel + + {d0a05aef-dc7e-4b2b-a82a-9a23eaa0af95} + GraphLabs.Guard + {d62cc3f4-3ea1-44ff-b9e2-492582788b3b} GraphLabs.Site.Core diff --git a/GraphLabs.WcfServices/Infrastructure/WcfRegistry.cs b/GraphLabs.WcfServices/Infrastructure/WcfRegistry.cs index 3fe340c..e744682 100644 --- a/GraphLabs.WcfServices/Infrastructure/WcfRegistry.cs +++ b/GraphLabs.WcfServices/Infrastructure/WcfRegistry.cs @@ -15,6 +15,7 @@ sealed class WcfRegistry : IUnityRegistry /// Сконфигурировать public void ConfigureContainer(IUnityContainer container) { + Guard.IsNotNull(nameof(container), container); container.RegisterInstance(CreateMapper()); container.RegisterType(); container.RegisterType(); diff --git a/GraphLabs.WcfServices/VariantGenService.svc.cs b/GraphLabs.WcfServices/VariantGenService.svc.cs index caf0705..f75b184 100644 --- a/GraphLabs.WcfServices/VariantGenService.svc.cs +++ b/GraphLabs.WcfServices/VariantGenService.svc.cs @@ -28,15 +28,13 @@ public VariantGenService(IOperationContextFactory operationFa /// Id варианта public TaskVariantDto GetVariant(long id) { - Contract.Assume(Contract.Result() != null); - using (var op = _operationFactory.Create()) { var variant = op.DataContext.Query.Find(id); if (variant == null) throw new ArgumentException("Вариант с указанным Id не найден."); - return new TaskVariantDto + TaskVariantDto taskVariantDto = new TaskVariantDto { Data = variant.Data, GeneratorVersion = variant.GeneratorVersion, @@ -44,6 +42,9 @@ public TaskVariantDto GetVariant(long id) Version = variant.Version, Id = variant.Id }; + + Guard.IsNotNull(taskVariantDto); + return taskVariantDto; } } diff --git a/UnitTestProject1/GraphLabs.Tests.Guard.csproj b/UnitTestProject1/GraphLabs.Tests.Guard.csproj new file mode 100644 index 0000000..136e8c8 --- /dev/null +++ b/UnitTestProject1/GraphLabs.Tests.Guard.csproj @@ -0,0 +1,89 @@ + + + + Debug + AnyCPU + {D0089CEE-F5BC-45C8-84B9-448DA06F4EDE} + Library + Properties + UnitTestProject1 + UnitTestProject1 + v4.5.2 + 512 + {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + 10.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages + False + UnitTest + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + {d0a05aef-dc7e-4b2b-a82a-9a23eaa0af95} + GraphLabs.Guard + + + + + + + False + + + False + + + False + + + False + + + + + + + + \ No newline at end of file diff --git a/UnitTestProject1/Properties/AssemblyInfo.cs b/UnitTestProject1/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..755c33e --- /dev/null +++ b/UnitTestProject1/Properties/AssemblyInfo.cs @@ -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("UnitTestProject1")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("UnitTestProject1")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[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("d0089cee-f5bc-45c8-84b9-448da06f4ede")] + +// 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")] diff --git a/UnitTestProject1/UnitTestGuard.cs b/UnitTestProject1/UnitTestGuard.cs new file mode 100644 index 0000000..8e66611 --- /dev/null +++ b/UnitTestProject1/UnitTestGuard.cs @@ -0,0 +1,203 @@ +using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using GraphLabs; +using System.Collections.Generic; + +namespace UnitTestProject1 +{ + [TestClass] + public class UnitTestGuard + { + private class A { } + private class B : A { }; + private class C { }; + [TestMethod] + public void TestMethodIsNotNull() + { + List a = new List() { 1, 2, 3 }; + Guard.IsNotNull(a); + + Exception exception = null; + List b = null; + try + { + Guard.IsNotNull(b); + } + catch (Exception ex) + { + exception = ex; + } + Assert.IsNotNull(exception); + } + + [TestMethod] + public void TestAreAssignedTypes() + { + Guard.AreAssignedTypes(typeof(A), typeof(B)); + Exception exception = null; + try + { + Guard.AreAssignedTypes(typeof(B), typeof(A)); + } + catch (Exception ex) + { + exception = ex; + } + Assert.IsNotNull(exception); + + exception = null; + try + { + Guard.AreAssignedTypes(typeof(C), typeof(A)); + } + catch (Exception ex) + { + exception = ex; + } + Assert.IsNotNull(exception); + + } + + [TestMethod] + public void TestAreEqual() + { + String str1 = "a"; + String str2 = "a"; + String str3 = "b"; + + Guard.AreEqual(str1, str2, nameof(str1), nameof(str2)); + Exception exception = null; + try + { + Guard.AreEqual(str1, str3, nameof(str1), nameof(str3)); + } + catch (Exception ex) + { + exception = ex; + } + Assert.IsNotNull(exception); + } + + [TestMethod] + public void TestIsNotNullOrWhiteSpace() + { + String str1 = "a"; + String str2 = ""; + String str3 = " "; + String str4 = null; + + Guard.IsNotNullOrWhiteSpace(str1); + Exception exception = null; + try + { + Guard.IsNotNullOrWhiteSpace(str2); + } + catch (Exception ex) + { + exception = ex; + } + Assert.IsNotNull(exception); + + exception = null; + try + { + Guard.IsNotNullOrWhiteSpace(str3); + } + catch (Exception ex) + { + exception = ex; + } + Assert.IsNotNull(exception); + + exception = null; + try + { + Guard.IsNotNullOrWhiteSpace(str4); + } + catch (Exception ex) + { + exception = ex; + } + Assert.IsNotNull(exception); + + } + + [TestMethod] + public void TestIsIsPositive() + { + int intp = 5; + int intn = -1; + long longp = 10; + long longn = -3; + + Guard.IsPositive(intp, nameof(intp)); + Guard.IsPositive(longp, nameof(longp)); + + Exception exception = null; + try + { + Guard.IsPositive(intn, nameof(intn)); + } + catch (Exception ex) + { + exception = ex; + } + Assert.IsNotNull(exception); + + exception = null; + try + { + Guard.IsPositive(longn, nameof(longn)); + } + catch (Exception ex) + { + exception = ex; + } + Assert.IsNotNull(exception); + + } + + + [TestMethod] + public void TestIsNotEmpty() + { + String str1 = "a"; + String str2 = null; + String str3 = ""; + + Guard.IsNotEmpty(str1, nameof(str1)); + Guard.IsNotEmpty(str1, nameof(str1)); + + Exception exception = null; + try + { + Guard.IsNotEmpty(str3, nameof(str3)); + } + catch (Exception ex) + { + exception = ex; + } + Assert.IsNotNull(exception); + + } + + [TestMethod] + public void TestIsTrueAssertion() + { + bool a = true; + bool b = false; + + Guard.IsTrueAssertion(a); + Exception exception = null; + try + { + Guard.IsTrueAssertion(b); + } + catch (Exception ex) + { + exception = ex; + } + Assert.IsNotNull(exception); + } + } +}