ASP.NET username change - asp.net

I have an asp.net site which uses the ASP.net Membership provider. Each comment, entry etc in the DB is tracked by the userID.
Since MS doesn't provide a way to change the username, I've found the userNAME in the "users" table in the DB and there is only 1 place where the username appears.
My question is,
Is it safe to provide an "edit profile" page where the user is allowed to edit their own username. Of course i would handle this change in the background by directly changing the "username" value in the DB.
Are there any downsides to this ? I've created and modified some test accounts and it seems to be fine, i am just wondering if there is any known negatives to this before putting it into production.

cptScarlet's link was good, however I despise using stored procedures if I don't have to and I favor Entity Framework whenever possible. Here's what I did to change the user name, using EF 4.0 and .NET 4.0:
Right click project -> Add New Item -> ADO.NET Entity Data Model
Give it a proper name, I chose "MembershipModel.edmx" and click Add
Select Generate from database and click Next
Add the connection to your 'aspnetdb' database (the ASP.NET membership database)
Give it a proper name, I chose "MembershipEntities"
Click Next
Drill into Tables and select aspnet_Users
Change the Model Namespace to MembershipModel
Click Finish
Now you can add code to create the EF object context and modify the database:
public void ChangeUserName(string currentUserName, string newUserName)
{
using (var context = new MembershipEntities())
{
// Get the membership record from the database
var currentUserNameLowered = currentUserName.ToLower();
var membershipUser = context.aspnet_Users
.Where(u => u.LoweredUserName == currentUserNameLowered)
.FirstOrDefault();
if (membershipUser != null)
{
// Ensure that the new user name is not already being used
string newUserNameLowered = newUserName.ToLower();
if (!context.aspnet_Users.Any(u => u.LoweredUserName == newUserNameLowered))
{
membershipUser.UserName = newUserName;
membershipUser.LoweredUserName = newUserNameLowered;
context.SaveChanges();
}
}
}
}
Note: I did not account for application ID's in my code. I typically only ever have one application using the ASP.NET membership database, so if you have multiple apps, you'll need to account for that.

Related

Login authentication to asp.net and postgresql

I have tried to implement login page in ASP.NET Core MVC and using postgresql as database.
It should check whether user exits in the database table of postgresql and verify, so what is the query to search for user in database and made them sign in?
I have written my code like this:
public IActionResult Login(string seller_email, string seller_password)
{
using var connection = new NpgsqlConnection(connString);
connection.Open();
string main_query = String.Format(#"select exists(select 1 from public.""sellers"" where ""seller_email""='{0}')", seller_email);
using var command_main = new NpgsqlCommand(main_query, connection);
int result_main = command_main.ExecuteNonQuery();
if (result_main < 0)
{
return View(nameof(Create));
}
else
{
return View(nameof(Sign));
}
}
There is a seller table in the database, so just have to check seller exists or not - if exists the have to create a view for it
You are doing a select query, so you must use a command.ExecuteReader.
The ExecuteNonQuery is to be used with statements that update/insert/delete records.
BUT, most importantly, don't concatenate user submitted values into the query string, as it opens the door to SQL injections. Instead, used a parameter.
See the getting started doc for a simple example.

Error with creating record in EF 6 - "Cannot insert explicit value for identity column in table "Photos" when IDENTITY_INSERT is set to OFF"

I recently upgraded my application from ASP.NET MVC 3 and EF 4 to ASP.NET MVC 5 and EF 6. I have several repository functions that I'm using for CRUD functionality.
I haven't changed anything, but I'm suddenly receiving this error if I try to add a record to my entities:
Cannot insert explicit value for identity column in table "Photos" when IDENTITY_INSERT is set to OFF
Here's an example of one of these methods
public void SavePhoto(Photo photo)
{
if (photo.PhotoID == 0) // new photo
_entities.Photos.Add(photo);
else // edit photo
{
_entities.Photos.Attach(photo);
_entities.Entry(photo).State = EntityState.Modified;
}
_entities.SaveChanges();
}
The PhotoID column in my database for this table is set to be the Identity. When this worked before, it would just increment the PhotoID column value based on the last entry (as expected).
Is there a better way to do this now with EF 6?
Is your PhotoId column is "int" type and annotated with "DateGenerated identity"? If so, the following code will error. Because EF might thinking you are inserting 0 into identity column.
if (photo.PhotoID == 0) // new photo
_entities.Photos.Add(photo);
Use id == 0 to check whether it is a new photo or not is not a good practice, actually it is a "bug", because say you have 3 records in the system(which default could mean your photoid is not greater than 4), And somehow you PhotoID was manipulated as 100 in the backend, now when your code run, your code will set its state as Modified. And EF might throw error for you, or EF might try to insert it for you instead of editing.
So I would suggest to use follow code
var photo = _entities.Photos.Find(photo.PhotoId)
if (photo == null) {
//your code to add photo
}
else
{
//your code to set the the modal state to modified.
}

Asp.net Identity 2.0 update user

Having a problem with saving user changes to the database, like changing the person's name. I'm using the IdentityModel that is automatically created in a new VS2013 web project using individual authentication. Sadly, the template doesn't allow you to change any user information, other than changing roles. I'm looking around via google, I haven't found much. Anyone implement updating using the base identity code?
This is the closest thing I found:
Updating user data - Asp.net Identity
I haven't been successful at incorporating default template. I've just started using Identity this week, so it might be my lack of understanding that's the problem.
var updatedUser = new ApplicationUser
{
Id = model.UserId,
UserName = model.UserName,
CustomerId = model.CustomerId,
Email = model.EmailAddress,
FirstName = model.FirstName,
LastName = model.LastName,
PhoneNumber = model.PhoneNumber,
};
...
var result = await UserManager.UpdateAsync(updatedUser);
My UserManager is created like this:
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
I get the following error in the browser:
Attaching an entity of type 'ApplicationUser' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate
Thanks
The problem I had was I creating an ApplicationUser and saved the object to the database. Since Identity uses Entity Framework under the covers, the entity state of the "updatedUser" object is Added. So Entity Framework tried to INSERT in to the Identity database, causing the conflict. So, you have to get the user and update the returned user object for Entity Framework to know that the entity state is Modified. Here's the working code:
var user = await UserManager.FindByIdAsync(model.UserId);
user.Email = model.EmailAddress;
user.CustomerId = model.CustomerId;
user.FirstName = model.FirstName;
user.PhoneNumber = model.PhoneNumber;
user.LastName = model.LastName;
var result = await UserManager.UpdateAsync(user);
You can also use the AuthContext and update the state to EntityState.Modified. Below is an example. This will allow you to only make one call to the DB instead of two.
AuthContext authContext = new AuthContext();
authContext.Entry(updatedUser).State = EntityState.Modified;

ASP Membership / Role Provider -> how to report the number of users currently logged in?

I'm using the ASP.NET Membership and Role provider. My question is about if there is a built in way to report the number of users who are currently logged in. The question is not get the information about the user who is logged in but from a high level view of everyone who is logged in.
I would like to create a user management dashboard and this metric would be great. also showing the usernames of users who are currently logged in would be useful.
thank you for any help you can provide.
Yes there's a built-in way, see Membership.GetNumberOfUsersOnline(). You can change the "window" for what's considered online, see Membership.UserIsOnlineTimeWindow. (you set the threshold in web.config)
UPDATE:
In response to your comment about getting a list of online usernames...
The Membership API is lacking what you want, so you have to roll your own. You can use the following as starter code, it's similar to what I've done in the past:
public static List<string> GetUsersOnline() {
List<string> l = new List<string>();
string CS = WebConfigurationManager
.ConnectionStrings[YOUR_WEB_CONFIG_KEY]
.ConnectionString
;
string sql = #"
SELECT UserName,LastActivityDate
FROM aspnet_Users
WHERE LastActivityDate > #window
ORDER BY LastActivityDate DESC"
;
using (SqlConnection c = new SqlConnection(CS) ) {
using (SqlCommand cmd = new SqlCommand(sql, c) ) {
DateTime window = DateTime.UtcNow.AddMinutes(
-Membership.UserIsOnlineTimeWindow
);
cmd.Parameters.AddWithValue("#window", window);
c.Open();
using (SqlDataReader r = cmd.ExecuteReader() ) {
while ( r.Read() ) {
l.Add(r.GetString(0));
}
}
}
}
return l;
}
A couple of notes:
Replace YOUR_WEB_CONFIG_KEY above with the key in your web.config <connectionStrings> section.
The LastActivityDate field in the aspnet_Users table (aspnetdb database) is stored as a GMT/UTC Datetime value, so that's why DateTime.UtcNow is used to calculate the window.
Not sure how your Membership database permissions are setup, but you may need to make permission changes, since above code is directly querying the database.

Microsoft dynamics CRM 2011: how to generate lead from external contact form

i developed CMS to one of my customers and he wants that when a user fill in the contact form, it will automatically generate lead in his CRM.
what is the easiest way to do that?
by the way, the contact form is ajax and the data is transfered to asmx, so it will be easy to call to CRM webservice or something like that, because i'm already in the server side.
can someone point me to tutorial or some code example?
thanks!
Your best start will be with the SDK available here, which contains example code and the sdk dlls etc...
Here is a page with a quick reference to all the web service endpoints available in the different flavors of CRM 2011.
From the SDK samplepcode\cs\quickstart creating account, but very similar for lead:
// Connect to the Organization service.
// The using statement assures that the service proxy will be properly disposed.
using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,
serverConfig.HomeRealmUri,
serverConfig.Credentials,
serverConfig.DeviceCredentials))
{
// This statement is required to enable early-bound type support.
_serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
// Instaniate an account object.
// See the Entity Metadata topic in the SDK documentation to determine
// which attributes must be set for each entity.
Account account = new Account { Name = "Fourth Coffee" };
// Create an account record named Fourth Coffee.
_accountId = _serviceProxy.Create(account);
Console.Write("{0} {1} created, ", account.LogicalName, account.Name);
// Retrieve the account containing several of its attributes.
ColumnSet cols = new ColumnSet(
new String[] { "name", "address1_postalcode", "lastusedincampaign" });
Account retrievedAccount = (Account)_serviceProxy.Retrieve("account", _accountId, cols);
Console.Write("retrieved, ");
// Update the postal code attribute.
retrievedAccount.Address1_PostalCode = "98052";
// The address 2 postal code was set accidentally, so set it to null.
retrievedAccount.Address2_PostalCode = null;
// Shows use of a Money value.
retrievedAccount.Revenue = new Money(5000000);
// Shows use of a boolean value.
retrievedAccount.CreditOnHold = false;
// Update the account record.
_serviceProxy.Update(retrievedAccount);
Console.WriteLine("and updated.");

Resources