Roles.GetRolesForUser() returns empty array - c#

I'm using Roles.GetRolesForUser() and when I call it I get {string[0]}. However, when I type in a users name as a hard coded string like this: Roles.GetRolesForUser("theloggedinusersname"), I get {string[2]} [0]: "AccountingAdmin" [1]: "Admin". For the record, I also get values for Roles.IsUserInRole and User.Identity.
Here is how I have my Web.config set up:
<roleManager enabled="true" defaultProvider="DefaultRoleProvider">
<providers>
<clear/>
<add connectionStringName="DefaultConnection"
applicationName="[MyAppName]"
name="DefaultRoleProvider"
type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=[MyPublicKeyToken]" />
</providers>
</roleManager>
Clue: "theloggedinusersname" is not equal to User.Identity.Name.

Related

C# GetAllUsers() Item has already been added. Key in dictionary error

I am new to C# using Membership to handle users.
I inherited code I didn't write.
The code is trying to get all users so it can show all in a table. The other option it is trying to do is show each letter in the alphabet to filter by letter.
Here is the code:
private void Page_PreRender()
{
if (Alphalinks.Letter == "All")
{
Users.DataSource = Membership.GetAllUsers();
}
else
{
Users.DataSource = Membership.FindUsersByName(Alphalinks.Letter + "%");
}
Users.DataBind();
}
The error I am running into is on this line:
Users.DataSource = Membership.GetAllUsers();
When I run the page it generates the error:
Item has already been added. Key in dictionary: '2309' Key being added: '2309'.
The stack trace is:
System.Collections.Hashtable.Insert(Object key, Object nvalue, Boolean add) +14328157
System.Web.Security.MembershipUserCollection.Add(MembershipUser user) +268
System.Web.Providers.DefaultMembershipProvider.GetAllUsers(Int32 pageIndex, Int32 pageSize, Int32& totalRecords) +315
System.Web.Security.Membership.GetAllUsers() +37
ASP.admin_access_users_aspx.Page_PreRender() in x:\xxxxx\xxxPM\Admin\access\users.aspx:9
System.EventHandler.Invoke(Object sender, EventArgs e) +0
System.Web.UI.Control.OnPreRender(EventArgs e) +11725240
System.Web.UI.Control.PreRenderRecursiveInternal() +132
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4005]
I have looked on StackOverflow for a similar situation and was told it is caused by having duplicate user names... usually in a Lowercase field.
My issue is I don't know where this is coming from. I don't have any '2309' in my users or membership tables.
My default connection in web.config is:
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=xxxxxx;Initial Catalog=xxxPM;Persist Security Info=True;User ID=sa;Password=xxxx" />
The following in web.config point to this DefaultConnection:
<profile defaultProvider="DefaultProfileProvider">
<providers>
<add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 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=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordFormat="Clear" applicationName="/" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="DefaultRoleProvider">
<providers>
<add connectionStringName="DefaultConnection" applicationName="/" name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</providers>
</roleManager>
The SQL database in this connection has a Users table and a Membership table. I've done queries like this for the Users and Memberships tables:
SELECT COUNT(username) cnt,
Lower(Username) as Username
FROM [xxxxPMTest].[dbo].[Users]
GROUP BY UserName
HAVING COUNT(username) > 1
To verify I have unique users. 0 records returned.
I cannot find any duplicates.
I've tried commenting out the Users.Datasource = Membership.GetAllUsers(); and the page will load showing all of the Alphabet letters separated for filtering. Clicking on each letter correctly filters users and none of the pages have any errors (which I would expect to find if there actually was a duplicate entry). I can't figure out why I get this error.
What am I doing wrong? What can I add to check if the key already exists in Membership.GetAllUsers before adding it to Users.Datasource? Is that even the correct approach?
-- edited SQL query --

Could not load type '...' from assembly 'System.Web, ...'

<system.web>
<profile defaultProvider="TestProfileProvider" inherits="Test.Library.UserAccountProvider.TestUserProfile">
<providers>
<add name="TestProfileProvider" type="Test.Library.UserAccountProvider.TestProfileProvider, , Test.Library.UserAccountProvider" connectionStringName="SecurityContext" applicationName="Sigma" applicationContext="XpressPago" />
</providers>
</profile>
<membership defaultProvider="TestMembershipProvider">
<providers>
<add name="TestMembershipProvider" type="Test.Library.UserAccountProvider.TestMembershipProvider, Test.Library.UserAccountProvider" connectionStringName="SecurityContext" passwordFormat="Clear" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="3" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="Sigma" PasswordResetLimit="45" applicationContext="XpressPago" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="TestRoleProvider">
<providers>
<add name="TestRoleProvider" type="Test.Library.UserAccountProvider.TestRoleProvider" connectionStringName="SecurityContext" applicationName="Sigma" applicationContext="XpressPago" />
</providers>
</roleManager>
<httpRuntime executionTimeout="90" maxRequestLength="1048576" useFullyQualifiedRedirectUrl="false" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100"/>
<machineKey validationKey="196975F087819B74AC983A6D0882E5936BD0F30915A770C58E1177505D72D46F2D6F50BDB35DDF4E904AE01FD3E62726A6E63ADED231644D2D2E595A84AA76B2" decryptionKey="4496E865CAED30BA35BE7B60A06023CC3A13422F15060346" validation="SHA1" />
</system.web>
TestMembershipProvider is not showing any error but TestUserProfile is showing the following error:
Could not load type
'Test.Library.UserAccountProvider.TestUserProfile' from assembly
'System.Web, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a'.
on statement return (TestUserProfile)Create(username);
Maybe you should add the full assembly name (", Test.Library.UserAccountProvider") at the end of 'type' attribute of the line with name="TestProfileProvider" if its the location of your class ?
Like this :
<add name="TestProfileProvider" type="Test.Library.UserAccountProvider.TestProfileProvider, Test.Library.UserAccountProvider" connectionStringName="SecurityContext" applicationName="Sigma" applicationContext="XpressPago" />
And the same for the 'inherits' attribute :
<profile defaultProvider="TestProfileProvider" inherits="Test.Library.UserAccountProvider.TestUserProfile, Test.Library.UserAccountProvider">
I think Create does not where to pick the class since it tries in "System.Web".
Of course I suppose Test.Library.UserAccountProvider is the right assembly name, fix it if needed...

Login attempt restriction

I am using membership tag for login attempt restriction after 3 times given wrong password in web.config file. But it is not working please help me
this is my web.config file below code is I given but it is not working
<connectionStrings>
<add name="mydb" connectionString="Data Source=mydbcnt;Initial Catalog=19052015;Integrated Security=True" providerName="System.Data.SqlClient" ></add>
</connectionStrings>
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="3" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/>
</providers>
</membership>
Add a <clear/> tag before adding your provider.
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" [...]/>
</providers>
</membership>
As stated here, the section within the web.config file is implemented as a collection, and so it is possible to register multiple providers at the same time, includig the ones created by ASP.NET in the root web.config file on your machine.

EnablePasswordReset in Membership

I'd like to reset user password. I've a method like the following code. EnablePasswordReset does not overwrite because It's abstract. I've already changed web.config. But still take a error :
Password reset is not enabled. Set the EnablePasswordReset property of
the membership provider to true.
How to EnablePasswordReset value set true?
public static string ResetCurrentUserPassword(string userName)
{
MembershipProvider p = (MembershipProvider)Membership.Providers["Default"];
//p.EnablePasswordReset value false;
MembershipUser obj = Membership.GetUser(userName);
return obj.ResetPassword();
}
web.config
<siteMap defaultProvider="SitefinitySiteMap">
<providers>
<add name="SitefinitySiteMap" type="Telerik.Sitefinity.Web.SitefinitySiteMap, Telerik.Sitefinity" enablePasswordReset="true" taxonomyProvider="OpenAccessDataProvider" pageTaxonomy="Pages" rootNode="FrontendSiteMap" pageProvider="OpenAccessDataProvider"/>
</providers>
</siteMap>
<roleManager enabled="false"/>
<membership defaultProvider="Default">
<providers>
<clear/>
<add name="Default" type="Telerik.Sitefinity.Security.Data.SitefinityMembershipProvider, Telerik.Sitefinity" enablePasswordReset="true"/>
</providers>
</membership>
Set in your web.config file;
enablePasswordReset="true"
Check out MSDN example;
<membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="20">
<providers>
<add name="SqlProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="SqlServices"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
passwordFormat="Hashed"
applicationName="MyApplication" />
</providers>
</membership>
You said, you done it before, please check in your codebehind like this;
if (!Membership.EnablePasswordReset)
{
}
Check your membership is really using it or not.

Error in role redirection

I am trying to make an access role in my system. I have these two roles ; Admin and user. In my login page, I put this line of code:
if (Roles.IsUserInRole(Login1.UserName, "Administrator"))
Response.Redirect("~/4_Admin/Page1.aspx");
else if (Roles.IsUserInRole(Login1.UserName, "Users"))
Response.Redirect("~/3_User/Expense.aspx");
When user role logged in, they are directed to the correct page but for the admin, it gives me this error,
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Self_studies/login.aspx
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="Connection" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" applicationName="SampleApplication"/>
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="Connection" applicationName="SampleApplication"/>
</providers>
</profile>
<roleManager enabled="true">
<providers>
<clear />
<add connectionStringName="Connection" applicationName="SampleApplication"
name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" />
</providers>
</roleManager>
<compilation debug="false">
<assemblies>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Forms" />
I think I have checked the name and went through all the coding for so many times. Is there anything that I can do to fix this? Thank you.
Reference this- Examining ASP.NET's Membership, Roles, and Profile
try to configure your role manager as:
<roleManager enabled="true"
defaultProvider="CustomizedRoleProvider">
<providers>
<add name="CustomizedRoleProvider"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="MyDB"
applicationName="/" />
</providers>
</roleManager>
and at login button check user role as: Ref: Validation on current user
if (HttpContext.Current.User.IsInRole("Administrators"))
Response.Redirect("~/PageA.aspx");
else
Response.Redirect("~/PageB.aspx");

Categories