Second Life of a Hungarian SharePoint Geek

October 17, 2010

Getting the type of the web part from a BinarySerializedWebPart

As I promised earlier, in this post I will show you a simple way to determine the type of the web part that is encoded in a BinarySerializedWebPart. The code in this post is only an extension to the code example in my former post.

The WebPart node of the BinarySerializedWebPart XML contains an attribute called WPTypeId that has a GUID value.

The internal WebPartTypeInfo class (Microsoft.SharePoint.WebPartPages namespace, Microsoft.SharePoint assembly) contains a static method, TryGetWellKnownTypeId, that provides the Type of the well known (built-in) web parts as an out parameter based on this GUID value.

The code below shows how to access this information using Reflection:

  1. XmlAttribute attribute = webPartNode.Attributes["WPTypeId"];
  2. if (attribute != null)
  3. {
  4.     Type webPartTypeInfoType = assembly.GetType("Microsoft.SharePoint.WebPartPages.WebPartTypeInfo");
  6.     Guid wpTypeId = new Guid(attribute.Value);
  8.     //internal static bool TryGetWellKnownTypeId(Guid webPartTypeId, out Type type);
  9.     MethodInfo mi_TryGetWellKnownTypeId = webPartTypeInfoType.GetMethod("TryGetWellKnownTypeId", BindingFlags.NonPublic | BindingFlags.Static);
  11.     Type webPartType = null;
  13.     object[] parameters = new object[2] { wpTypeId, webPartType };
  15.     if ((bool)mi_TryGetWellKnownTypeId.Invoke(null, parameters))
  16.     {
  17.         webPartType = (Type)parameters[1];
  18.         Console.WriteLine("Web part type is: {0}", webPartType);
  19.     }
  20. }

You can use the result as the type parameter when calling the constructor of the BinaryWebPartDeserializer.


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at

%d bloggers like this: