Unable to cast object of type 'System.Web.Security.SqlRoleProvider' to type 'WebMatrix.WebData.SimpleRoleProvider' - sql-server

I developing an mvc web app with Entity Frame]work. I've enabled database migration so that i can add some seed data on each update.
More specifically, i want to add two users and two roles; so the configuration file looks like this:
var roles = (SimpleRoleProvider)Roles.Provider;
var membership = (SimpleMembershipProvider)Membership.Provider;
//// create two roles
if (!roles.RoleExists("Admin"))
{
roles.CreateRole("Admin");
}
if (!roles.RoleExists("User"))
{
roles.CreateRole("User");
}
However there seems to be a problem during the casting; it throws an exception
Unable to cast object of type 'System.Web.Security.SqlRoleProvider' to type 'WebMatrix.WebData.SimpleRoleProvider'.
I suspect that this might be a configuration issue, but i'm not really sure. Does anyone stumbled across the same problem?

That's because SqlRoleProvider does not inherit SimpleRoleProvider. However, you can try using SimpleRoleProvider Constructor (RoleProvider):
var roles = new SimpleRoleProvider(Roles.Provider);

I sorted this out. The problem apparently was related to web configuration. I added the following lines to the web.config file:
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
to explicitly set the role provider. So now the Roles.Provider returns an instance of WebMatrix.WebData.SimpleRoleProvider; thus i don't need to cast any more

I solved this by placing below code in web.config between
<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>

Related

Problem with mxEditor and xml configuration file

I'm trying to use mxGraph editor. I read the examples and try to understand it. But I can't. From the the tutorial page, in the "port.html" file, they describe the way that they load an xml file for configure an editor. To sum up, they have this configuration file:
<mxEditor>
<mxDefaultKeyHandler as="keyHandler">
<add as="8" action="collapse"/>
<add as="13" action="expand"/>
<add as="33" action="exitGroup"/>
<add as="34" action="enterGroup"/>
<add as="35" action="refresh"/>
<add as="36" action="home"/>
<add as="37" action="selectPrevious"/>
<add as="38" action="selectParent"/>
<add as="40" action="selectChild"/>
<add as="39" action="selectNext"/>
<add as="46" action="delete"/>
<add as="65" control="1" action="selectAll"/>
<add as="90" control="1" action="undo"/>
<add as="89" control="1" action="redo"/>
<add as="88" control="1" action="cut"/>
<add as="67" control="1" action="copy"/>
<add as="86" control="1" action="paste"/>
<add as="71" control="1" action="group"/>
<add as="85" control="1" action="ungroup"/>
<add as="113" action="edit"/>
<add as="123" action="showProperties"/>
<add as="107" action="zoomIn"/>
<add as="109" action="zoomOut"/>
</mxDefaultKeyHandler>
</mxEditor>
And in port.html, they put this :
var editor = new mxEditor();
var graph = editor.graph;
var model = graph.getModel();
editor.setGraphContainer(container);
var config = mxUtils.load('editors/config/keyhandler-commons.xml').getDocumentElement();
editor.configure(config);
Then, when I try to execute any oh this bindings with the associate action on my canvas, it doesn't work, and I realy don't know why.
Thank
I know I see that pretty late, but what I would do is:
var config = mxUtils.load('editors/config/keyhandler-commons.xml').getDocumentElement();
var editor = new mxEditor(config);
You may also not have to query for the graph in order to direct to your container.
mxGraph will do that for you if, in your config file, you have specified:
<ui>
<add as="graph" element="container"/>
...
</ui>

RIA Service Error in a Silverlight Application

In a very simple Silverlight Application I have a DomainService Class which has a single method that returns a list of Letter Objects.
The application works fine when I run it in VisualStudio. However, when I publish it to a folder on my Windows 10 local machine and run it using IIS (version 10.0.166299.5) I get the following error:
The remote server returned an error: NotFound.
at System.ServiceModel.DomainServices.Client.OperationBase.Complete(Exception error) at System.ServiceModel.DomainServices.Client.LoadOperation.Complete(Exception error) at System.ServiceModel.DomainServices.Client.DomainContext.CompleteLoad(IAsyncResult asyncResult) at System.ServiceModel.DomainServices.Client.DomainContext.<>c__DisplayClass1b.b__17(Object )
I supect this is due to something being wrong in missing in my WebConfig file. My WebConfig Currently looks like this:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.6" />
<httpRuntime targetFramework="4.6" />
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<add name="DomainServiceModule" preCondition="managedHandler" type="System.ServiceModel.DomainServices.Hosting.DomainServiceHttpModule, System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</modules>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
</configuration>
The code for my Domain Service Class is like this:
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.DomainServices.Hosting;
using System.ServiceModel.DomainServices.Server;
using SilverData.Web.Models;
namespace SilverData.Web.Services
{
[EnableClientAccess]
public class DrugsRiaService : DomainService
{
public IQueryable<Letter> GetAllLetters()
{
List<Letter> letters = new List<Letter>();
Letter letterA = new Letter { ID = 1, Statement = "Mike" };
Letter LetterB = new Letter { ID = 2, Statement = "Emma" };
Letter LetterC = new Letter { ID = 3, Statement = "Peter" };
letters.Add(letterA);
letters.Add(LetterB);
letters.Add(LetterC);
return letters.AsQueryable();
}
}
}
The error was due to the problem that .svc file wasn't being served.. The problem got solved with the kind help from the Kyle Abraham on Experts Exchange.
https://www.experts-exchange.com/questions/29084691/RIA-Service-Error-in-a-Silverlight-Application.html
The solution was to add the following line to the webserver section of the Webconfig
<handlers>
<add name=".svc" verb="*" path="*.svc" type="System.ServiceModel.Activation.ServiceHttpHandlerFactory, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</handlers>
I'm not sure, its a guess as I have not used RIA for awhile, but I think letters needs to returned as something other than queryable... try ToList() which causes the query to execute, and the payload is complete with the complete enumeration that was retrieved from the database. Remember, this is a remote call from a client, not a local one that can extend the queryable.

MVC 4 - after seeding database webpages_Roles is still empty

So I have basic MVC 4 Internet application project with Entity Framework 5.
I have configured WebSecurity that uses my table for users.
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "Users", "Id", "Email", autoCreateTables: true);
Then in my migration configuration class I seed DB with new roles and add users to them.
internal sealed class Configuration : DbMigrationsConfiguration<Infrastructure.KlepecV2Db>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(Infrastructure.KlepecV2Db context)
{
if(!Roles.RoleExists("Admin"))
{
Roles.CreateRole("Admin");
}
if (!Roles.RoleExists("Test1"))
{
Roles.CreateRole("Test1");
}
if(Membership.GetUser("user1") != null)
{
if(!Roles.IsUserInRole("user1","Admin"))
{
Roles.AddUserToRole("user1", "Admin");
}
}
if (Membership.GetUser("user2") != null)
{
if (!Roles.IsUserInRole("user2", "Admin"))
{
Roles.AddUserToRole("user2", "Admin");
}
}
}
}
So when I type "update-database" in NuGet console everything gets executed without errors. But if I look into webpages_Roles table its empty. Also webpages_UsersInRoles is empty.
For testing I have removed Role.RoleExists() calls and updating database fails, becouse roles already exists.
What am I missing here? Where are this roles stored?
I came across into an error The Role Manager feature has not been enabled mentioned by #Magnus. Hope this probably related to your roles issue in which the default role provider is unknown.
The error The Role Manager feature has not been enabled happened when I move the WebSecurity.InitializeDatabaseConnection method from MVC project into a class library (data access) for code first migration seed.
The point is App.config need to be configured for Package Manager Update-Database command to be run just like when Web.config exist.
Below is my App.config and Seed. Note that
I add "DefaultConnection" connection string *
Add system.web->roleManager to set the enable="true"
Add runtime->assemblyBinding->qualifyAssembly to give hint to compiler where is WebMatrix.WebData by giving the full assembly name.
App.config:
<?xml version="1.0" encoding="utf-8"?>
<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" requirePermission="false" />
</configSections>
<connectionStrings>
<!--<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Db;Persist Security Info=True;User=user;Password=pass" providerName="System.Data.SqlClient" />-->
</connectionStrings>
<system.web>
<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>
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<qualifyAssembly partialName="WebMatrix.WebData" fullName="WebMatrix.WebData, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
</configuration>
Seed Method:
protected override void Seed(DatabaseContext context)
{
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "Users", "Id", "Email", autoCreateTables: true);
if(!Roles.RoleExists("Admin"))
{
Roles.CreateRole("Admin");
}
if (!Roles.RoleExists("Test1"))
{
Roles.CreateRole("Test1");
}
if(Membership.GetUser("user1") != null)
{
if(!Roles.IsUserInRole("user1","Admin"))
{
Roles.AddUserToRole("user1", "Admin");
}
}
if (Membership.GetUser("user2") != null)
{
if (!Roles.IsUserInRole("user2", "Admin"))
{
Roles.AddUserToRole("user2", "Admin");
}
}
}
Hope this will help anyone with The Role Manager feature has not been enabled issue when using code first migration seed in a class library.
Update
* EF5 will read the connection string in Web.config of Mvc project but not in the App.config of the project with EF Migrations. However the membership and roleManager settings is still required in the EF Migration project.
Wanted to add my $0.02 to the conversation. I have a similar setup to CallMeLaNN, but was still getting the error. My solution was to set my "Data" project to a StartUp project. After that, my app.config file started getting picked up, and I can now seed my users from the Update-Database command.

Property 'attributeMapFailedPasswordAnswerLockoutTime' cannot be mapped to schema attribute 'lockoutTime' as the attribute is already in use

I am trying to use the ADMembershipProvider to connect to a local ADAM server and I am getting the error in the title. If I remove the enable password reset and the properties it relies on I am able to connect.
I have tried to google it and nothing has come up. Below is my provider config. Any advice would be highly appreciated.
<providers>
<add name="AspNetActiveDirectoryMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="ADService"
connectionUsername="[username]"
connectionPassword="[password]"
connectionProtection="Secure"
enableSearchMethods="true"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
applicationName="/"
description="Default AD connection"
requiresUniqueEmail="true"
clientSearchTimeout="30"
serverSearchTimeout="30"
attributeMapPasswordQuestion="department"
attributeMapPasswordAnswer="division"
attributeMapFailedPasswordAnswerCount="badPwdCount"
attributeMapFailedPasswordAnswerTime="badPasswordTime"
attributeMapFailedPasswordAnswerLockoutTime="lockoutTime"
attributeMapEmail = "mail"
attributeMapUsername = "userPrincipalName"
maxInvalidPasswordAttempts = "5"
passwordAttemptWindow = "10"
passwordAnswerAttemptLockoutDuration = "30"
minRequiredPasswordLength="7"
minRequiredNonalphanumericCharacters="1"/>
</providers>
FYI... The closest thing to a similar result was someone who got this error on a similar attribute and he just restarted the machine. That didn't work for me. I did find this article as well http://blogs.msdn.com/b/dansellers/archive/2005/10/20/483272.aspx but I am struggling to get the LDAP admin to make this change. Especially since we already have those properties.
I finally had the LDAP admin perform the steps in the following link an we are up and running.
http://blogs.msdn.com/b/dansellers/archive/2005/10/20/483272.aspx

Setting up BugTracker.NET complete noob

This is my first ASP.NET project and I'm stuck right away.
I'm setting up a bugtracker on a remote webhotel but I can't get the connectionstrings to work.
If we say that my host is called hosting.org and my website would be www.trallala.com
what do I have to change in this script?
<configSections>
</configSections>
<system.web>
<!--
BugTracker.NET is not compatible with Session serialization.
Timeout session after 120 minutes
-->
<sessionState mode="InProc" timeout="120"/>
<compilation debug="true">
<assemblies>
<add assembly="System.DirectoryServices.Protocols, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
<pages validateRequest="true" />
<!-- A few people over the years have needed to override the default IIS settings...
<httpRuntime executionTimeout="300" maxRequestLength="51200"/>
-->
<!-- for my testing <globalization culture="de-DE" uiCulture="en-US" /> -->
</system.web>
<appSettings>
<!--
********* QUICK START *************
If you want to get started quickly, then just change the following
and then try to log in:
ConnectionString
AbsouteUrlPrefix
After you can log in and create a bug, then you probably want to
set up the email integration. Set up the following:
ErrorEmailTo
ErrorEmailFrom
NotificationEmailEnabled
NotificationEmailFrom
And your SMTP settings below.
-->
<!--
Change this to point to your database
-->
<add key="ConnectionString" value="server=(local)\SQLEXPRESS;database=btnet;user id=sa;password=x;Trusted_Connection=no"/>
<!--
Used when creating absolute href's. For example, in notification emails.
Don't forget trailing slash!.
-->
<add key="AbsoluteUrlPrefix" value="http://127.0.0.1/btnet2/"/>
<!--
You can turn the logging and emailing of errors on and off.
Log file name is "btnet_log_yyyy_mm_dd.txt"
For the LogFileFolder setting, if you specify the folder starting with a
drive letter or the \\ that indicates a UNC path, it's treated as a full path.
For example: c:\\something or \\somemachine\something
Otherwise it's treated as a path relative to where you virtual directory is
located.
LogEnabled turns on and off logging as a whole.
LogSqlEnabled turns on and off just the logging of SQL statements, but
that's about 98% of what gets logged, so if you want to reduce the
volume, turn that off.
-->
<add key="LogEnabled" value="1"/>
<add key="LogSqlEnabled" value="1"/>
<add key="LogFileFolder" value="App_Data\logs"/>
<!-- If BugTracker.NET itself experiences an error, it can send an email notification -->
<add key="ErrorEmailEnabled" value="1"/>
<add key="ErrorEmailTo" value="YOUR EMAIL HERE"/>
<add key="ErrorEmailFrom" value="FROM EMAIL HERE"/>
<!--
You can "subscribe" to email notifications on a per-bug basis.
You will receive an email whenever the bug is updated.
-->
<add key="NotificationEmailEnabled" value="1"/>
<add key="NotificationEmailFrom" value="FROM EMAIL HERE"/>
<!--
This controls the format of the subject of the email notifications.
The available variables are:
$THING$ - from the "SingularBugLabel" setting
$BUGID$
$ACTION$ - added or changed
$SHORTDESC$
$PROJECT$
$CATEGORY$
$ORGANIZATION$
$PRIORITY$
$STATUS$
$TRACKINGID$ - from the "TrackingIdString" setting
-->
<add key="NotificationSubjectFormat" value="$THING$:$BUGID$ was $ACTION$ - $SHORTDESC$ $TRACKINGID$"/>
<!--
If you aren't using the local SMTP server that comes with IIS,
set the name, user, and password for your SMTP server here.
-->
<!-- Sample SMTP Settings -->
<!--
These settings work with my SBC account
-->
<!--
<add key="SmtpServer" value="smtp.att.yahoo.com"/>
<add key="SmtpServerAuthenticateUser" value="ctrager#sbcglobal.net"/>
<add key="SmtpServerPort" value="465"/>
<add key="SmtpUseSSL" value="1"/>
<add key="SmtpServerAuthenticatePassword" value="MY PASSWORD"/>
-->
<!--
These settings work with my GMail account
-->
<!--
<add key="SmtpServer" value="smtp.gmail.com"/>
<add key="SmtpServerAuthenticateUser" value="ctrager#gmail.com"/>
<add key="SmtpServerPort" value="465"/>
<add key="SmtpUseSSL" value="1"/>
<add key="SmtpServerAuthenticatePassword" value="MY PASSWORD"/>
-->
<!--
These settings work with my GoDaddy account
-->
<!--
<add key="SmtpServer" value="relay-hosting.secureserver.net"/>
<add key="SmtpServerAuthenticateUser" value="ctrager#ifdefined.com"/>
<add key="SmtpServerAuthenticatePassword" value="MY PASSWORD"/>
<add key="SmtpServerPort" value="25"/>
-->
<!--
Specify the pickup directory if you have the problem described here:
http://support.microsoft.com/default.aspx?scid=kb;en-us;816789#8
-->
<!--
<add key="SmtpServerPickupDirectory" value=""/>
<add key="SmtpSendUsing" value="1"/>
-->
<!--
Ignore this setting unless you are esperiencing the symptoms
related to this: http://cr.yp.to/docs/smtplf.html
-->
<!--
<add key="SmtpForceReplaceOfBareLineFeeds" value="1"/>
-->
<!--
By default, emails are UTF8 encoded. If that doesn't work for you,
uncomment the following.
-->
<!--
<add key="BodyEncodingUTF8" value="0"/>
-->
<add key="ConnectionString" value="Persist Security Info=true;User ID=bugtracker;Password=bugs;Initial Catalog=BugTracker;Data Source=[IP ADDRESS]" />
This is what you'd need to add/edit in the web.config. once it's setup, BugTracker will run the scripts to create the proper database elements.
You need to make sure that "ConnectionString" points to the right Database and has the right username and password for DB-access.
You might want to make sure that your Database is actually up and running and that the username and password are correct by simply trying to log in as that user in your DB.
If that doesn't work, than the problem doesn't lie with your asp.net configuration.
The BugTracker.NET documentation includes this section on connection strings:
The hardest part ...for most people is getting the ConnectionString to work.
For help, see these links, the "SqlConnection (.NET)" sections
http://www.connectionstrings.com/?carrier=sqlserver2005
http://www.sqlstrings.com/SQL-Server-connection-strings.htm
https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-3513_11-6084879.html
Another thing you might try to get the connection string right is the following:
Create a new blank file and name it test.udl.
Double click on it, and a "Data Link Properties" dialog should appear.
On "Providers" tab, select "Microsoft OLE DB Provider for SQL Server" or "SQL Native Client"
On "Connections" tab, try various settings and use the "Test Connection" button to test them. Click "Ok" when it works.
Open the test.udl file in Notepad and copy the line that starts with "Provider=" into your Web.config "ConnectionString" value, BUT delete the little part that says "Provider=SQLNCLI.1;"

Resources