A cool way to use Properties in a SharePoint Web Part

Properties are nothing new in OOP, but something that I stumbled upon not too long ago was a cool thing that you could do with properties. My work was SharePoint web part related, but I imagine that it would work with any customized object that can be called in your page.

I needed a way to reuse a webpart that was accessing a single User Profile field so that I could display any field I wished, as many as I wanted just by simply dropping a new custom web part on my page in SPD and simply adding a name/value pair to the HTML.

The idea here is to build your web part with a property:

public string CustomProperty
{
  get { return _CustomProperty; }
  set { _CustomProperty= value; }
}


Nothing crazy here but later in the code we check the CustomProperty property for a value and if it's valid, we go and grab the field from the User Profile database and then display it in the web part:

<WpNs0:ProfilePropertyPart runat="server" CustomProperty="FirstName" .../>

So the trick to making this work is to make sure you use the correct nomenclature for the value you pass into the CustomProperty property.

The value you need is found on View Profile page (found here - Central Admin/Shared Services/User Profiles and Properties/View Profile Properties).

Find the field in the "Property Name" column, click it and chose "Edit" and in the Property Settings block, you should see a "Name" field and a "Display Name" field. You want to use the "NAME" field. SharePoint uses this as it's logical name and it is the value you need to pass into the CustomProperty property of the web part declaration!

In this case with the "First Name" field, the SharePoint logical field is actually "FieldName" with no spaces. Some fields use the same value for 'Name' and 'Display Name', others are close like the 'First Name' but slightly different. and others still can have prefixes that don't make sense, ie. if you create a custom field, the value that SharePoint gave me for the 'Name' of the field was "SPS-Skills", which is what I passed in to the CutsomProperty property.

Of course you'll need admin rights on the server to get to that page.

I will go more into accessing values from the User Profile database in a future posting, but I thought this was a really cool thing you could do for an easy way to customize a web part so that you could reuse it and get different output simply by changing the value of a property in your html in designer.

Comments

Popular posts from this blog

Get users of AD group for use in SharePoint webpart.

SharePoint 2010: Adding List Attachments as Links in a DataView Webpart

A simple method for finding Active Directory user information using C# with LDAP