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 --
Related
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.
I have a web service application written in asp.net c# and with a MySQL database. I am using the MySQL providers (v6.9.4.0) for memberships, roles and profiles. For the profile, I am using this to store 7 properties, name, company etc.
I am able to connect and access the database fine, read all users and all other information so far. I am able to create user accounts and delete them with no issues, and all the profile properties are saved correctly in 'my_aspnet_profiles' table.
However, when I try to change some of the properties on an existing account, I get the following exception (including stack trace):
System.Web.HttpUnhandledException (0x80004005): Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.Configuration.Provider.ProviderException: Profile update failed. ---> MySql.Data.MySqlClient.MySqlException: Column 'lastUpdatedDate' cannot be null
at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId)
at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()
at MySql.Web.Profile.MySQLProfileProvider.SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection)
--- End of inner exception stack trace ---
at MySql.Web.Profile.MySQLProfileProvider.SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection)
at System.Configuration.SettingsBase.SaveCore()
at System.Configuration.SettingsBase.Save()
at System.Web.Profile.ProfileBase.SaveWithAssert()
at System.Web.Profile.ProfileBase.Save()
at Cylon.QuoteEngine.Application.Web.AccountManager.SaveUserProfile(String username, CylonProfile customProfile) in C:\Work\Web\AccountManager.cs:line 86
This works when I am using a MySQL instance hosted on my local machine, but when I attempt to run the app with the database hosted on a server, I am getting the exception.
Here is where I am attempting to save the user profile:
public void SaveUserProfile(string username, CylonProfile customProfile)
{
var profile = ProfileBase.Create(username);
profile.SetPropertyValue("Name", customProfile.Name);
profile.SetPropertyValue("Company", customProfile.Company);
...
profile.Save();
}
In my web.config file, the providers are declared as:
MembershipProvider:
<membership defaultProvider="MySqlMembershipProvider">
<providers>
<clear />
<add name="MySqlMembershipProvider" type="MySql.Web.Security.MySQLMembershipProvider, MySql.Web,Version=6.9.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" connectionStringName="ApplicationServices" enablePasswordRetrieval="true" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" passwordFormat="Encrypted" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" autogenerateschema="true" />
</providers>
</membership>
ProfileProvider:
<profile enabled="true" defaultProvider="MySqlProfileProvider">
<properties>
<add name="Name" type="String" />
<add name="Company" type="String" />
...
</properties>
<providers>
<clear />
<add name="MySQLProfileProvider" type="MySql.Web.Profile.MySQLProfileProvider, MySql.Web, Version=6.9.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" applicationName="/" connectionStringName="ApplicationServices" autogenerateschema="True" description="" writeExceptionsToEventLog="False" enableExpireCallback="False" />
</providers>
</profile>
RoleProvider:
<roleManager enabled="true" defaultProvider="MySqlRoleProvider">
<providers>
<clear />
<add connectionStringName="ApplicationServices" applicationName="/" name="MySqlRoleProvider" type="MySql.Web.Security.MySQLRoleProvider, MySql.Web,Version=6.9.4.0, Culture=neutral,PublicKeyToken=c5687fc88969c44d" autogenerateschema="true" />
</providers>
</roleManager>
I was under the assumption that the 'lastUpdatedDate' column would be updated automatically and I wouldn't have to do any coding to set this value, or do I? Can anyone explain why it's happening on the hosted server, and not on my local machine? What can I do to fix it?
If you need any more info, let me know and I can add it.
Sorry not enough reputation to comment, but you could have look here, it looks related:
How do you set a default value for a MySQL Datetime column?
Update
Could be related to a bug in MySql v5.6.19 bugs.mysql.com/bug.php?id=68472
If select ##explicit_defaults_for_timestamp; returns 1 try changing the value to 0 in my.ini file.
The file is usually located at C:\Program Files\MySQL\MySQL Server x.xx\my.ini
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.
i have an application that uses membership schema 6.
When i try to add a user on code behind with membership.CreateUser i get error 11 "Provider error".
In my application Membership.UserValidate, Membership.GetUser, Membership.ChangePassword etc. work fine.
Even Role.AddUserToRole works fine without having created the user.
I have the following settings in the web.config:
<membership defaultProvider="MySQLMembershipProvider">
<providers>
<remove name="MySQLMembershipProvider" />
<add name="MySQLMembershipProvider" type="MySql.Web.Security.MySQLMembershipProvider, MySql.Web, Version=6.3.6.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"
applicationName="/myApp" description="MySQL myApp" connectionStringName="LocalMySqlServer" writeExceptionsToEventLog="False" autogenerateschema="True"
enablePasswordRetrieval="True" enablePasswordReset="True" requiresQuestionAndAnswer="False" requiresUniqueEmail="True" passwordFormat="Encrypted"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression="" />
</providers>
</membership>
Any ideas?
Thanks
I got the error because I added columns to one of the created membership tables. After removing the columns all worked fine.
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");