SharePoint: Custom provider web part

Got a requirement to read a querystring and pass it to some of the web parts on a page. I thought that this would be easy since I can use the OOTB query string url filter web part to read and then pass the value after setting up the connection.

However, apparently some of the consumer web parts need the value to be in different format. My first thought was to append another querystring with the same value (just different format) but that would not be very nice (especially when the url length is restricted). This is where ITransformableFilterValues comes in handy. The interface is used for web part to web part connections.

Below are an example on how this interface can be implemented.


public class CustomQueryStringFilterWebPart : System.Web.UI.WebControls.WebParts.WebPart, ITransformableFilterValues
    {        
        string _queryStringKey = "category";
		string _filterValue = "";
		
        [WebPartStorage(Storage.Shared)]
        [WebBrowsable(true)]
        [WebDisplayName("Query String Key")]
        [Personalizable(PersonalizationScope.Shared)]
        [Category("Settings")]
        public string QueryStringKey
        {
            get { return _queryStringKey; }
            set { _queryStringKey = value; }
        }      

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            _filterValue = HttpContext.Current.Request.QueryString[_queryStringKey];
        }

        public bool AllowAllValue
        {
            get { return true; }
        }

        public bool AllowEmptyValue
        {
            get { return false; }
        }

        public bool AllowMultipleValues
        {
            get { return false; }
        }

        public string ParameterName
        {
            get { return "Query String Filter"; }
        }

        public System.Collections.ObjectModel.ReadOnlyCollection<string> ParameterValues
        {
            get
            {
                string value = string.Format("[{0}]", _filterValue.ToUpper());
                string[] values = new string[] { value };
                return new ReadOnlyCollection<string>(values);
            }
        }

        [ConnectionProvider("Query String Filter", "ITransformableFilterValues", AllowsMultipleConnections = true)]
        public ITransformableFilterValues SetConnectionInterface()
        {
            return this;
        }        
    }

The code above is a custom web part that implements ITransformableFilterValues. It gets the querystring value and convert it to uppercase.

Add the above web part to a page and to pass the transformed value, connections to the consumer web parts need to be created. Once the connection is setup, everything should just work 🙂

Advertisements

Using SharePoint PeopleEditor user control

I had the chance to play with PeopleEditor user control on my previous project and just thought would be good to put another blog about it out there, so here you go:

Started with creating a visual web part and the next step is adding the control to the ascx page

<SharePoint:PeopleEditor ID="peUser" ValidatorEnabled="true" runat="server"
                        SelectionSet="User" Width="350px" IsValid="true" AllowTypeIn="true"
                        MultiSelect="true"></SharePoint:PeopleEditor>
<SharePoint:InputFormRequiredFieldValidator ID="rfvUser" 
                        SetFocusOnError="true" runat="server" ControlToValidate="peUser" BreakBefore="true"
                        ErrorMessage="Required field." EnableClientScript="false"
                        Display="Dynamic"></SharePoint:InputFormRequiredFieldValidator>

To get the selected users we can iterate through its resovedEntities property

for (index = 0; index <= peControl.ResolvedEntities.Count - 1; ++index)
{
    PickerEntity entity = (PickerEntity)peopleEdControl.ResolvedEntities[index];
    SelectedUser selectedUser = new SelectedUser(){ Id = Convert.ToInt32(entity.EntityData["SPUserID"])
                                                    , Name = entity.DisplayText
                                                    , LoginName = entity.Key };
    selectedUserList.Add(selectedUser);
}

To assign a value to PeopleEditor user control (in my case I use a string of login name separated by a semicolon)

string[] delimiter = { ";" };
string[] loginNames = loginNameString.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);

foreach(string loginName in loginNames)
{
     PickerEntity pe = new PickerEntity();
     pe.Key = loginName;

     pe = peUser.ValidateEntity(pe);
     ArrayList entityList = new ArrayList() { pe };

     peUser.UpdateEntities(entityList);
}

Hope that helps 🙂

Create a new Wiki Page

The code below adds a new wiki page and then inserts a web part into the new page’s rich text editor

SPList pagesList = web.Lists["Pages"];

SPFolder rootFolder = pagesList.RootFolder;

SPFileCollection fileCollection = rootFolder.Files;

string pageUrl = rootFolder.ServerRelativeUrl + "/MyNewPage.aspx";

//Create the page
SPFile newFile = fileCollection.Add(pageUrl, SPTemplateFileType.WikiPage);

//Checkout and add custom web part to the newly created page
newFile.CheckOut();

//Use a new Guid as the web part id
Guid storageKey = Guid.NewGuid();

string wpId = String.Format("g_{0}", storageKey.ToString().Replace('-', '_'));

//Get web part manager
using (SPLimitedWebPartManager manager = newFile.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))

{

//Initialize the web part and insert it into 'wpz' web part zone.
//Web part zone is hidden in Rich text editor and its name is fixed ('wpz')

MyWebPart webPart = new MyWebPart();

webPart.ID = wpId;

webPart.Title = "My New Page";

manager.AddWebPart(webPart, "wpz", 0);

string content = String.Format(CultureInfo.InvariantCulture
, "<div class=\"ms-rtestate-read ms-rte-wpbox\" contentEditable=\"false\"><div class=\"ms-rtestate-read {0}\" id=\"div_{0}\"></div><div style='display:none' id=\"vid_{0}\"></div></div>"

, new object[] { storageKey.ToString("D") });

SPListItem item = newFile.Item;

item["WikiField"] = content;

item.Update();

}
newFile.CheckIn(string.Empty);

Hope that helps 🙂

A quick and easy way to read RSS in SharePoint Foundation 2010

Thanks to George Tsiokos for his Data view web part http://sharepointrss.com/, we just have to submit the form on the site. This will produce a .DWP file. Save the .DWP file to your local drive and the next step is to upload this .DWP file to a web part page in SharePoint and you can view the RSS feed. No installation required 🙂

Add Content Editor Web Part into Site Template

In Onet.xml, find the module(s) that need to have a content editor web part and add the following:


<AllUsersWebPart WebPartZoneID="Left" WebPartOrder="1">
          <![CDATA[
          <WebPart xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.microsoft.com/WebPart/v2">
            <Title>My Web part</Title>
            <FrameType>None</FrameType>
            <Description>Say Hello Web Part</Description>
            <FrameState>Normal</FrameState>
            <Assembly>Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>
            <TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>
            <ContentLink xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor" />
            <Content xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor">
                &lt;script&gt; 

                function SayHello() 
                { 
			alert('Hello');
                  	
                      //all done 
                      return; 
                    } 
                  } 
                }


                _spBodyOnLoadFunctionNames.push(&quot;SayHello&quot;) 

                &lt;/script&gt;
            </Content>
            <PartStorage xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor" />
          </WebPart>
          ]]>

        </AllUsersWebPart>

Note some characters need to be encoded.

In case a web part is broken, use contents=1 query string, for example: http://myurladdress/default.aspx?contents=1. This will show a list of all the web parts on the page.

Cheers 🙂