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.
Related
Problem Statement:
Performing MVC CRUD operations using WCF Service.Everything was working fine with SOAP,but when i changed from SOAP to REST it is giving end point error.I suspect that there might be some problem with my webconfig..!!!
Exception Details:
"There was no endpoint listening at http://localhost:8733/Design_Time_Addresses/ALCMS.MasterConfigurationService/Service1/InsertAssetType that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details."
WCF REST service is hosting properly and it is running.I'm getting the exception mentioned above in WCF REST Service method calls in controller like :
objSvcMasterConfig.InsertAssetType(objAssetTypeDC);
objSvcMasterConfig.UpdateAssetType(objAssetTypeDC);
objSvcMasterConfig.DeleteAssetType(objAssetTypeDC);
What i'm doing wrong??
I'm having two projects in Solution
WCF Service library
MVC Razor application
1. WCF Service Library:
IService1.cs
Data Contract:
[DataContract]
public class AssetTypeDC
{
[DataMember]
public int ID { get; set; }
[DataMember]
public int AssetTypeID { get; set; }
[DataMember]
public string Name { get; set; }
}
Service Contract:
[ServiceContract]
public interface IService1
{
#region Asset Type
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "InsertAssetType")]
bool InsertAssetType(AssetTypeDC objAssetTypeDC);
[WebInvoke(Method = "PUT",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "UpdateAssetType")]
[OperationContract]
bool UpdateAssetType(AssetTypeDC objAssetTypeDC);
[WebInvoke(Method = "DELETE",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "DeleteAssetType")]
[OperationContract]
bool DeleteAssetType(AssetTypeDC objAssetTypeDC);
#endregion
}
Service.cs
public bool InsertAssetType(AssetTypeDC objAssetTypeDC)
{
try
{
objAssetType.ID = objAssetTypeDC.ID;
objAssetType.AssetTypeID = objAssetTypeDC.AssetTypeID;
objAssetType.Name = objAssetTypeDC.Name;
dbEntity.AssetTypes.Attach(objAssetType);
var entry = dbEntity.Entry(objAssetType);
dbEntity.AssetTypes.Add(objAssetType);
dbEntity.SaveChanges();
return true;
}
catch
{
return false;
}
}
public bool UpdateAssetType(AssetTypeDC objAssetTypeDC)
{
try
{
objAssetTypeID = ID;
objAssetType.AssetTypeID = objAssetTypeDC.AssetTypeID;
objAssetType.Name = objAssetTypeDC.Name;
dbEntity.AssetTypes.Attach(objAssetType);
var entry = dbEntity.Entry(objAssetType);
entry.Property(e => e.Name).IsModified = true;
dbEntity.SaveChanges();
return true;
}
catch
{
return false;
}
}
public bool DeleteAssetType(AssetTypeDC objAssetTypeDC)
{
try
{
objAssetType.AssetTypeID = objAssetTypeDC.AssetTypeID;
objAssetType.ID = objAssetTypeDC.ID;
dbEntity.AssetTypes.Attach(objAssetType);
dbEntity.Entry(objAssetType).State = EntityState.Deleted;
dbEntity.SaveChanges();
return true;
}
catch
{
return false;
}
}
App.Config:
<?xml version="1.0" encoding="utf-8"?>
<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>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" />
</system.web>
<system.serviceModel>
<services>
<service name="ALCMS.MasterConfigurationService.Service1" behaviorConfiguration="ALCMS.MasterConfigurationService.Service1Behaviour">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8733/Design_Time_Addresses/ALCMS.MasterConfigurationService/Service1/" />
</baseAddresses>
</host>
<endpoint address="" binding="webHttpBinding" contract="ALCMS.MasterConfigurationService.IService1" behaviorConfiguration="ALCMS.MasterConfigurationService.RESTEndpointBehaviour">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="ALCMS.MasterConfigurationService.RESTEndpointBehaviour">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ALCMS.MasterConfigurationService.Service1Behaviour">
<serviceMetadata httpGetEnabled="True" httpsGetEnabled="True" />
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<connectionStrings><add name="DB_V2Entities" connectionString="metadata=res://*/Entities.MasterConfigurationEntity.csdl|res://*/Entities.MasterConfigurationEntity.ssdl|res://*/Entities.MasterConfigurationEntity.msl;provider=System.Data.SqlClient;provider connection string="data source=SQL-PC\SQLEXPRESS;initial catalog=DB_V2;user id=sa;password=Sql#123;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings></configuration>
2.MVC Application
Controller:
Insert Operation:
[HttpPost]
public ActionResult Create(AssetTypeModel assettypemodel)
{
if (ModelState.IsValid)
{
objAssetTypeDC.ID = 1;
objAssetTypeDC.AssetTypeID = assettypemodel.ID;
objAssetTypeDC.Name = assettypemodel.Name;
objSvcMasterConfig.InsertAssetType(objAssetTypeDC);
return RedirectToAction("Index");
}
return View(assettypemodel);
}
Update Operation:
[HttpPost]
public ActionResult Edit(AssetTypeModel assettypemodel, int id, int ID)
{
if (ModelState.IsValid)
{
objAssetTypeDC.ID = assettypemodel.ID = ID;
objAssetTypeDC.AssetTypeID = assettypemodel.AssetTypeID = id;
objAssetTypeDC.Name = assettypemodel.Name;
objSvcMasterConfig.UpdateAssetType(objAssetTypeDC);
return RedirectToAction("Index");
}
return View(assettypemodel);
}
Delete Operation:
public ActionResult Delete(int id = 0, int ID = 0)
{
AssetTypeModel assettypemodel = db.AssetType.Find(id, ID);
if (assettypemodel == null)
{
return HttpNotFound();
}
return View(assettypemodel);
}
Web.Config:
<?xml version="1.0" encoding="utf-8"?>
<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="DB" connectionString="Data Source=SQL-PC\SQLEXPRESS;initial catalog=DB_V2;Persist Security Info=True;User ID=sa;Password=Sql#123;Pooling=False;" providerName="System.Data.SqlClient" />
<add name="DBEntities" connectionString="metadata=res://*/Entities.WebEntity.csdl|res://*/Entities.WebEntity.ssdl|res://*/Entities.WebEntity.msl;provider=System.Data.SqlClient;provider connection string="data source=SQL\SQLEXPRESS;initial catalog=DB_V2;user id=sa;Password=Sql#123;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings>
<appSettings>
<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" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5"><assemblies><add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /></assemblies></compilation>
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms">
<forms loginUrl="~/Login" protection="All" timeout="2880" />
</authentication>
<sessionState mode="InProc" timeout="30" stateConnectionString="tcpip=SQL-PC\SQLEXPRESS,1433" cookieless="false" regenerateExpiredSessionId="false" />
<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" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<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%\Microsoft.NET\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%\Microsoft.NET\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="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="1.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>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="WebHttpBinding_IService1" />
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="ALCMS.MasterConfigurationService.RESTEndpointBehaviour">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint address="http://localhost:8733/Design_Time_Addresses/ALCMS.MasterConfigurationService/Service1/" binding="webHttpBinding" bindingConfiguration="WebHttpBinding_IService1" behaviorConfiguration="ALCMS.MasterConfigurationService.RESTEndpointBehaviour" contract="MasterConfigurationServiceReference.IService1" name="WebHttpBinding_IService1" />
</client>
</system.serviceModel>
</configuration>
Mr Vishal,
Instead of converting, you can develop in REST only.
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.
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.
I created custom membership and custom role provider follow exact same this link:
for custom membership:
http://msdn.microsoft.com/en-us/library/6tc47t75(v=vs.100).aspx
more info:
http://msdn.microsoft.com/en-us/library/ms366730(v=vs.100).aspx
for custom role provider:
http://msdn.microsoft.com/en-us/library/317sza4k(v=vs.100).aspx
more info:
http://msdn.microsoft.com/en-us/library/tksy7hd7(v=vs.100).aspx
and i have a SimpleMembershipInitializer
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Threading;
using WebMatrix.WebData;
using TestProject.Web.Models;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace TestProject.Web.Filters
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
{
private static SimpleMembershipInitializer _initializer;
private static object _initializerLock = new object();
private static bool _isInitialized;
public override void OnActionExecuting(HttpActionContext actionContext)
{
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
}
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null);
try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("TestProjectEntities", "Users", "UsrID","UsrLoginName", autoCreateTables: false);
}
catch (Exception ex)
{
throw ex;
}
}
}
}
}
and i wrote a web api for login:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using TestProject.Web.Models;
using TestProject.Web.Filters;
using System.Configuration;
namespace TestProject.Web.Controllers
{
[Authorize]
[InitializeSimpleMembership]
public class APIAccountController : ApiController
{
[System.Web.Http.AcceptVerbs("GET", "POST")]
[System.Web.Http.HttpGet]
[System.Web.Http.HttpPost]
[System.Web.Http.AllowAnonymous]
[System.Web.Mvc.ValidateAntiForgeryToken]
public string Login(string UserName, string Password, bool RememberMe)
{
if (WebSecurity.Login(UserName, Password, persistCookie: RememberMe))
{
return "OK";
}
return "Failed";
}
}
}
and my web.config is:
<?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=169433
-->
<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=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<!--<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-TestProject.Web-20130430091159;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-TestProject.Web-20130430091159.mdf" providerName="System.Data.SqlClient" />-->
<add name="TestProjectEntities" connectionString="Data Source=.;Initial Catalog=TestProject;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<appSettings>
<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="enableSimpleMembership" value="false"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms">
<forms protection="All" loginUrl="/" timeout="2880" requireSSL="false" slidingExpiration="true" cookieless="UseCookies">
<credentials passwordFormat="SHA1" />
</forms>
</authentication>
<authorization>
<!--<deny users="?" lockAllAttributesExcept="AllowAnonymous" />-->
<allow users="*"/>
</authorization>
<machineKey validationKey="C50B3C89CB21F4F1422FF158A5B42D0E8DB8CB5CDA1742572A487D9401E3400267682B202B746511891C1BAF47F8D25C07F6C39A104696DB51F17C529AD3CABE"
decryptionKey="8A9BE8FD67AF6979E7D20198CFEA50DD3D3799C77AF2B72F"
validation="SHA1" />
<membership defaultProvider="UsersMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear />
<add
name="UsersMembershipProvider"
type="TestProject.Web.Utility.UsersMembershipProvider"
connectionStringName="TestProjectEntities"
applicationName="TestProject"
enablePasswordRetrieval="true"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
requiresUniqueEmail="true"
passwordFormat="Hashed" />
</providers>
</membership>
<roleManager defaultProvider="UsersRoleProvider"
enabled="true"
cacheRolesInCookie="true"
cookieName=".ASPROLES"
cookieTimeout="30"
cookiePath="/"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
cookieProtection="All" >
<providers>
<clear />
<add
name="UsersRoleProvider"
type="TestProject.Web.Utility.UsersRoleProvider"
connectionStringName="TestProjectEntities"
applicationName="TestProject"
writeExceptionsToEventLog="false" />
</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.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<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%\Microsoft.NET\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%\Microsoft.NET\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="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="1.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>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters>
<parameter value="System.Data.SqlServerCe.4.0" />
</parameters>
</defaultConnectionFactory>
<!--<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>-->
</entityFramework>
</configuration>
after run api with this link:
/api/APIAccount/Login/?UserName=test1&Password=123456&RememberMe=true
its give me error:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
To call this method, the "Membership.Provider" property must be an instance of "ExtendedMembershipProvider".
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
at WebMatrix.WebData.WebSecurity.VerifyProvider()
at WebMatrix.WebData.WebSecurity.Login(String userName, String password, Boolean persistCookie)
at TestProject.Web.Controllers.APIAccountController.Login(String UserName, String Password, Boolean RememberMe)
in c:\Visual Studio 2012\Projects\TestProject\TestProject.Web\Controllers\APIAccountController.cs:line 30
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.<>c__DisplayClass5.<ExecuteAsync>b__4()
at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)
</StackTrace>
</Error>
I check it and see that CustomRoleManager Initializer not run in Web API and when i use view and not web api, its ok.
What should i do?
I uploaded test project in http://filebin.net/k8cqbyltac and it made by VS 2012, C#, MVC4, .Net 4.5
plaese check this URL after run for seeing error:
/api/APIAccount/Login/?UserName=test1&Password=123456&RememberMe=true
After inspecting your source I found the culprit:
Your Membership class should inherit from ExtendedMembershipProvider instead of MembershipProvider.
The WebSecurity class works with this base-class instead of the MembershipProvider, if your class doesn't inherit from that class, it will get a null-reference and it correctly tells you that it doesn't have a reference to an object of the correct type.
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.