User Voices
Our blog on SharePoint add-ons and solutions development
« New in FilterZen 2.4: SQL Data Filters | Main | jQuery Color Animations: Adding RGBA alpha channel support »

FilterZen How To: Create and Set Up Web Parts Programmatically

We've quietly launched the newest release of FilterZen yesterday — a fantastic release that finally pushed the tool from being the URL Filter Web Part for SharePoint to being the Filter Web Part for SharePoint. URL filtering is still supported and got even better, but now there's a wealth of other highly useful filter types in there, many new powerful capabilities, and yet it's all still available in just one single Web Part, reducing complexity and clutter in your Web Part catalog.

We received one enquiry about programmatically creating and setting up the Web Part: a use case that was intriguing enough to warrant the following (code-heavy) tutorial.

Initially, the answer seems easy: just only once manually — as you might know, that gives you an XML text file to play with — then programmatically customize to requirements and re-import the XML Web Part configuration many times. However, there are two issues here:

  • First, programmatically operating on a Web Part Zone using the Web Part Manager of a given Web Part Page can actually be somewhat tricky if you haven't done it before.
  • Secondly, the new FilterZen Filter Web Part serializes its Filters in a binary (Base64-encoded) format, so you'll need to reference the roxority_FilterZen.dll assembly to programmatically work with an instance of the roxority_FilterZen.roxority_FilterWebPart class.

Let's get to work. Before playing with the FilterZen Filter Web Part, it might be a good idea to programmatically create, set up and persist some simple out-of-the-box Web Part, say, an .

Web Part Pages consist of Web Part Zones (), managed by a Web Part Manager (). The latter object lets you rearrange Web Parts in zones, add, export, close, minimize or remove them. Recall that right now we want to add an Image Web Part. The following code will do that, assuming you take care of obtaining an reference for your Web Part Page yourself:

using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.WebPartPages;

void AddNewWebPartToPage(SPFile webPartPage) {
ImageWebPart webPart = new ImageWebPart ();
webPart.ImageLink = "/_layouts/images/templogo.gif";
using (SPLimitedWebPartManager webPartManager = webPartPage.GetLimitedWebPartManager (PersonalizationScope.Shared)) {
webPartManager.AddWebPart (webPart, "LeftZone", 0);
webPartManager.CacheInvalidate (webPart, Storage.Shared);
webPartManager.SaveChanges (webPart);

The first two lines in this custom AddNewWebPartToPage method initialize a new ImageWebPart instance. If obtaining an SPFile reference is not for you, use the method instead.

Now to make things more interesting, let's go about setting up a FilterZen Filter Web Part. Add a reference to the roxority_FilterZen assembly — it should be in the GAC if the FilterZen solution package is deployed to your server farm. The following code sample initializes a new Filter Web Part that contains one enabled Page Request Filter (at this point, some basic familiarity with the FilterZen Filter Web Part and its Page Request filter type is assumed) with a request mode of "URL path fragment" and any "programmatically desired" filter name / parameter name combination:

using roxority_FilterZen;

WebPart InitializeFilterWebPart (string columnOrFilterName, string paramName) {
roxority_FilterWebPart webPart = new roxority_FilterWebPart ();
FilterBase pageRequestFilter = FilterBase.Create ("roxority_FilterZen.FilterBase+RequestParameter");
List<FilterBase> filters = webPart.GetFilters();
filters.Add (pageRequestFilter);
pageRequestFilter.Name = columnOrFilterName;
pageRequestFilter.Enabled = true;
pageRequestFilter.Set ("ParameterName", paramName);
pageRequestFilter.Set ("RequestMode", 3);
webPart.SerializedFilters = FilterBase.Serialize (filters);
return webPart;

That should work — give it a whirl! Some important notes on the above code:

  • The above code will not work outside the SharePoint context without some additional work: whenever your code is not running inside the SharePoint context, i.e. called from a Page/Control/Web Part/Event Receiver (that is: when is null), then you need to set the public static roxority_FilterWebPart.OffSite property to a non-null SPSite object at least once before first referencing or initializing any objects from the roxority_FilterZen assembly. Whenever your code "switches" to another site collection, you're advised to update the static roxority_FilterWebPart.OffSite property to the SPSite object that's semantically "current" from your code point of view.
  • The above code creates and initializes your Filter Web Part "in a vacuum". Unless combined with the previous sample code to add a Web Part to a Web Part Page and save all those changes to the content database, your Web Part will get lost once your code is done or the server is reset.
  • You will notice some filter properties are set calling a Set method. The names that can be used for this method are basically semi-documented here. If you use these property names in this way (they were originally intended just for URL overriding of Web Part and filter settings), then the following guidelines always apply:
    • Remove the filter_ prefix from the property names.
    • Be sure not to attempt to Set a Web Part setting (those in the second paragraph in the documentation page) on a filter: only filter settings (those from the third paragraph onwards) will work.
    • Pass a Boolean value for those properties expecting either '1' or '0' per the above documentation, pass an Int32 value for those properties expecting enumerated numeric values (except for the Date filter AbsoluteDefaultValue property pass an Int64), pass a String.
  • The above code used the type name of the Page Request filter type with the FilterBase.Create method. The other filter types have the following names to be used when calling the Create method:
    • roxority_FilterZen.FilterBase+Choice
    • roxority_FilterZen.FilterBase+Date
    • roxority_FilterZen.FilterBase+Lookup
    • roxority_FilterZen.FilterBase+PageField
    • roxority_FilterZen.FilterBase+Text
    • roxority_FilterZen.FilterBase+User
    • roxority_FilterZen.FilterBase+SqlData

If you have questions about working with FilterZen programmatically or have issues with getting your code to work, let us know in the FilterZen Feedback Forum! We look forward to working with you on building smart new filtering solutions.

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>