|
Рисунок 43 – Страница изменения товара |
|
Рисунок 44 – Страница изменения товара |
|
Рисунок 45 – Страница изменения товара |
|
Рисунок 46 – Страница изменения товара |
В разделе «Лог работы» администратор просматривает все ошибки, происходящие в процессе работы интернет-магазина (см. рис. 47).
|
Рисунок 47 – Страница ошибок работы интернет-магазина |
4. Тестирование разработанного приложения в различных браузерах
Для проверки корректности оторбражения содержимого страниц было проведено тестирование в браузерах Interner Explorer 11, Mozilla Firefox и Opera (см. рис. 48, 49, 50).
|
Рисунок 48 – Страница зарегистрированного пользователя в браузере Internet Explorer |
|
Рисунок 49 – Страница зарегистрированного пользователя в браузере Mozilla Firefox |
|
Рисунок 50 – Страница зарегистрированного пользователя в браузере Opera |
Тестирование показало, что во всех браузерах элементы страницы отображаются одинаково как по форме, размерам, цвету, так и расположению всех элементов относительно друг друга.
Заключение
Целью бакалаврской работы была разработка веб-приложения по организации работы интернет-магазина по продаже компьютерной техники.
Использование объектно-ориентированного программирования позволяет легко дополнить данное приложение дополнительным функционалом, необходимым для заказчика.
Примененная трехуровневая схема доступа к данным позволяет с легкостью интегрировать данное приложение с программами ведения бухгалтерского учета, например «1С», а также организовать безналичную форму оплаты покупки с использованием различных платежных систем.
Была определена структура базы данных: все таблицы были составлены таким образом, чтобы можно было избежать избыточности, и чтобы они соответствовали требованиям приложения. Также была определена структура самой системы, которая отвечает таким качествам как: удобство использования, производительность.
В результате было разработано приложение, которое отвечает всем требованиям и задачами, которые были поставлены ранее. Процесс выполнения бакалаврской работы позволил укрепить практические навыки разработки, а также приобрести ценные знания в области реализации программного обеспечения.
Список использованных источников
HTML и XHTML. Подробное руководство. – Пер. с англ. – Муссиано Ч., Кеннеди Б. – 2003. – 752 с. Web-программирование на Java и JavaScript. – , – 2002. – 1040 с. JavaScript и jQuery. Исчерпывающее руководство – – – 2015. – 880 с. Microsoft 3.5 с примерами на C# 2008 для профессионалов. 2-е изд./ Мак-Дональд М., Шпушта М. – 2008. – 1424 с. MVC 3 Framework с примерами на C# для профессионалов. 3-е изд./ Фримен А., Сандерсон С. – 2012. – 672 с. Информационные системы и базы данных. Организация и проектирование – – 2009. – 528 с. Bootstrap 3 на русском / - Режим доступа: http://bootstrap-3.ru/, свободный – Загл. с экрана, - Яз. Русский Ninject - Open source dependency injector / - Режим доступа: http://www. ninject. org/, свободный – Загл. с экрана, - Яз. Английский Основы HTML5: Часть 1. - Приступая к работе - Режим доступа: http://www. /, свободный – Загл. с экрана, - Яз. Русский Библиографическое описание документа. Общие требования и правила составления: ГОСТ 7.1.84. – Введ. 01.01.86. – М., 1984. –75 с. – (Система стандартов по информ., библ. и изд. Делу).
Приложение «Листинг программы»
Листинг 1 - Код класса Brend |
using ponentModel. DataAnnotations; using ponentModel. DataAnnotations. Schema; namespace Shop. Domain. DAL { /// <summary> /// Производитель /// </summary> [Table("Brends")] public class Brend { [Key] public int BrendID { get; set; } /// <summary> /// Наименование производителя /// </summary> [Required] public string BrendName { get; set; } } } |
Листинг 2 - Код класса Category |
using ponentModel. DataAnnotations; using ponentModel. DataAnnotations. Schema; namespace Shop. Domain. DAL { /// <summary> /// Категория товара /// </summary> [Table("Categories")] public partial class Category { [Key] public int CategoryID { get; set; } /// <summary> /// Наименование категории /// </summary> [Required] public string CategoryName { get; set; } /// <summary> /// Идентификатор изображения в таблице Images /// </summary> public int ImageID { get; set; } } } |
Листинг 3 - Код класса Image |
using ponentModel. DataAnnotations; using ponentModel. DataAnnotations. Schema; namespace Shop. Domain. DAL { /// <summary> /// Картинки /// </summary> [Table("Images")] public class Image { [Key] public int ImageID { get; set; } /// <summary> /// Наименование производителя /// </summary> [Required] public byte[] ImageData { get; set; } } } |
Листинг 4 - Код класса Log |
using System; using System. Collections. Generic; using System. Linq; using System. Text; using ponentModel. DataAnnotations; using ponentModel. DataAnnotations. Schema; namespace Shop. Domain. DAL { [Table("Logs")] public class Log { public Log() { } /// <summary> /// Создает экземпляр записи в журнале документов /// </summary> /// <param name="message">текст сообщения</param> public Log(string message) { this. Message = message; this. CreatedAt = DateTime. Now; } [Key] [Display(Name = "Идентификатор")] public int Id { get; set; } /// <summary> /// Текст сообщения /// </summary> [Required] [Display(Name = "Текст сообщения о событии")] [StringLength(1000)] public string Message { get; private set; } /// <summary> /// Дата выполнения операции /// </summary> [Required] [Display(Name = "Дата события")] public DateTime CreatedAt { get; private set; } /// <summary> /// Имя пользователя /// </summary> [Required] [Display(Name = "Автор")] [StringLength(50)] public string UserName { get; set; } } } |
Листинг 5 - Код класса Order |
using System; using System. Collections. Generic; using ponentModel. DataAnnotations; using ponentModel. DataAnnotations. Schema; namespace Shop. Domain. DAL { /// <summary> /// Заказ /// </summary> [Table("Orders")] public partial class Order { public Order() { this. OrderItems = new List<OrderItem>(); } [Key] public int OrderID { get; set; } /// <summary> /// Идентификатор покупателя /// </summary> [Required] public int UserID { get; set; } public virtual User User { get; set; } /// <summary> /// Дата заказа /// </summary> [Required] public DateTime AddDate { get; set; } /// <summary> /// Дата заказа /// </summary> public string DeliveryAddress { get; set; } /// <summary> /// Дата исполнения заказа /// </summary> public DateTime? ExecuteDate { get; set; } /// <summary> /// Идентификатор исполнителя заказа /// </summary> [Required] public int ManagerID { get; set; } public virtual ICollection<OrderItem> OrderItems { get; set; } /// <summary> /// Идентификатор курьера /// </summary> [Required] public int CourierID { get; set; } /// <summary> /// Дата доставки /// </summary> public DateTime? DeliveryDate { get; set; } } public partial class Order { private readonly ShopDbDataContext context = new ShopDbDataContext(); /// <summary> /// Фамилия Имя Отчество исполнителя заказа /// </summary> public string ManagerName { get { string result = ""; if (this. ManagerID!= 0) { User user = context. Users. Find(this. ManagerID); result = rName + " " + user. FirstName + " " + user. LastName; } return result; } } /// <summary> /// Телефон менеджера /// </summary> public string ManagerPhone { get { string result = ""; if (this. ManagerID!= 0) { User user = context. Users. Find(this. ManagerID); result = user. Phone; } return result; } } /// <summary> /// Фамилия Имя Отчество курьера /// </summary> public string CourierName { get { string result = ""; if (this. CourierID!= 0) { User user = context. Users. Find(this. CourierID); result = rName + " " + user. FirstName + " " + user. LastName; } return result; } } /// <summary> /// Телефон курьера /// </summary> public string CourierPhone { get { string result = ""; if (this. CourierID!= 0) { User user = context. Users. Find(this. CourierID); result = user. Phone; } return result; } } } } |
Листинг 6 - Код класса OrderItem |
using System; using ponentModel. DataAnnotations; using ponentModel. DataAnnotations. Schema; namespace Shop. Domain. DAL { /// <summary> /// Заказанный товар /// </summary> [Table("OrderItems")] public class OrderItem { [Key] public int OrderItemID { get; set; } /// <summary> /// Идентификатор заказа /// </summary> [Required] public int OrderID { get; set; } public virtual Order Order { get; set; } /// <summary> /// Идентификатор товара /// </summary> [Required] public int ProductID { get; set; } public virtual Product Product { get; set; } /// <summary> /// Количество товара /// </summary> [Required] public int Quantity { get; set; } } } |
Листинг 7 - Код класса Product |
using System. Collections. Generic; using ponentModel. DataAnnotations; using ponentModel. DataAnnotations. Schema; using System. Linq; namespace Shop. Domain. DAL { /// <summary> /// Товара /// </summary> [Table("Products")] public partial class Product { public Product() { this. ProductLocations = new List<ProductLocation>(); } [Key] public int ProductID { get; set; } /// <summary> /// Идентификатор категории /// </summary> [Required] public int CategoryID { get; set; } public virtual Category Category { get; set; } /// <summary> /// Идентификатор бренда /// </summary> [Required] public int BrendID { get; set; } public virtual Brend Brend { get; set; } /// <summary> /// Модель /// </summary> [Required] public string Model { get; set; } /// <summary> /// Цена /// </summary> [Required] public decimal Price { get; set; } public int ImageID { get; set; } public virtual ICollection<ProductLocation> ProductLocations { get; set; } } public partial class Product { private readonly ShopDbDataContext context = new ShopDbDataContext(); /// <summary> /// Количество товара /// </summary> public int SumProduct { get { int result = 0; IQueryable<ProductLocation> collection = context. ProductLocations. Where(p => p. ProductID == this. ProductID); if (collection. Any()) { result = m(p => p. Quantity); } return result; } } /// <summary> /// Количество отзывов о товаре /// </summary> public int RewiewCount { get { return context. Reviews. Where(p => p. ProductID == this. ProductID).Count(); } } } } |
Листинг 8 - Код класса ProductLocation |
using ponentModel. DataAnnotations; using ponentModel. DataAnnotations. Schema; namespace Shop. Domain. DAL { /// <summary> /// Склад /// </summary> [Table("ProductLocations")] public class ProductLocation { public ProductLocation() { } [Key] public int ProductLocationID { get; set; } /// <summary> /// Идентификатор категории /// </summary> [Required] public int StorageID { get; set; } public virtual Storage Storage { get; set; } /// <summary> /// Идентификатор товара /// </summary> [Required] public int ProductID { get; set; } public virtual Product Product { get; set; } /// <summary> /// Количество товара /// </summary> [Required] public int Quantity { get; set; } } } |
Листинг 9 - Код класса Review |
using System; using ponentModel. DataAnnotations; using ponentModel. DataAnnotations. Schema; namespace Shop. Domain. DAL { /// <summary> /// Отзыв о товаре /// </summary> [Table("Reviews")] public class Review { [Key] public int ReviewID { get; set; } public DateTime DateCreate { get; set; } /// <summary> /// Идентификатор товара /// </summary> public int ProductID { get; set; } public virtual Product Product { get; set; } /// <summary> /// Идентификатор пользователя /// </summary> public int UserID { get; set; } public virtual User User { get; set; } /// <summary> /// Текст отзыва /// </summary> [Required] public string Message { get; set; } } } |
Листинг 10 - Код класса Role |
using System; using System. Collections. Generic; using ponentModel. DataAnnotations; using ponentModel. DataAnnotations. Schema; namespace Shop. Domain. DAL { /// <summary> /// Роль /// </summary> [Table("Roles")] public class Role { public Role() { this. UserInRoles = new List<UserInRole>(); } [Key] public int RoleID { get; set; } /// <summary> /// Наименование роли /// </summary> [Required] public string RoleName { get; set; } /// <summary> /// Дата создания /// </summary> public DateTime DateCreated { get; set; } public virtual ICollection<UserInRole> UserInRoles { get; set; } } } |
Листинг 11 - Код класса Storage |
using System. Collections. Generic; using ponentModel. DataAnnotations; using ponentModel. DataAnnotations. Schema; namespace Shop. Domain. DAL { /// <summary> /// Склад /// </summary> [Table("Storages")] public class Storage { public Storage() { this. ProductLocations = new List<ProductLocation>(); } [Key] public int StorageID { get; set; } /// <summary> /// Название склада /// </summary> [Required] public string Name { get; set; } /// <summary> /// Адрес склада /// </summary> [Required] public string Adress { get; set; } /// <summary> /// Адрес склада /// </summary> [Required] public string Phone { get; set; } public virtual ICollection<ProductLocation> ProductLocations { get; set; } } } |
Листинг 12 - Код класса User |
using System; using System. Collections. Generic; using ponentModel. DataAnnotations; using ponentModel. DataAnnotations. Schema; using System. Linq; namespace Shop. Domain. DAL { /// <summary> /// Клиент сайта /// </summary> [Table("Users")] public partial class User { public User() { this. UserInRoles = new List<UserInRole>(); } [Key] public int UserID { get; set; } /// <summary> /// Почта /// </summary> [Required] public string Email { get; set; } /// <summary> /// Пароль покупателя /// </summary> [Required] public string PasswordHash { get; set; } /// <summary> /// Номер телефона /// </summary> public string Phone { get; set; } /// <summary> /// Имя покупателя /// </summary> [Required] public string FirstName { get; set; } /// <summary> /// Отчество покупателя /// </summary> public string LastName { get; set; } /// <summary> /// Фамилия /// </summary> public string SurName { get; set; } /// <summary> /// Статус покупателя /// </summary> public bool Status { get; set; } /// <summary> /// Дата регистрации /// </summary> [Required] public DateTime DateRegistred { get; set; } /// <summary> /// Дата изменения /// </summary> [Required] public DateTime DateModified { get; set; } public virtual ICollection<UserInRole> UserInRoles { get; set; } } public partial class User { private readonly ShopDbDataContext context = new ShopDbDataContext(); ///// <summary> ///// Проверка присутствия пользователя в роли ///// </summary> ///// <param name="roles"></param> public bool InRoles(string roles) { if (string. IsNullOrWhiteSpace(roles)) { return false; } var rolesArray = roles. Split(new[] { "," }, StringSplitOptions. RemoveEmptyEntries); foreach (var role in rolesArray) { int roleId = context. Roles. FirstOrDefault(p => p. RoleName == role).RoleID; int hasRole = context. UserInRoles. Where(p => p. RoleID == roleId & p. UserID == this. UserID).Count(); if (hasRole == 1) { return true; } } return false; } /// <summary> /// ФИО /// </summary> /// <returns></returns> public string UserFullName { get { return rName + " " + this. FirstName + " " + this. LastName; } } } } |
Листинг 13 - Код класса UserInRole |
using ponentModel. DataAnnotations; using ponentModel. DataAnnotations. Schema; namespace Shop. Domain. DAL { /// <summary> /// Роли пользователя /// </summary> [Table("UserInRoles")] public partial class UserInRole { [Key] public int UserInRoleID { get; set; } /// <summary> /// Идентификатор пользователя /// </summary> [Required] public int UserID { get; set; } public virtual User User { get; set; } /// <summary> /// Идентификатор роли /// </summary> [Required] public int RoleID { get; set; } public virtual Role Role { get; set; } } } |
Листинг 14 - Код класса ShopDbDataContext |
using Shop. Domain. DAL; using System. Data. Entity; namespace Shop. Domain { /// <summary> /// Контекст данных /// </summary> public class ShopDbDataContext : DbContext { //Доступ public DbSet<User> Users { get; set; } public DbSet<Role> Roles { get; set; } public DbSet<UserInRole> UserInRoles { get; set; } public DbSet<Log> Logs { get; set; } // Товар public DbSet<Storage> Storages { get; set; } public DbSet<Product> Products { get; set; } public DbSet<ProductLocation> ProductLocations { get; set; } public DbSet<Review> Reviews { get; set; } //Заказ public DbSet<Order> Orders { get; set; } public DbSet<OrderItem> OrderItems { get; set; } //Справочники public DbSet<Brend> Brends { get; set; } public DbSet<Category> Categories { get; set; } //Изображения public DbSet<Image> Images { get; set; } } } |
Листинг 15 - Код класса IBaseRepository |
using System; using System. Collections. Generic; using System. Data. Entity; using System. Data. Entity. Validation; using System. Linq; using System. Linq. Expressions; namespace Shop. Domain. Repositories { /// <summary> /// Базовый интерфейс /// </summary> public interface IBaseRepository<T> { ICollection<T> All { get; } IQueryable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties); T Find(int id); void Insert(T entity); void Update(T entity); void Delete(int id); void Save(); } public class SqlBaseRepository<T> : IBaseRepository<T> where T : class { private readonly ShopDbDataContext context = new ShopDbDataContext(); private DbSet<T> _dbSet; public SqlBaseRepository() { this._dbSet = context. Set<T>(); } public virtual ICollection<T> All { get { return _dbSet. ToList(); } } public virtual IQueryable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties) { IQueryable<T> query = _dbSet; foreach (var includeProperty in includeProperties) { query = query. Include(includeProperty); } return query; } public virtual T Find(int id) { return _dbSet. Find(id); } public virtual void Insert(T entity) { _dbSet. Add(entity); } public virtual void Update(T entity) { _dbSet. Attach(entity); context. Entry(entity).State = EntityState. Modified; } public virtual void Delete(int id) { var entity = _dbSet. Find(id); _dbSet. Remove(entity); } public virtual void Save() { context. SaveChanges(); } } } |
Листинг 16 - Код класса NinjectWebCommon |
[assembly: WebActivatorEx. PreApplicationStartMethod(typeof(ShopWeb. App_Start. NinjectWebCommon), "Start")] [assembly: WebActivatorEx. ApplicationShutdownMethodAttribute(typeof(ShopWeb. App_Start. NinjectWebCommon), "Stop")] namespace ShopWeb. App_Start { using System; using System. Web; using Microsoft. Web. Infrastructure. DynamicModuleHelper; using Ninject; using Ninject. mon; using Shop. Domain. Repositories; using Shop. Domain; using System. Configuration; using ShopWeb. Global. Auth; public static class NinjectWebCommon { private static readonly Bootstrapper bootstrapper = new Bootstrapper(); /// <summary> /// Starts the application /// </summary> public static void Start() { DynamicModuleUtility. RegisterModule(typeof(OnePerRequestHttpModule)); DynamicModuleUtility. RegisterModule(typeof(NinjectHttpModule)); bootstrapper. Initialize(CreateKernel); } /// <summary> /// Stops the application. /// </summary> public static void Stop() { bootstrapper. ShutDown(); } /// <summary> /// Creates the kernel that will manage your application. /// </summary> /// <returns>The created kernel.</returns> private static IKernel CreateKernel() { var kernel = new StandardKernel(); try { kernel. Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel); kernel. Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); RegisterServices(kernel); return kernel; } catch { kernel. Dispose(); throw; } } /// <summary> /// Загрузка модулей и регистрация интерфейсов /// </summary> private static void RegisterServices(IKernel kernel) { //Аутефикация kernel. Bind<IAuthentication>().To<CustomAuthentication>().InRequestScope(); //Базовый интерфейс kernel. Bind(typeof(IBaseRepository<>)).To(typeof(SqlBaseRepository<>)).InRequestScope(); } } } |
Листинг 17 - Текст конфигурационного файла Web. config |
<?xml version="1.0" encoding="utf-8"?> <!-- Дополнительные сведения по настройке приложения см. по ссылке http://go. /fwlink/?LinkId=169433 --> <configuration> <configSections> <section name="entityFramework" type="System. Data. Entity. Internal. ConfigFile. EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> <!-- For more information on Entity Framework configuration, visit http://go. /fwlink/?LinkID=237468 --> </configSections> <connectionStrings> <add name="ShopDbDataContext" providerName="System. Data. SqlClient" connectionString="Data Source=(local);Initial Catalog=ShopDB; Persist Security Info = True;User ID=sa;Password=6233; Connect Timeout=3000; pooling='true'; Max Pool Size=200"/> </connectionStrings> <appSettings> <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /> <add key="webpages:Version" value="2.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="PreserveLoginUrl" value="true" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> <add key="Culture" value="ru" /> </appSettings> <system. web> <compilation debug="true" targetFramework="4.0" /> <authentication mode="Forms"> <forms loginUrl="~/Home/Login" timeout="2880" slidingExpiration="true" /> </authentication> <pages> <namespaces> <add namespace="System. Web. Helpers" /> <add namespace="System. Web. Mvc" /> <add namespace="System. Web. Mvc. Ajax" /> <add namespace="System. Web. Mvc. Html" /> <add namespace="System. Web. Optimization" /> <add namespace="System. Web. Routing" /> <add namespace="System. Web. WebPages" /> <add namespace="Shop. Domain" /> </namespaces> </pages> <httpModules> <add name="AuthHttpModule" type="ShopWeb. Global. Auth. AuthHttpModule" /> </httpModules> </system. web> <system. webServer> <modules runAllManagedModulesForAllRequests="true" > <add name="AuthHttpModule" type="ShopWeb. Global. Auth. AuthHttpModule" /> </modules> <validation validateIntegratedModeConfiguration="false" /> <handlers> <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" /> <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" /> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET, HEAD, POST, DEBUG, PUT, DELETE, PATCH, OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\\Framework\v4.0.30319\aspnet_isapi. dll" preCondition="classicMode, runtimeVersionv4.0,bitness32" responseBufferLimit="0" /> <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET, HEAD, POST, DEBUG, PUT, DELETE, PATCH, OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\\Framework64\v4.0.30319\aspnet_isapi. dll" preCondition="classicMode, runtimeVersionv4.0,bitness64" responseBufferLimit="0" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET, HEAD, POST, DEBUG, PUT, DELETE, PATCH, OPTIONS" type="System. Web. Handlers. TransferRequestHandler" preCondition="integratedMode, runtimeVersionv4.0" /> </handlers> </system. webServer> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm. v1"> <dependentAssembly> <assemblyIdentity name="DotNetOpenAuth. Core" publicKeyToken="2780ccd10d57b246" /> <bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="DotNetOpenAuth. AspNet" publicKeyToken="2780ccd10d57b246" /> <bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System. Web. Helpers" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System. Web. Mvc" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System. Web. WebPages" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="0.0.0.0-1.3.0.0" newVersion="1.3.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-4.4.0.0" newVersion="4.4.0.0" /> </dependentAssembly> </assemblyBinding> </runtime> <entityFramework> <defaultConnectionFactory type="System. Data. Entity. Infrastructure. LocalDbConnectionFactory, EntityFramework"> <parameters> <parameter value="v11.0" /> </parameters> </defaultConnectionFactory> <providers> <provider invariantName="System. Data. SqlClient" type="System. Data. Entity. SqlServer. SqlProviderServices, EntityFramework. SqlServer" /> </providers> </entityFramework> </configuration> |
Листинг 18 - Код класса BaseController |
namespace ShopWeb. Controllers { public class BaseController : Controller { public static string HostName = string. Empty; /// <summary> /// Интерфейс лога работы /// </summary> [Inject] public IBaseRepository<Log> LogRepository { get; set; } #region Аутенфикация /// <summary> /// Интерфейс пользователя /// </summary> [Inject] public IBaseRepository<User> UserRepository { get; set; } /// <summary> /// Интерфейс роли /// </summary> [Inject] public IBaseRepository<Role> RoleRepository { get; set; } /// <summary> /// Интерфейс списка ролей пользователя /// </summary> [Inject] public IBaseRepository<UserInRole> UserInRoleRepository { get; set; } [Inject] public IAuthentication Auth { get; set; } public User CurrentUser { get { return ((IUserProvider)Auth. CurrentUser. Identity).User; } } #endregion Аутенфикация #region Товар /// <summary> /// Интерфейс склада /// </summary> [Inject] public IBaseRepository<Storage> StorageRepository { get; set; } /// <summary> /// Интерфейс товара /// </summary> [Inject] public IBaseRepository<Product> ProductRepository { get; set; } /// <summary> /// Интерфейс отзывов /// </summary> [Inject] public IBaseRepository<Review> ReviewRepository { get; set; } /// <summary> /// Интерфейс местонахождения склада /// </summary> [Inject] public IBaseRepository<ProductLocation> ProductLocationRepository { get; set; } /// <summary> /// Интерфейс заказа /// </summary> [Inject] public IBaseRepository<Order> OrderRepository { get; set; } /// <summary> /// Интерфейс товара в заказе /// </summary> [Inject] public IBaseRepository<OrderItem> OrderItemRepository { get; set; } /// <summary> /// Интерфейс категории /// </summary> [Inject] public IBaseRepository<Category> CategoryRepository { get; set; } /// <summary> /// Интерфейс бренда /// </summary> [Inject] public IBaseRepository<Brend> BrendRepository { get; set; } /// <summary> /// Интерфейс изображения /// </summary> [Inject] public IBaseRepository<Image> ImageRepository { get; set; } //Извлечение изображения public FileContentResult GetImageRead(int id) { Image img = ImageRepository. Find(id); if (img!= null) { return File(img. ImageData, "image/img"); } else { return null; } } /// <summary> /// autocomplete модель товара /// </summary> [HttpPost] public JsonResult AutocompleteModelName(string keyword) { if (keyword!= null & keyword. Length > 2) { var result = ProductRepository. All. Where(x => x. Model. ToLower().Contains(keyword. ToLower())) .Select(x => new { keyword = x. Model }).Distinct().ToArray(); return Json(result, JsonRequestBehavior. AllowGet); } else { return null; } } #endregion protected override void Initialize(System. Web. Routing. RequestContext requestContext) { if (requestContext. HttpContext. Request. Url!= null) { HostName = requestContext. HttpContext. Request. Url. Authority; } base. Initialize(requestContext); } } } |
Листинг 19 - Код класса HomeController |
namespace ShopWeb. Controllers { [HandleError] public class HomeController : BaseController { public int pageSize = 3; public ActionResult Index() { if (Request. IsAuthenticated) { User user = UserRepository. Find(CurrentUser. UserID); if (rName == null || user. LastName == null || user. Phone == null) { return RedirectToAction("ProfileEdit", "Home"); } else { //Добавление списка категории товара IEnumerable<CategoryViewModel> vm = CategoryRepository. All. ToViewModels(); return View(vm); } } else { //Добавление списка категории товара IEnumerable<CategoryViewModel> vm = CategoryRepository. All. ToViewModels(); return View(vm); } } public ActionResult About() { return View(); } #region Вход [HttpGet] public ActionResult Login(string ReturnUrl) { LoginModel vm = new LoginModel(); vm. ReturnUrl = ReturnUrl; return View(vm); } [HttpPost] public ActionResult Login(LoginModel vm) { if (ModelState. IsValid) { var user = Auth. Login(vm. UserName, Crypto. Hash(vm. Password)); if (user!= null) { if (user. Status == true) { if (vm. ReturnUrl == null) { return RedirectToAction("Index", "Home"); } else { return Redirect(vm. ReturnUrl); } } else { ModelState["Password"].Errors. Add("Ваша учетная запись заблокирована"); return View(vm); } } else { ModelState["Password"].Errors. Add("Отказано в доступе"); return View(vm); } } else { return View(vm); } } //Выход из системы public ActionResult LogOut() { Auth. LogOut(); return RedirectToAction("Index", "Home"); } #endregion Вход #region Регистрация [HttpGet] public ActionResult Register(string ReturnUrl) { RegisterModel vm = new RegisterModel(); return View(vm); } [HttpPost] public ActionResult Register(RegisterModel vm) { if (UserRepository. All. Where(p => p. Email. ToLower().Trim() == vm. Email. ToLower().Trim()) != null) { ModelState["Email"].Errors. Add("Такой Email уже существует"); } if (ModelState. IsValid) { User context = new User(); context. FirstName = vm. FirstName. Trim(); context. Email = vm. Email. Trim(); context. PasswordHash = Crypto. Hash(vm. Password. Trim()); context. Status = true; context. DateRegistred = DateTime. Now; context. DateModified = DateTime. Now; UserRepository. Insert(context); UserRepository. Save(); UserInRole ur = new UserInRole(); ur. UserID = context. UserID; ur. RoleID = 3; UserInRoleRepository. Insert(ur); UserInRoleRepository. Save(); var user = Auth. Login(vm. Email, Crypto. Hash(vm. Password)); if (user!= null) { return RedirectToAction("Index", "Home"); } else { return View(vm); } } else { return View(vm); } } #endregion Регистрация #region Профиль /// <summary> /// Редактирование профиля /// </summary> [Authorize] [HttpGet] public ActionResult ProfileEdit() { User user = UserRepository. Find(CurrentUser. UserID); if (user == null) throw new HttpException(404, "Страница не найдена"); ProfileEditModel vm = new ProfileEditModel(user); return View(vm); } [HttpPost] public ActionResult ProfileEdit(ProfileEditModel vm) { if (ModelState. IsValid) { User context = UserRepository. Find(vm. UserID); rName = rName; context. FirstName = vm. FirstName; context. LastName = vm. LastName; context. Phone = vm. Phone; UserRepository. Update(context); UserRepository. Save(); return RedirectToAction("Index", "Home"); } else { return View(vm); } } #endregion Профиль #region Заказ /// <summary> /// Спосок товаров конкретной категории /// </summary> /// <param name="id">ID категории</param> public ActionResult Categories(int id, int page = 1) { Category cat = CategoryRepository. Find(id); if (cat == null) throw new HttpException(404, "Страница не найдена"); CategoryIndexViewModel vm = new CategoryIndexViewModel(); vm. Category = new CategoryViewModel(cat); var totalProducts = ProductRepository. All. ToList(); vm. Products = totalProducts. Where(p => p. CategoryID == id) .OrderBy(p => p. BrendID).Skip((page - 1) * pageSize) .Take(pageSize).ToViewModels(); vm. PagingInfo = new PagingInfo() { CurrentPage = page, ItemsPerPage = pageSize, TotalItems = totalProducts. Where(p => p. CategoryID == id).Count() }; return View(vm); } /// <summary> /// Подтверждение заказа /// </summary> /// <returns></returns> public ActionResult Complete() { return View(); } /// <summary> /// Подтверждение заказа /// </summary> /// <returns></returns> [Authorize] public ActionResult UserOrders() { UserOrdersViewModel vm = new UserOrdersViewModel(); vm. ExecuteOrders = OrderRepository. AllIncluding(p => p. OrderItems, p => p. User. UserInRoles) .Where(p => p. UserID == CurrentUser. UserID & p. DeliveryDate == null) .OrderBy(p => p. AddDate).ToViewModels(); vm. OrdersArchive = OrderRepository. AllIncluding(p => p. OrderItems, p => p. User. UserInRoles) .Where(p => p. UserID == CurrentUser. UserID & p. DeliveryDate!= null) .OrderBy(p => p. AddDate).ToViewModels(); return View(vm); } #endregion Заказ #region Поиск /// <summary> /// Поиск товара /// </summary> /// <returns></returns> [HttpPost] public ActionResult Find() { ProductFindModel vm = new ProductFindModel(); if (Request. Form["Keyword"] != "") { vm. Keyword = Request. Form["keyword"]; vm. Products = ProductRepository. All. Where(p => p. Model. ToLower().Contains(vm. Keyword. ToLower())).ToViewModels(); } else { vm. Keyword = ""; vm. Products = null; return RedirectToAction("Index", "Home"); } return View(vm); } #endregion Поиск protected override void Dispose(bool disposing) { base. Dispose(disposing); } } } |
Листинг 20 - Код класса AdminController |
namespace ShopWeb. Controllers { [HandleError] public class AdminController : BaseController { public ActionResult Index() { return View(); } /// <summary> /// Пользователи по ролям /// </summary> /// <param name="id">Идентификатор роли</param> /// <returns></returns> public ActionResult Users(int id) { IEnumerable<UserInRoleViewModel> vm = UserInRoleRepository. AllIncluding(p => p. User. UserInRoles, p => p. Role. UserInRoles) .Where(p => p. RoleID == id).OrderBy(p => p. rName).ToViewModels(); return View(vm); } /// <summary> /// Информация о пользователе /// </summary> /// <returns></returns> [HttpGet] public ActionResult UserDetails(int id) { UserEditModel vm = new UserEditModel(); vm. UserID = id; vm. User = UserRepository. Find(id); vm. Status = UserRepository. Find(id).Status; vm. Roles = RoleRepository. All; vm. UserInRoles = UserInRoleRepository. All. Where(p => p. UserID == id); return View(vm); } [HttpPost] public ActionResult UserDetails(UserEditModel vm) { // Удаление всех ролей пользователя кроме роли Покупателя (RoleID =3) foreach (var item in UserInRoleRepository. All. Where(p => p. UserID == vm. UserID & p. RoleID!= 3)) { UserInRoleRepository. Delete(item. UserInRoleID); UserInRoleRepository. Save(); } //// Просмотр переменных прямо из формы foreach (string key in Request. Form. Keys) { if (key. StartsWith("role.")) { int int_role = int. Parse(bstring(5, key. Length - 5)); if (!UserInRoleRepository. All. Where(p => p. UserID == vm. UserID & p. RoleID == int_role).Any()) { UserInRole userinrole = new UserInRole(); userinrole. UserID = vm. UserID; userinrole. RoleID = int_role; UserInRoleRepository. Insert(userinrole); UserInRoleRepository. Save(); } } } // Обновление статуса пользователя User context = UserRepository. Find(vm. UserID); context. Status = vm. Status; UserRepository. Update(context); UserRepository. Save(); return RedirectToAction("Users", "Admin", new { id = 3 }); } #region Изменение товара /// <summary> /// Изменение товара /// </summary> /// <returns></returns> [HttpGet] public ActionResult Products(int id = 1) { ProductEditViewModel vm = new ProductEditViewModel(); vm. Categories = CategoryRepository. All. ToViewModels(); ViewBag. CurrentCategory = id; vm. Products = ProductRepository. AllIncluding(p => p. Brend, p => p. Category).Where(p => p. CategoryID == id).ToViewModels(); return View(vm); } /// <summary> /// Добавление изображения товара /// </summary> /// <returns></returns> [HttpPost] public ActionResult ImageAdd(int id, HttpPostedFileBase imageUpload) { Product context = ProductRepository. Find(id); if (imageUpload!= null) { Image image = new Image(); image. ImageData = new byte[imageUpload. ContentLength]; imageUpload. InputStream. Read(image. ImageData, 0, imageUpload. ContentLength); ImageRepository. Insert(image); ImageRepository. Save(); context. ImageID = image. ImageID; ProductRepository. Update(context); ProductRepository. Save(); } return RedirectToAction("Products", "Admin", new { id = context. CategoryID }); } /// <summary> /// Удаление изображения /// </summary> /// <returns></returns> [HttpPost] public ActionResult ImageDelete(int id) { Product context = ProductRepository. Find(id); //Удаление из таблицы картинок (Image) ImageRepository. Delete(context. ImageID); ImageRepository. Save(); // Обнуляем ImageID context. ImageID = 0; ProductRepository. Update(context); ProductRepository. Save(); return RedirectToAction("Products", "Admin", new { id = context. CategoryID }); } #endregion Изменение товара protected override void Dispose(bool disposing) { base. Dispose(disposing); } } } |
Листинг 21 - Код класса ManagementController |
namespace ShopWeb. Controllers { [HandleError] public class AdminController : BaseController { public ActionResult Index() { return View(); } /// <summary> /// Пользователи по ролям /// </summary> /// <param name="id">Идентификатор роли</param> /// <returns></returns> public ActionResult Users(int id) { IEnumerable<UserInRoleViewModel> vm = UserInRoleRepository. AllIncluding(p => p. User. UserInRoles, p => p. Role. UserInRoles) .Where(p => p. RoleID == id).OrderBy(p => p. rName).ToViewModels(); return View(vm); } /// <summary> /// Информация о пользователе /// </summary> /// <returns></returns> [HttpGet] public ActionResult UserDetails(int id) { UserEditModel vm = new UserEditModel(); vm. UserID = id; vm. User = UserRepository. Find(id); vm. Status = UserRepository. Find(id).Status; vm. Roles = RoleRepository. All; vm. UserInRoles = UserInRoleRepository. All. Where(p => p. UserID == id); return View(vm); } [HttpPost] public ActionResult UserDetails(UserEditModel vm) { // Удаление всех ролей пользователя кроме роли Покупателя (RoleID =3) foreach (var item in UserInRoleRepository. All. Where(p => p. UserID == vm. UserID & p. RoleID!= 3)) { UserInRoleRepository. Delete(item. UserInRoleID); UserInRoleRepository. Save(); } //// Просмотр переменных прямо из формы foreach (string key in Request. Form. Keys) { if (key. StartsWith("role.")) { int int_role = int. Parse(bstring(5, key. Length - 5)); if (!UserInRoleRepository. All. Where(p => p. UserID == vm. UserID & p. RoleID == int_role).Any()) { UserInRole userinrole = new UserInRole(); userinrole. UserID = vm. UserID; userinrole. RoleID = int_role; UserInRoleRepository. Insert(userinrole); UserInRoleRepository. Save(); } } } // Обновление статуса пользователя User context = UserRepository. Find(vm. UserID); context. Status = vm. Status; UserRepository. Update(context); UserRepository. Save(); return RedirectToAction("Users", "Admin", new { id = 3 }); } #region Изменение товара /// <summary> /// Изменение товара /// </summary> /// <returns></returns> [HttpGet] public ActionResult Products(int id = 1) { ProductEditViewModel vm = new ProductEditViewModel(); vm. Categories = CategoryRepository. All. ToViewModels(); ViewBag. CurrentCategory = id; vm. Products = ProductRepository. AllIncluding(p => p. Brend, p => p. Category).Where(p => p. CategoryID == id).ToViewModels(); return View(vm); } /// <summary> /// Добавление изображения товара /// </summary> /// <returns></returns> [HttpPost] public ActionResult ImageAdd(int id, HttpPostedFileBase imageUpload) { Product context = ProductRepository. Find(id); if (imageUpload!= null) { Image image = new Image(); image. ImageData = new byte[imageUpload. ContentLength]; imageUpload. InputStream. Read(image. ImageData, 0, imageUpload. ContentLength); ImageRepository. Insert(image); ImageRepository. Save(); context. ImageID = image. ImageID; ProductRepository. Update(context); ProductRepository. Save(); } return RedirectToAction("Products", "Admin", new { id = context. CategoryID }); } /// <summary> /// Удаление изображения /// </summary> /// <returns></returns> [HttpPost] public ActionResult ImageDelete(int id) { Product context = ProductRepository. Find(id); //Удаление из таблицы картинок (Image) ImageRepository. Delete(context. ImageID); ImageRepository. Save(); // Обнуляем ImageID context. ImageID = 0; ProductRepository. Update(context); ProductRepository. Save(); return RedirectToAction("Products", "Admin", new { id = context. CategoryID }); } #endregion Изменение товара protected override void Dispose(bool disposing) { base. Dispose(disposing); } } } |
Листинг 22 - Код класса CartController |
namespace ShopWeb. Controllers { [HandleError] public class CartController : BaseController { /// <summary> /// Содержимое корзины /// </summary> /// <param name="cart"></param> /// <param name="returnUrl"></param> /// <returns></returns> public ViewResult Index(Cart cart, string returnUrl) { return View(new CartIndexViewModel { Cart = cart, ReturnUrl = returnUrl }); } /// <summary> /// Добавление товара в корзину /// </summary> /// <param name="cart">Cart</param> /// <param name="productId">ProductID</param> /// <param name="returnUrl"></param> /// <returns></returns> public RedirectToRouteResult AddToCart(Cart cart, int productID, string returnUrl) { Product product = ProductRepository. All. FirstOrDefault(p => p. ProductID == productID); //Количество текущего товара в корзине int cartsum = 0; if (cart. Lines. Where(p => p. Product. ProductID == productID).Count() > 0) { cartsum = cart. Lines. FirstOrDefault(p => p. Product. ProductID == productID).Quantity; } if (product!= null) { if (cartsum >= mProduct) { cart. RemoveLine(product); cart. AddItem(product, mProduct); } else { cart. AddItem(product, 1); } } return RedirectToAction("Index", new { returnUrl }); } /// <summary> /// Удаление товара из корзину /// </summary> /// <param name="cart"></param> /// <param name="productID"></param> /// <param name="returnUrl"></param> /// <returns></returns> public RedirectToRouteResult RemoveFromCart(Cart cart, int productID, string returnUrl) { Product product = ProductRepository. All. FirstOrDefault(p => p. ProductID == productID); if (product!= null) { cart. RemoveLine(product); } return RedirectToAction("Index", new { returnUrl }); } /// <summary> /// Изменение количества товара /// </summary> public RedirectToRouteResult EditQuantity(Cart cart, int productID, string returnUrl) { Product product = ProductRepository. All. FirstOrDefault(p => p. ProductID == productID); decimal temp = Math. Round(decimal. Parse(Request. Form["Quantity"]), 0, MidpointRounding. AwayFromZero); int quantity = Decimal. ToInt32(temp); // Если число не действительное перекидываем на 1 if (quantity <= 0) { TempData["message"] = "Вы ввели недействительное число"; quantity = 1; } // Если число больше количества товаров на всех складах, то ставим сумму товара на всех складах if (quantity > mProduct) { TempData["message"] = "Вы ввели количество товара, превышающее количество товара на складах"; quantity = mProduct; } if (product!= null) { cart. RemoveLine(product); cart. AddItem(product, quantity); } quantity = 0; return RedirectToAction("Index", new { returnUrl }); } public ViewResult Summary(Cart cart) { return View(cart); } /// <summary> /// Оформление заказа /// </summary> /// <returns></returns> [HttpGet] public ActionResult Checkout() { ShippingDetails vm = new ShippingDetails(); if (CurrentUser!= null) { vm. User = CurrentUser; vm. NewUser = false; vm. Email = CurrentUser. Email; rName = rName; vm. FirstName = CurrentUser. FirstName; vm. LastName = CurrentUser. LastName; vm. Phone = CurrentUser. Phone; vm. Password = CurrentUser. PasswordHash; } else { vm. User = new User(); vm. NewUser = true; } return View(vm); } [HttpPost] public ActionResult Checkout(Cart cart, ShippingDetails vm) { if (ModelState. IsValid) { if (vm. NewUser) { // Добавление нового User в базу User context = new User(); rName = rName. Trim(); context. FirstName = vm. FirstName. Trim(); context. LastName = vm. LastName. Trim(); context. Phone = vm. Phone. Trim(); context. Email = vm. Email. Trim(); context. PasswordHash = Crypto. Hash(vm. Password. Trim()); context. Status = true; context. DateRegistred = DateTime. Now; context. DateModified = DateTime. Now; UserRepository. Insert(context); UserRepository. Save(); // Добавление default - роли новому User UserInRole ur = new UserInRole(); ur. UserID = context. UserID; ur. RoleID = 3; UserInRoleRepository. Insert(ur); UserInRoleRepository. Save(); // Добавление заказа Order Order order = new Order(); order. UserID = context. UserID; order. AddDate = DateTime. Now; order. DeliveryAddress = vm. DeliveryAddress. Trim(); OrderRepository. Insert(order); OrderRepository. Save(); // Запись товаров из корзины в Order foreach (var item in cart. Lines) { OrderItem orderItem = new OrderItem(); orderItem. OrderID = order. OrderID; orderItem. ProductID = item. Product. ProductID; orderItem. Quantity = item. Quantity; OrderItemRepository. Insert(orderItem); OrderItemRepository. Save(); } } else { // Добавление заказа Order Order order = new Order(); order. UserID = CurrentUser. UserID; order. AddDate = DateTime. Now; order. DeliveryAddress = vm. DeliveryAddress. Trim(); OrderRepository. Insert(order); OrderRepository. Save(); // Запись товаров из корзины в Order foreach (var item in cart. Lines) { OrderItem orderItem = new OrderItem(); orderItem. OrderID = order. OrderID; orderItem. ProductID = item. Product. ProductID; orderItem. Quantity = item. Quantity; OrderItemRepository. Insert(orderItem); OrderItemRepository. Save(); } } cart. Clear(); return RedirectToAction("Complete", "Home"); } else { if (CurrentUser!= null) { vm. User = CurrentUser; vm. NewUser = false; vm. Email = CurrentUser. Email; rName = rName; vm. FirstName = CurrentUser. FirstName; vm. LastName = CurrentUser. LastName; vm. Phone = CurrentUser. Phone; vm. Password = CurrentUser. PasswordHash; } else { vm. User = new User(); vm. NewUser = true; } return View(vm); } } } } |
Листинг 23 - Код класса LogController |
namespace ShopWeb. Controllers { /// <summary> /// Логи работы /// </summary> [HandleError] public class LogController : BaseController { public int pageSize = 15; public ActionResult Index(int id = 1) { LogIndexViewModel vm = new LogIndexViewModel(); var totalLogs = LogRepository. All. ToList(); vm. Logs = totalLogs. OrderByDescending(p => p. CreatedAt).Skip((id - 1) * pageSize).Take(pageSize); vm. PagingInfo = new PagingInfo() { CurrentPage = id, ItemsPerPage = pageSize, TotalItems = totalLogs. Count() }; return View(vm); } } } |
Листинг 24 - Код класса ErrorController |
namespace ShopWeb. Controllers { public class ErrorController : BaseController { public ActionResult General(Exception exception) { return View("Exception", exception); } public ActionResult Http403() { ViewBag. Url = Request. Url; return View("403"); } public ActionResult Http404() { return View("404"); } public ActionResult Http500() { return View("500"); } } } |
Листинг 25 - Код класса ReviewController |
namespace ShopWeb. Controllers { /// <summary> /// Контроллер отзывов /// </summary> public class ReviewController : BaseController { public ActionResult Index(int id) { ReviewIndexViewModel vm = new ReviewIndexViewModel(); Product product = ProductRepository. Find(id); vm. ProductID = id; vm. BrandName = product. Brend. BrendName + " " + product. Model; vm. Price = product. Price; vm. Reviews = ReviewRepository. AllIncluding(p => p. User).Where(p => p. ProductID == id).OrderByDescending(p => p. DateCreate); //Проверка существования отзыва конкретного пользователя if (CurrentUser!= null) { if (ReviewRepository. All. Where(p => p. ProductID == id & p. UserID == CurrentUser. UserID).Count()>= 1) { vm. IsDuble = true; } else { vm. IsDuble = false; } } return View(vm); } ///// <summary> ///// Добавление отзыва ///// </summary> [HttpGet] public ActionResult Create(int id) { ReviewViewModel vm = new ReviewViewModel(); vm. ProductID = id; return View(vm); } [HttpPost] public ActionResult Create(ReviewViewModel vm) { Review context = new Review(); context. DateCreate = DateTime. Now; context. ProductID = vm. ProductID; context. UserID = CurrentUser. UserID; if (ModelState. IsValid) { context. Message = vm. Message; ReviewRepository. Insert(context); ReviewRepository. Save(); return RedirectToAction("Index", "Review", new { id = vm. ProductID }); } else { return View(vm); } } } } |
Листинг 26 - Код класса MvcApplication |
using Shop. Domain. DAL; using Shop. Domain. Repositories; using ShopWeb. Binders; using ShopWeb. Controllers; using ShopWeb. Models; using System; using System. Web; using System. Web. Mvc; using System. Web. Optimization; using System. Web. Routing; namespace ShopWeb { // Примечание: Инструкции по включению классического режима IIS6 или IIS7 // см. по ссылке http://go. /?LinkId=9394801 public class MvcApplication : System. Web. HttpApplication { protected void Application_Start() { AreaRegistration. RegisterAllAreas(); FilterConfig. RegisterGlobalFilters(GlobalFilters. Filters); RouteConfig. RegisterRoutes(RouteTable. Routes); BundleConfig. RegisterBundles(BundleTable. Bundles); ModelBinders. Binders. Add(typeof(Cart), new CartModelBinder()); } protected void Application_Error(Object sender, EventArgs e) { ////#if! DEBUG var exception = Server. GetLastError(); var httpException = exception as HttpException; Response. Clear(); Server. ClearError(); var routeData = new RouteData(); routeData. Values["controller"] = "Error"; routeData. Values["action"] = "General"; routeData. Values["Exception"] = exception; if (httpException!= null) { Response. StatusCode = httpException. GetHttpCode(); switch (Response. StatusCode) { case 403: routeData. Values["action"] = "Http403"; break; case 404: routeData. Values["action"] = "Http404"; break; case 500: routeData. Values["action"] = "Http500"; break; } } Response. TrySkipIisCustomErrors = true; IController errorsController = new ErrorController(); // запись лога в базу SqlBaseRepository<Log> logger = new SqlBaseRepository<Log>(); Log logentry = new Log(exception. Message); try { if (HttpContext. Current. User. Identity. Name == null) { logentry. UserName = "Anonimus"; } else { logentry. UserName = HttpContext. Current. User. Identity. Name; } } catch { logentry. UserName = "SYSTEM"; } logger. Insert(logentry); logger. Save(); HttpContextWrapper wrapper = new HttpContextWrapper(Context); var rc = new RequestContext(wrapper, routeData); errorsController. Execute(rc); //#endif } } } |
Листинг 27 - Код класса AuthHttpModule |
using System; using System. Web; using System. Web. Mvc; namespace ShopWeb. Global. Auth { public class AuthHttpModule : IHttpModule { public void Init(HttpApplication context) { context. AuthenticateRequest += new EventHandler(this. Authenticate); } private void Authenticate(Object source, EventArgs e) { HttpApplication app = (HttpApplication)source; HttpContext context = app. Context; var auth = DependencyResolver. Current. GetService<IAuthentication>(); auth. AuthCookieProvider = new HttpContextCookieProvider(context); context. User = auth. CurrentUser; } public void Dispose() { } } } |
Листинг 28 - Код класса CustomAuthentication |
using Ninject; using Shop. Domain. DAL; using Shop. Domain. Repositories; using System; using System. Linq; using System. Security. Principal; using System. Web; using System. Web. Security; namespace ShopWeb. Global. Auth { public class CustomAuthentication : IAuthentication { private const string cookieName = "_SHOP_COOKIE"; public IAuthCookieProvider AuthCookieProvider { get; set; } [Inject] public IBaseRepository<User> Repository { get; set; } #region IAuthentication пользователей public User Login(string userName, string password) { User retUser = Repository. All. FirstOrDefault(p => p. Email == userName & p. PasswordHash == password); if (retUser!= null) { CreateCookie(userName, false); retUser. DateModified = DateTime. Now; Repository. Update(retUser); Repository. Save(); } return retUser; } private void CreateCookie(string userName, bool isPersistent = false) { var ticket = new FormsAuthenticationTicket( 1, userName, DateTime. Now, DateTime. Now. Add(FormsAuthentication. Timeout), isPersistent, string. Empty, FormsAuthentication. FormsCookiePath); // Шифрование билета. var encTicket = FormsAuthentication. Encrypt(ticket); // Создание cookie. var AuthCookie = new HttpCookie(cookieName) { Value = encTicket, Expires = DateTime. Now. Add(FormsAuthentication. Timeout) }; AuthCookieProvider. SetCookie(AuthCookie); } public void LogOut() { var httpCookie = AuthCookieProvider. GetCookie(cookieName); if (httpCookie!= null) { var AuthCookie = new HttpCookie(cookieName); httpCookie. Value = string. Empty; AuthCookieProvider. SetCookie(AuthCookie); } } private IPrincipal _currentUser; public IPrincipal CurrentUser { get { if (_currentUser == null) { try { HttpCookie authCookie = AuthCookieProvider. GetCookie(cookieName); if (authCookie!= null && !string. IsNullOrEmpty(authCookie. Value)) { var ticket = FormsAuthentication. Decrypt(authCookie. Value); _currentUser = new UserProvider(ticket. Name, Repository); } else { _currentUser = new UserProvider(null, null); } } catch { _currentUser = new UserProvider(null, null); } } return _currentUser; } } #endregion } } |
Листинг 29 - Код класса HttpContextCookieProvider |
using System; using System. Collections. Generic; using System. Linq; using System. Web; namespace ShopWeb. Global. Auth { public class HttpContextCookieProvider : IAuthCookieProvider { public HttpContextCookieProvider(HttpContext HttpContext) { this. HttpContext = HttpContext; } protected HttpContext HttpContext { get; set; } public HttpCookie GetCookie(string cookieName) { return HttpContext. Request. Cookies. Get(cookieName); } public void SetCookie(HttpCookie cookie) { HttpContext. Response. Cookies. Set(cookie); } } } |
Листинг 30 - Код интерфейса IAuthCookieProvider |
using System; using System. Collections. Generic; using System. Linq; using System. Text; using System. Threading. Tasks; using System. Web; namespace ShopWeb. Global. Auth { public interface IAuthCookieProvider { HttpCookie GetCookie(string cookieName); void SetCookie(HttpCookie cookie); } } |
Листинг 31 - Код интерфейса IAuthentication |
using Shop. Domain. DAL; using System. Security. Principal; namespace ShopWeb. Global. Auth { /// <summary> /// Интерфейс для авторизации /// </summary> public interface IAuthentication { /// <summary> /// Контекст (тут мы получаем доступ к запросу и кукисам) /// </summary> IAuthCookieProvider AuthCookieProvider { get; set; } /// <summary> /// Процедура входа /// </summary> /// <param name="login">логин</param> /// <param name="password">пароль</param> User Login(string login, string password); /// <summary> /// Выход /// </summary> void LogOut(); /// <summary> /// Данные о текущем пользователе /// </summary> IPrincipal CurrentUser { get; } } } |
Листинг 32 - Код интерфейса IUserProvider |
using Shop. Domain. DAL; namespace ShopWeb. Global. Auth { public interface IUserProvider { User User { get; set; } } } |
Листинг 33 - Код класса UserIndentity |
using Shop. Domain. DAL; using Shop. Domain. Repositories; using System. Security. Principal; using System. Linq; namespace ShopWeb. Global. Auth { /// <summary> /// Реализация интерфейса для идентификации пользователя /// </summary> public class UserIndentity : IIdentity, IUserProvider { /// <summary> /// Текущий пользователь /// </summary> public User User { get; set; } /// <summary> /// Тип класса для пользователя /// </summary> public string AuthenticationType { get { return typeof(User).ToString(); } } /// <summary> /// Авторизован или нет /// </summary> public bool IsAuthenticated { get { return User!= null; } } /// <summary> /// Имя пользователя /// </summary> public string Name { get { if (User!= null) { return User. FirstName; } //иначе аноним return "anonym"; } } /// <summary> /// Инициализация по Email /// </summary> /// <param name="user">имя пользователя</param> public void Init(string user, IBaseRepository<User> repository) { if (!string. IsNullOrEmpty(user)) { User = repository. All. FirstOrDefault(p => p. Email. ToLower().Trim() == user. ToLower().Trim()); } } } } |
Листинг 34 - Код класса UserProvider |
using Ninject; using Shop. Domain. DAL; using Shop. Domain. Repositories; using System; using System. Linq; using System. Security. Principal; namespace ShopWeb. Global. Auth { /// <summary> /// Реализация интерфейса Principal /// </summary> public class UserProvider : IPrincipal { private UserIndentity userIdentity { get; set; } #region IPrincipal Members /// <summary> /// Идентификатор пользователя /// </summary> public IIdentity Identity { get { return userIdentity; } } /// <summary> /// Находится в данной роли или нет /// </summary> /// <param name="role">имя роли</param> /// <returns>есть такая роль или нет</returns> public bool IsInRole(string role) { if (userIdentity. User == null) { return false; } return userIdentity. User. InRoles(role); } #endregion IPrincipal Members /// <summary> /// Конструктор /// </summary> /// <param name="name"></param> /// <param name="repository"></param> public UserProvider(string name, IBaseRepository<User> repository) { userIdentity = new UserIndentity(); userIdentity. Init(name, repository); } /// <summary> /// Имя пользователя /// </summary> /// <returns></returns> public override string ToString() { return userIdentity. Name; } } } |
|
Из за большого объема этот материал размещен на нескольких страницах:
1 2 3 4 5 6 |










