Wednesday, February 1, 2012

Set WebPart Icon in Site Definition.

It’s a very common scenario to create a site definition with pages, features, lists, web parts…etc

Capture

I have tried to change the web part icon as per the information in MSDN page, by using the “ImageUrl” property, but this didn’t work.

<View List="$Resources:core,lists_Folder;/Discussions" ImageUrl=”/_layouts/????????.png”  BaseViewID="0" WebPartZoneID="Left" Name="$Resources:Strings,List_Instance_Title_Discussions_Forum;" WebPartOrder="1" ShowHeaderUI="True"/>

So I decided to catch the webpart and set the ImageUrl programmatically. So the only way to do this is to implement this in the FeatureActivated event in the FeatureReceiver class.

   1: public override void FeatureActivated(SPFeatureReceiverProperties properties)
   2: {
   3:     base.FeatureActivated(properties);
   4:     SetWebPartIcon(properties)
   5: }
   6:  
   7: private static void SetWebPartIcon(SPFeatureReceiverProperties properties)
   8: {
   9:     try
  10:     {
  11:         SPSecurity.RunWithElevatedPrivileges(() =>
  12:         {
  13:             SPWeb site = properties.Feature.Parent as SPWeb;
  14:             SPLimitedWebPartManager webPartManager = 
  15:                 site.GetLimitedWebPartManager(site.ServerRelativeUrl + "/default.aspx", PersonalizationScope.Shared);
  16:             SPLimitedWebPartCollection webParts = webPartManager.WebParts;
  17:             if (webParts != null && webParts.Count > 0)
  18:             {
  19:                 foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in webParts)
  20:                 {
  21:                     if (string.Compare(webPart.Title, "Web Part Name", false) == 0)
  22:                     {
  23:                         // Set the Image URL
  24:                         webPart.TitleIconImageUrl = "*****";
  25:                         webPartManager.SaveChanges(webPart);
  26:                     }
  27:                 }
  28:             }
  29:         });
  30:     }
  31:     catch (Exception ex)
  32:     {
  33:         // Catch the Exception
  34:     }
  35: }