ASP.NET Membership Provider - Remove Unwanted Profile Properties


/ Published in: C#
Save to your folder(s)

I removed several properties from my custom Profile class, and wanted to clean out the data from the aspnet\_Profile table. This code will remove all unwanted data from the PropertyNames and PropertyValuesString columns of aspnet\_Profile. Note this assumes PropertyValuesBinary is not used, though it wouldn't be hard to support that too.


Copy this code and paste it in your HTML
  1. protected void fixProfile(aspnet_Profile p)
  2. {
  3. string[] okfields = { "names", "of", "profile", "properties",
  4. "you", "want", "to", "keep"};
  5.  
  6. // search for: fieldname:S:startpos:length
  7. string regex = @"([a-zA-Z0-9]+):S:([0-9]+):([0-9]+):";
  8.  
  9. string newNames = string.Empty;
  10. string newValues = string.Empty;
  11.  
  12. int pos = 0;
  13. System.Text.RegularExpressions.Regex rgx
  14. = new System.Text.RegularExpressions.Regex(regex);
  15. System.Text.RegularExpressions.Match match
  16. = rgx.Match(p.PropertyNames, pos);
  17.  
  18. while ( match != null && match.Success ) {
  19. string propertyName = match.Groups[1].Value;
  20. if (okfields.Contains(propertyName))
  21. {
  22. // We want to keep this profile property. Extract the
  23. // value and then append to newNames/newValues
  24. int startPos = Convert.ToInt32(match.Groups[2].Value);
  25. int len = Convert.ToInt32(match.Groups[3].Value);
  26. string value = p.PropertyValuesString.Substring(startPos, len);
  27. newNames += string.Format(
  28. "{0}:S:{1}:{2}:",
  29. propertyName,
  30. newValues.Length,
  31. len);
  32. newValues += value;
  33. }
  34. pos = match.Index + match.Length;
  35. match = rgx.Match(p.PropertyNames, pos);
  36. }
  37.  
  38. p.PropertyNames = newNames;
  39. p.PropertyValuesString = newValues;
  40.  
  41. }
  42.  
  43. protected void cleanMyData()
  44. {
  45. // db is your DataContext
  46. foreach (var user in db.aspnet_Users)
  47. {
  48. aspnet_Profile p = user.aspnet_Profile;
  49. if (p == null) continue;
  50.  
  51. fixProfile(p);
  52. db.SubmitChanges();
  53. }
  54. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.