InitializeSimpleMembershipAttribute.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System;
  2. using System.Data.Entity;
  3. using System.Data.Entity.Infrastructure;
  4. using System.Threading;
  5. using System.Web.Mvc;
  6. using WebMatrix.WebData;
  7. using EMIS.Web.Models;
  8. namespace EMIS.Web.Filters
  9. {
  10. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
  11. public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
  12. {
  13. private static SimpleMembershipInitializer _initializer;
  14. private static object _initializerLock = new object();
  15. private static bool _isInitialized;
  16. public override void OnActionExecuting(ActionExecutingContext filterContext)
  17. {
  18. // Ensure ASP.NET Simple Membership is initialized only once per app start
  19. LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
  20. }
  21. private class SimpleMembershipInitializer
  22. {
  23. public SimpleMembershipInitializer()
  24. {
  25. Database.SetInitializer<UsersContext>(null);
  26. try
  27. {
  28. using (var context = new UsersContext())
  29. {
  30. if (!context.Database.Exists())
  31. {
  32. // Create the SimpleMembership database without Entity Framework migration schema
  33. ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
  34. }
  35. }
  36. WebSecurity.InitializeDatabaseConnection("EMISNewContext", "Sys_User", "UserId", "Name", autoCreateTables: true);
  37. }
  38. catch (Exception ex)
  39. {
  40. throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
  41. }
  42. }
  43. }
  44. }
  45. }