I'm trying to move my DbSet's to a class library project that is going to be used for database operations.
I've been following this tutorial to a Code First / SimpleMembershipProfider project. I've already got the database filled with new tables etc, via the class lib project.
But i am missing the webpages_ tables you can see on this image.
This is my datacontext class:
public class DataContext : DbContext
{
public DataContext() : base("DefaultConnection")
{
}
public DbSet<Orders> Orders { get; set; }
public DbSet<Appointment> Appointment { get; set; }
public DbSet<UserProfile> UserProfile { get; set; }
}
And for every DbSet i created a cs file. I copied the connectionString from the web.config and placed it in the app.config in the class lib project. This is how the app.config file looks like:
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=aspnet-CodeFirst-test;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<clear />
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear />
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
</system.web>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
I'm not sure what to do with the Filters folder (which has the class InitializeSimpleMembershipAttribute) in my webproject.
Can someone tell me how to get the webpages_ created in the database? And how to move websecurity etc to the class lib project?
Thanks in advance!
If you trying to take control of Asp.net Simple Membership Table and or Including Asp.net Simple Membership Tables as Part of Your Entity Framework Model your Project Entity framework, there is a number of steps you need to take. I would explain them step by step but it would take too long so i will just provide you with references.
Including Asp.net Simple Membership Tables as Part of Your Entity Framework Model
Seed Users and Roles with MVC 4, SimpleMembershipProvider, SimpleRoleProvider, Entity Framework 5 CodeFirst, and Custom User Properties
Building Applications with ASP.NET MVC 4. You can use trial version on pluralsight
If you have any specific questions, i would be happy to answer them.
Related
I have a MVC4 application using SimpleMembership to authenticate users.
I want to add users from a console program.
The console program that references a class library that has the method that will do the user creation.
It looks like this:
public class UserBuilder
{
private static readonly SimpleMembershipInitializer _membershipInitializer;
private static readonly bool _isInitialized;
private static readonly object _initializerLock = new object();
static UserBuilder()
{
LazyInitializer.EnsureInitialized(ref _membershipInitializer, ref _isInitialized, ref _initializerLock);
}
public void HandleEvent(UserAdded #event)
{
if (!WebSecurity.UserExists("ReportModels"))
{
WebSecurity.CreateUserAndAccount("ReportModels", "ReportModels");
};
}
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
}
}
When I start my console application I get System.Configuration.Provider.ProviderException {"The Role Manager feature has not been enabled."} at the line starting with WebSecurity.InitializeDatabaseConnection.
What do I need to do to accomplish this?
I've tried:
adding the nuget package Microsoft ASP.NET Web Pages 2 Web Data to both the console project and the class library project.
the answers listed in this post: SimpleMembershipProvider not working.
verified the connection string.
verified that the tables are in place in the database.
verified that creating users and authenticating them from the MVC4 project works.
Finally solved it thanks to information found in this blog post: http://insomniacgeek.com/to-call-this-method-the-membership-provider-property-must-be-an-instance-of-extendedmembershipprovider/ and some googling.
In essence I needed to add this to my app.config file:
<system.web>
<profile defaultProvider="SimpleProfileProvider">
<providers>
<add name="SimpleProfileProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"
connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</profile>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
<roleManager defaultProvider="SimpleRoleProvider" enabled="true">
<providers>
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
</providers>
</roleManager>
</system.web>
Please note the enabled="true" on the roleManager element. Without that the same exception will be thrown.
I have a problem with using [Authorize(Roles = "admin")] attribute.
[Authorize(Roles = "admin")]
public ActionResult GetAllLocations()
{
I am getting the following error
You must call the "WebSecurity.InitializeDatabaseConnection" method
before you call any other method of the "WebSecurity" class. This call
should be placed in an _AppStart.cshtml file in the root of your site.
I have built a MVC 4 application using EF 5 Code first with my own database.
A little background:
I have created a custom membership provider I have inherited from
MembershipProvider
I have look at a lot of questions in this site about this issue, but
didn't found an answer.
In some answers i saw how to disable the membership provider
like this:
<add key="enableSimpleMembership" value="false"/>
<add key="autoFormsAuthentication" value="false"/>
This is how i implemented my custom membership provider
<membership defaultProvider="ATWMembershipProvider">
<providers>
<clear/>
<add name="ATMMembershipProvider" type="AroundTheWorldWeb.Infrastructure.AuthenticationProvider.ATMMembershipProvider"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
equiresUniqueEmail="false"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10" applicationName="myApplication" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="AspNetSqlRoleProvider">
<providers>
<remove name="AspNetSqlRoleProvider" />
<add name="AspNetSqlRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<!-- note: WebMatrix registers SimpleRoleProvider with name
'AspNetSqlRoleProvider'. I don't know why but i kept it. -->
</providers>
</roleManager>
I fixed this problem by creating the MVC 4 from template. I think there some DLL's aren't loaded when choosing Empty template. So i have created it from a template and override all the Account's methods And also implemented custom member and role provider
I am trying to register a user to a role but i am getting the following error:
No user found was found that has the name "MyName"
I have created an MVC 4 Application using the default template.
I have created a custom membership provider and implemented the CreateUser method as follow
public User CreateUser(User i_userToCreate)
{
using (var _db = new Repository())
{
User _user = _db.CreateUser(i_userToCreate);
MembershipUser _membershipUser = new MembershipUser(providerName: "ATWMembershipProvider",
name: _user.UserName,
providerUserKey: null,
email: _user.Email,
passwordQuestion: "",
comment: "",
isApproved: true,
isLockedOut: false,
creationDate: DateTime.UtcNow,
lastLoginDate: DateTime.UtcNow,
lastActivityDate: DateTime.UtcNow,
lastPasswordChangedDate: DateTime.UtcNow,
lastLockoutDate: DateTime.UtcNow);
return _user;
}
This is how i configured my web.config
<appSettings>
<add key="enableSimpleMembership" value="false"/>
<add key="autoFormsAuthentication" value="false"/>
</appSettings>
<system.web>
<membership defaultProvider="ATWMembershipProvider">
<providers>
<clear/>
<add name="ATWMembershipProvider" type="AroundTheWorld.Infrastructure.ATWMembershipProvider"
enablePasswordRetrieval="false"
ConnetionStringName="Context"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
equiresUniqueEmail="false"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10" applicationName="myApplication" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="AspNetSqlRoleProvider">
<providers>
<remove name="AspNetSqlRoleProvider" />
<add name="AspNetSqlRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<!-- note: WebMatrix registers SimpleRoleProvider with name
'AspNetSqlRoleProvider'. I don't know why but i kept it. -->
</providers>
</roleManager>
Now the authenticate method is as follow:
var MembershipProvider = new ATWMembershipProvider();
User authentictedUser = MembershipProvider.CreateUser(_userToCreate);
FormsAuthentication.SetAuthCookie(authentictedUser.UserName, true);
System.Web.Security.Roles.AddUserToRole(authentictedUser.UserName, authentictedUser.Role.Name);
Session.Add("UserID", authentictedUser.ID);
Session.Add("UserName", authentictedUser.UserName);
I have already checked the following:
My User as all necessary information
I have registered two roles in App_start "user" , "admin"
but i still getting an error that No user found was found that has the name "MyName"
In asp web form that wasn't necessary in order to secure a folder based on a role
All i am trying to do is to secure an action inside a controller to a specific "Role"
[Authorize(Roles = "admin")]
public ActionResult GetAllLocations()
{
using (var _db = new Repository())
{
return View(_db.GetLocations());
}
}
I have fixed the problem...
The problem was because I implemented only a custom membership provider without a role provider.
I have followed this blog.
Basically I have created a class MyOwnRoleProvider which inherits from RoleProvider
and:
Implemented the method called GetRolesForUser
Implemented the method called GetUsersInRole
finally I modified my web.config to
<roleManager defaultProvider="ATWRoleProvider" enabled="true" cacheRolesInCookie="true">
<providers>
<clear />
<add name="ATWRoleProvider" type="AroundTheWorld.Infrastructure.ATWRoleProvider, AroundTheWorld" connectionStringName="Context" />
</providers>
</roleManager>
after it I was able to use the following
[Authorize(Roles="admin")]
public ActionResult GetAllLocations()
{
using (var _db = new Repository())
{
return View(_db.GetLocations());
}
}
AND
#if (User.IsInRole("user"))
I hope it will be helpful for someone...
I am trying to add a dropdownlist to a strongly typed razor view. ASP.Net MVC 4.0, Razor View engine version 2.0.0.0
#using System;
#model SampleApp.Models.ServiceRequestModel
#{
ViewBag.Title = "ServiceRequest";
}
#Html.DropDownListFor(m=>m.CategoryID, Model.Categories)
and the Model is as below:
public class ServiceRequestModel
{
public int ID { get; set; }
public int CategoryID { get; set; }
public SelectList Category { get; set; }
}
it is always showing an error in intellisense in CSHTML file as:
System.Web.WebPages.Html.HtmlHelper' does not contain a definition for 'DropDownListFor' and no extension method 'DropDownListFor' accepting a first argument of type 'System.Web.WebPages.Html.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)
and also it is giving errors for :
Error 3 The name 'model' does not exist in the current context
I have checked the web.config in View folder:
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
The below line of config code had to be changed to 4.0.0.0
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, **Version=3.0.0.0**, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
changed to
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, **Version=4.0.0.0**, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
I spent over a day on this error and it ended up being a data type clash with the VM data source for the dropdownlist (ie it wasn't a list of type IEnumerable). For some reason VS2012 thought the error was with the namespace even though it appeared in Intellipath.
I had this exact issue (only with html.displayFor).
I'm not sure how it started but i solved it by replacing the following:
<appSettings>
<add key="webpages:Enabled" value="false" />
</appSettings>
with
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
</appSettings>
in the View folder's Web.config file.
Found my solution here
I'm trying to connect to multiple databases in castle active record (which uses nhibernate.) My config file looks like this:
<configSections>
<section name="activerecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord" />
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<activerecord>
<config type="Navtrak.Business.Schemas.CommonSchemas.Models.NavtrakOperations.NavtrakOperationsDatabase`1, CommonSchemas">
<add key="hibernate.connection.connection_string" value="myconnstring" />
<add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver" />
<add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2005Dialect" />
<add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
</config>
<config type="Navtrak.Business.Schemas.CommonSchemas.Models.Errors.ErrorsDatabase`1, CommonSchemas">
<add key="hibernate.connection.connection_string" value="Data Source=myconnstring" />
<add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver" />
<add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2005Dialect" />
<add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
</config>
</activerecord>
And then I have a base abstract class for each database like this:
public abstract class NavtrakOperationsDatabase<T> : ActiveRecordBase<T>
{
}
And then each class inherits from this. I'm then initializing active record like this:
ActiveRecordStarter.Initialize(typeof(SimpleModel).Assembly, ActiveRecordSectionHandler.Instance);
Which gives me the error:
Could not find the dialect in the configuration
If I change the activation code to this:
ActiveRecordStarter.Initialize(
ActiveRecordSectionHandler.Instance,
typeof(NavtrakOperationsDatabase<>),
typeof(ErrorsDatabase<>)
);
Then I get the following error:
You have accessed an ActiveRecord class that wasn't properly initialized. There are two possible explanations: that the call to ActiveRecordStarter.Initialize() didn't include Navtrak.Business.Schemas.CommonSchemas.Models.NavtrakOperations.Application class, or that Navtrak.Business.Schemas.CommonSchemas.Models.NavtrakOperations.Application class is not decorated with the [ActiveRecord] attribute.
I obviously don't want to include every single class in the Initialize function.
Any ideas?
In my case - which was the same situation - I have added this to the InitializeAR method:
LoggerProvider.SetLoggersFactory(new NoLoggingLoggerFactory());
It ended up like this:
lock (typeof(SessionManager))
{
if (!initialized)
{
LoggerProvider.SetLoggersFactory(new NoLoggingLoggerFactory());
System.Reflection.Assembly bin = typeof(SimpleModel).Assembly;
IConfigurationSource s = (IConfigurationSource)ConfigurationManager.GetSection("activerecord");
ActiveRecordStarter.Initialize(bin, s);
}
initialized = true;
}
Drop the "hibernate." prefix from all config keys. That prefix was used in NHibernate 1.x