C# MVC Do i have to use DB for Role Provider - asp.net-mvc

I've been trying to use role provider but its been giving me headaches for a week.
All I am trying to do is allow a user to be able to see "Admin" Page if they are an admin (I've added Admin Coloumn in my database, to be 0 or 1)
Here is the code in my Controller for Login
if (user.Admin == 1)
{
addUserToRole(user.UserID, "Admin");
}
else
{
}
here is the method to add user to a role
public void addUserToRole(String user, String role)
{
if (!Roles.RoleExists(role))
Roles.CreateRole(role);
Roles.AddUserToRole(user, role);
}
for the admin controller, I want to enter this
[Authorize(role= "admin")]
Here is my webconfig
<profile defaultProvider="DefaultProfileProvider">
<providers>
<add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxxxx" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</profile>
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxx" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<roleManager defaultProvider="DefaultRoleProvider" enabled="true">
<providers>
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxx" connectionStringName="Database2Entities1" applicationName="/" />
</providers>
</roleManager>
my question is do I have to use database (meaning I had to add roles tables, etc) to use this role provider.
If yes is there another way I could implement this?

If you use SimpleMembership Provider the tables you will get automaticlly will be --> Your user table, Roles, UsersInRoles, Membership where in Roles you can add roles you wish and in UsersInRoles you can add users to role with this line:
assuming you already have the role "Admin" seed-ed into your database table for Roles
System.Web.Security.Roles.AddUsersToRole("username, "yourrolename");
the seeding of the role in the Roles table in the database is as you do it:
WebSecurity.InitializeDatabaseConnection("DefaultConnection",
"UserProfile", "UserId", "UserName", autoCreateTables: true);
var roles = (SimpleRoleProvider)Roles.Provider;
var membership = (SimpleMembershipProvider)Membership.Provider;
if (!roles.RoleExists("Admin"))
{
roles.CreateRole("Admin");
}
// you can do the seed of the role to user in the seed method too
if (membership.GetUser("user", false) == null)
{
membership.CreateUserAndAccount("user", "123456");
}
if (!roles.GetRolesForUser("user1").Contains("Admin"))
{
roles.AddUsersToRoles(new[] { "user" }, new[] { "Admin" });
}
you will also have to change the membership paragraph in your web config with this:
<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>
but is not needed to be done every time you add user to role. Hope this helps.

Related

MVC 5 Change ViewEngine Path Error: (must derive from ViewPage) even with WebConfig in View Root

i try to move my Views default directory top a different path.
I have changed my Global.asax to add the directory in my view Engine like this
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
RegisterViewEngines(ViewEngines.Engines);
}
private static void RegisterViewEngines(ICollection<IViewEngine> engines)
{
engines.Add(new WebFormViewEngine
{
//MasterLocationFormats = new[] { "~/App/Views/Admin/{0}.master" },
PartialViewLocationFormats = new[] { "~/Mvc/Views/Shared/{1}/{0}.cshtml" },
ViewLocationFormats = new[] { "~/Mvc/Views/{1}/{0}.cshtml" }
});
}
This is the image of my new folder configuration
Every where i read i see that i need to add a web config to my Views root folder. So i take the one came in the template View and i paste it in my new folder configuration.
This is my /Mvc/Views/Web.Config
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.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.Optimization"/>
<add namespace="System.Web.Routing" />
<add namespace="Template" />
</namespaces>
</pages>
</system.web.webPages.razor>
<appSettings>
<add key="webpages:Enabled" value="false" />
</appSettings>
<system.webServer>
<handlers>
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
</system.webServer>
<system.web>
<compilation>
<assemblies>
<add assembly="System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
</system.web>
</configuration>
No mater what i Always see this Error :
Error Stack Trace
The view at '~/Mvc/Views/Login/Index.cshtml' must derive from ViewPage, ViewPage<TModel>, ViewUserControl, or ViewUserControl<TModel>.
Description : Une exception non gérée s'est produite au moment de l'exécution de la requête Web actuelle. Contrôlez la trace de la pile pour plus d'informations sur l'erreur et son origine dans le code.
Détails de l'exception: System.InvalidOperationException: The view at '~/Mvc/Views/Login/Index.cshtml' must derive from ViewPage, ViewPage<TModel>, ViewUserControl, or ViewUserControl<TModel>.
I have found my solution, the problem was in my RegisterViewEngine Function.
I use the Class WebFormViewEngine that is suppose to be used for file .ascx. for the Razor view you are suppose to use the Class RazorViewEngine
So i just have to change my function like this:
private static void RegisterViewEngines(ICollection<IViewEngine> engines)
{
engines.Add(new RazorViewEngine
{
//MasterLocationFormats = new[] { "~/App/Views/Admin/{0}.master" },
PartialViewLocationFormats = new[] { "~/Mvc/Views/Shared/{1}/{0}.cshtml" },
ViewLocationFormats = new[] { "~/Mvc/Views/{1}/{0}.cshtml" }
});
}
Now it work perfectly!

WebAPI + SimpleMembership + WebSecurity - can never authenticate?

I'm trying to implement a single-page app. I carried over some of my working code from another project (MVC4) to implement authentication. Right now I see cookies being set, but WebSecurity / User.Identity do not seem to be working for some reason. After logging in, subsequent requests never validate as authenticated, either via WebSecurity.IsAuthenticated, or User.Identity.IsAuthenticated. Does anyone know why this is happening?
Controller code:
public class AccountController : ApiController {
private readonly UserService _userService;
public AccountController() {}
public AccountController(UserService userService) {
_userService = userService;
}
[AllowAnonymous]
[HttpGet]
[Route("api/authpayload")]
// This gets called when the app loads. Always, User.Identity.IsAuthenticated is false.
public HttpResponseMessage AuthPayload() {
var payload = new AuthPayloadDto();
try {
var userId = WebSecurity.GetUserId(User.Identity.Name);
if (User.Identity.IsAuthenticated && userId > 0) {
payload.Username = User.Identity.Name;
} else {
LogOut();
payload.IsAuthenticated = false;
}
return Request.CreateResponse(HttpStatusCode.OK, payload);
} catch (Exception e) {
return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
}
}
[HttpPost]
[Route("api/login")]
[AllowAnonymous]
public HttpResponseMessage LogIn(LoginModel model) {
if (!ModelState.IsValid)
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
try {
if (WebSecurity.IsAuthenticated)
return Request.CreateResponse(HttpStatusCode.Conflict, "already logged in.");
if (!WebSecurity.UserExists(model.Username))
return Request.CreateResponse(HttpStatusCode.Conflict, "User does not exist.");
if (WebSecurity.Login(model.Username, model.Password, persistCookie: model.RememberMe)) {
// This code always gets hit when I log in, no problems. I see a new cookie get sent down as well, using Chrome debugger.
var payload = new AuthPayloadDto();
return Request.CreateResponse(HttpStatusCode.OK, payload);
}
LogOut();
return Request.CreateResponse(HttpStatusCode.Forbidden, "Login Failed.");
} catch (Exception e) {
return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
}
}
Web.config:
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms">
<forms loginUrl="~/" timeout="2880" />
</authentication>
<roleManager enabled="true" defaultProvider="simple">
<providers>
<clear />
<add name="simple" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
<membership defaultProvider="simple">
<providers>
<clear />
<add name="simple" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
<!--
If you are deploying to a cloud environment that has multiple web server instances,
you should change session state mode from "InProc" to "Custom". In addition,
change the connection string named "DefaultConnection" to connect to an instance
of SQL Server (including SQL Azure and SQL Compact) instead of to SQL Server Express.
-->
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
</providers>
</sessionState>
</system.web>
The cookie that gets sent after login is not expired, and it does get sent back on subsequent requests, but IsAuthenticated is always false. What am I doing wrong?
Update:
I updated my web.config to the following to get everything working:
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<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>
But I'd like to leave this open in case anyone has an explanation of why this works; I'm pretty lost.
In my current mvc 4 project with mssql,
its a simple one i so I just wanted very simple memmbership provider
I disabled
InitializeSimpleMembershipAttribute
by
[Authorize]
//[InitializeSimpleMembership]
public partial class AccountController : Controller
and added this code to global.asax under Application_Start
WebSecurity.InitializeDatabaseConnection(
connectionStringName: "DefaultConnection",
userTableName: "UserProfile",
userIdColumn: "UserID",
userNameColumn: "UserName",
autoCreateTables: true);
in my sql database the application created some tables on of them was Roles and UserInRoles just added the roles I needed like Admin, customer, etc...
and I restrict the access to some Controllers or Actions by adding this code
[Authorize(Roles = "Admin")]
public class MessagesController : Controller

Connect Mvc3 project with a database

I have problems to connect my model with database, I was reading tutorials, but any example works.
My files:
Web Config
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<connectionStrings>
<add name="CancionContext" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|Canciones.mdf;User Instance=true" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear />
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<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.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Cancion.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace BibliotecaMusica.Models
{
public class Cancion
{
public int ID { get; set; }
public string Nombre { get; set; }
public string Autor { get; set; }
}
public class CancionContext : DbContext
{
public DbSet<Cancion> Canciones { get; set; }
}
}
CancionesController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BibliotecaMusica.Models;
namespace BibliotecaMusica.Controllers
{
public class CancionesController : Controller
{
CancionContext db = new CancionContext();
public ViewResult Index()
{
return View(db.Canciones.ToList());
}
}
}
View Index of CancionesController
#model IEnumerable<BibliotecaMusica.Models.Cancion>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th></th>
<th>
Nombre
</th>
<th>
Autor
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
#Html.ActionLink("Details", "Details", new { id=item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
<td>
#item.Nombre
</td>
<td>
#item.Autor
</td>
</tr>
}
</table>
The database Canciones.mdf is already created and the table Cancion is created too.
I get the following exception EntityCommandExecution was unhandled by user code
In the browser the message is :
Invalid object name 'dbo.Cancions'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.Cancions'.
Source Error:
Line 17: public ViewResult Index()
Line 18: {
Line 19: return View(db.Canciones.ToList());
Line 20: }
Line 21:
I don´t know what is wrong with my project.
I think your problem is in your connection string. Check this answer
https://stackoverflow.com/a/173375/3467053
Or in the server explorer you can open a new connection to your db and check the connection string that the wizzard generates.
Hope this helps.

Umbraco Overriding or extending default membership provider

I want to use a different provider in Umbraco 6.1.6, e.g. I have this
<membership defaultProvider="UmbracoMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear />
<add name="UmbracoMembershipProvider" type="umbraco.providers.members.UmbracoMembershipProvider" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" defaultMemberTypeAlias="Website" passwordFormat="Hashed" umbracoApprovePropertyTypeAlias="isActive" umbracoLastLoginPropertyTypeAlias="loginDate" />
<add name="UsersMembershipProvider" type="umbraco.providers.UsersMembershipProvider" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" />
</providers>
</membership>
but I want to use this
<membership defaultProvider="TechBureauMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear/>
<add name="TechBureauMembershipProvider" type="TechBureau.Web.providers.TechBureauMembershipProvider" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" defaultMemberTypeAlias="Website" passwordFormat="Hashed" umbracoApprovePropertyTypeAlias="isActive" umbracoLastLoginPropertyTypeAlias="loginDate"/>
<add name="UsersMembershipProvider" type="umbraco.providers.UsersMembershipProvider" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false"/>
</providers>
</membership>
Because I want to override the ResetPassword password function to not do anything.
public class TechBureauMembershipProvider : UmbracoMembershipProvider
{
/// <summary>
/// Overriding this so that it does nothing, reseting a password to a random password isn't cool for anyone.
/// </summary>
/// <param name="username"></param>
/// <param name="answer"></param>
/// <returns></returns>
public override string ResetPassword(string username, string answer)
{
return string.Empty; //base.ResetPassword(username, answer);
}
}
But the problem is the Members tab doesn't load if I do this.
David is on the right path but I don't believe reflection overwrite is necessary here.
Change the type of UmbracoMembershipProvider but leave the name the same.
<membership defaultProvider="TechBureauMembershipProvider" userIsOnlineTimeWindow="2880">
<providers>
<clear/>
<add name="UmbracoMembershipProvider" type="TechBureau.Web.providers.TechBureauMembershipProvider" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" defaultMemberTypeAlias="Member" passwordFormat="Hashed"/>
<add name="UsersMembershipProvider" type="umbraco.providers.UsersMembershipProvider" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" passwordFormat="Hashed"/>
I think the "umbraco.cms\businesslogic\member\Member.cs" file hardcodes the provider name to:
public static readonly string UmbracoMemberProviderName = "UmbracoMembershipProvider";
So you might have to override the function using reflection.

MVC3 Could not find schema information for the element 'entityFramework' when using EF 5.0

I found the following messages in my we.config file after looking for a couple of minutes to see why my database was not seeding.
The complete message list is as follows:
Message 1 Could not find schema information for the element 'entityFramework'.
Message 2 Could not find schema information for the element 'defaultConnectionFactory'.
Message 3 Could not find schema information for the at'type'.
Now I am extremely new to MVC, and this is my first application that I have ever built. I want to utilize the Code First Technologies available to create the database from my models that I have built.
Here is an Example of a model I Created:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
namespace TNTMVC.Models.UECDECZA.BaseTables
{
public class Actions
{
[Key]
public int ActionID { get; set; }
[Timestamp]
public DateTime ActionDateCreated { get; set; }
[Required]
[DefaultValue(true)]
public bool ActionActive { get; set; }
[Required]
public string ActionName { get; set; }
[Required]
[DefaultValue(true)]
public bool ActionRequiresComponents { get; set; }
[Required]
[DefaultValue(1000)]
public int ActionListOrder { get; set; }
}
}
Then I created my DB Context Class which looks like this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using TNTMVC.Models.UECDECZA.BaseTables;
using TNTMVC.Models.UECDECZA.DataTables;
namespace TNTMVC.Models.UECDECZA
{
public class UecdeczaContext : DbContext
{
public DbSet<Actions> Actions { get; set; }
public DbSet<Application> Application { get; set; }
public DbSet<Area> Area { get; set; }
}
}
And here is my Web.Config file:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
<add name="UecdeczaContext" connectionString="Data Source=.\SQLExpress;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="1.0.0.0" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear />
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<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.Routing" />
<add namespace="System.Web.WebPages" />
<add namespace="System.Data.Entity" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=.\SQLEXPRESS; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
This is suppose to be a successful model implementation right? But it doesn't seem to work at all. It's not seeding my Database and it's not working :(
I have also Asked the same Question on ASP forumns: My ASP Forum Question
You don't seem to have an initializer (other than the default one) that is calling a Seed() method. See Julia Lerman's blog post on seeding for more info. You need something like:
public class UecdeczaInitializer : DropCreateDatabaseIfModelChanges<UecdeczaContext >
{
protected override void Seed(UecdeczaContext context)
{
new List<Actions>
{
new Actions
{
ActionName = "My action name"
}
}
}.ForEach(b => context.Blogs.Add(b));
base.Seed(context); }
}
You might need to stick more properties in there to seed your Actions entities, but that's the basic idea.

Resources