The situation:
You need to access user profile properties in a custom DNN module for display or perhaps pre-filling a form.
Here’s how I handled it recently:
I created a method to retrieve the profile property of interest. I could have accessed the property directly, but I wanted to customize what came back and to guard against asking for a property that didn’t exist.
private string GetValidProfileProperty(string propertyName, out bool isValid)
{
if (CommonBase.HasValue(uProfile.GetPropertyValue(propertyName)))
{
isValid = true;
return uProfile.GetPropertyValue(propertyName);
}
else
{
isValid = false;
return "";
}
}
(You will note the use of CommonBase.HasValue() in there. This is a method I have in my common function library to test if a value exists and guards against NullReferenceException. You can find it here.)
So in my module’s view control code-behind, I have this code:
using DotNetNuke.Entities.Users;
public partial class EditProfile : PortalModuleChild, IActionable
{
UserInfo user;
UserProfile uProfile;
protected void Page_Init(object sender, EventArgs e)
{
user = UserController.GetCurrentUserInfo();
uProfile = user.Profile;
}
protected void Page_Load(object sender, EventArgs e)
{
bool IsValid = true;
string pval = GetValidProfileProperty("Company", out IsValid));
if (!IsValid)
{
// Do something here if there is no valid data for this property
}
else
{
// Do something here with the property value, such as fill a textbox
tbCompanyName.Text = pval;
}
}
}
But what if you need to save/update a profile property? Add some code like this to your submit button’s OnClick event:
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
uProfile.SetProfileProperty("Company", tbCompanyName.Text);
user.Profile = uProfile;
UserController.UpdateUser(user.PortalID, user);
}
catch (Exception)
{
// Add exception handling code here
}
}