Top Banner

of 15

153546270 Dynamic Webpart Creation

Oct 09, 2015

Download

Documents

Safdar Hussain

WebPart Creation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript

omment on this postwith any issues.Dynamically populate the Web Part Gallery using the WebPartAdder in SharePoint 2010Tags:WEB PARTS,SHAREPOINT 2010Jul 28 2011 3:49 AM*----Writing this post has been on my agenda for some time, initially I intended to put it into mySharePoint 2010 Web Parts in Action book,but there was not enough time, you know how it is! This is an excellent new feature toSharePoint 2010which allows you to dynamically populate the Web Part Gallery with Categories and Web Parts. So here we go.Introduction to the Web Part Adder and the Web Part GalleryThink of theList and Librariescategory in the Web Part Gallery - it is dynamically populated with the lists and libraries available in the current web. This is all done using theWebPartAdderclass which loads all the Web Parts available in the gallery from a number of different sources, see figure below. These source include the List and Libraries category, the local Web Part catalog, files in the wpcatalog, closed and uploaded Web Parts etc.

The really cool thing with this is that you can actually create custom Gallery Sources! This is a new feature of SharePoint 2010 and is really simple to do. I'll show you how!Create a custom Web Part Gallery SourceI've not yet seen any guide on how to create a custom Web Part Gallery Source, even though the classes and methods in MSDN are documented (the MSFT minimalistic way). To get this all working you need to use a new Feature element available in the Element manifest calledWebPartAdderExtension. This element isreferenced only once in MSDN, where it only says that the element is not documented!In this walkthrough I will use a very simple custom gallery source. It will dynamically populate the gallery withProduct Web Partsthat displays information about products. The product information is stored within a SharePoint list, in the local site, called Products.

From this list we'll create a new category in the gallery that lists all products, and when a product is added to the page it should add a new Web Part displaying that particular product information.Create a new SharePoint projectStart by creating a newEmpty SharePoint project. Make it a farm solution. Then add a newWeb Part SPI- this will also add a Site Collection scoped feature to your project. In the Web Part SPI remove the .webpart file. We do not want to add this Web Part to the gallery - we only need the Web Part class. You can of course make the Web Part without an SPI if you want to.Next step is to build the Web Part user interface - and here you can get fancy if you like. If you feel for a copy and paste excursion you can copy and paste the code below.public class ProductWebPart : WebPart { public ProductWebPart() { } public ProductWebPart(SPListItem item) { ProductId = item.ID; } protected override void CreateChildControls() { SPList productList = SPContext.Current.Web.Lists.TryGetList("Products"); if (productList != null) { try { SPListItem item = productList.GetItemById(ProductId); this.Title = "Product information:" + item.Title; this.Controls.Add(new LiteralControl( String.Format("Product: {0} costs ${1}", item.Title, item["Price"]))); } catch (ArgumentException) { this.Title = "Unknown product"; this.Controls.Add(new LiteralControl("Product not found")); } } }

[Personalizable(PersonalizationScope.Shared)] [WebBrowsable] public int ProductId { get; set; }}As you can see it's a simple Web Part with one propertyProductIdthat contains the id of the product to be listed. A specific constructor has been added which takes an SPListItem as argument - this one is used later by the custom source to instantiate the Web Part.The CreateChildControls is very simple and just writes the name of the product and its price, if the product is found - otherwise it shows an error.Create the Custom Web Part Gallery SourceNext is to create the Custom Web Part Gallery Source. First add a newEmpty Element SPIto your project - the SPI will automatically be associated with the feature that was created by the Web Part SPI (unless you installed Waldeks fancy Visual Studio extensions :-).In that SPI add two new classes;ProductsWebPartGallerySourceandProductsWebPartGalleryItem. The first one is the actual custom source and the second class represents the items in that source.The ProdcutsWebPartGallerySource is responsible for discovering and iterating the items for custom gallery extension. This class must derive from theWebPartGallerySourceand implement one constructor as well as one method as follows:[Guid("01db1e81-5853-448e-b8c7-4b6564994ae3")]public class ProductsWebPartGallerySource : WebPartGallerySourceBase { public ProductsWebPartGallerySource(Page page) : base(page) { }

protected override WebPartGalleryItemBase[] GetItemsCore() { List items = new List(); SPList list = SPContext.Current.Web.Lists["Products"]; foreach (SPListItem item in list.Items) { items.Add( new ProductsWebPartGalleryItem(this, base.Page, item)); } return items.ToArray(); } }The required constructor required only passes on to its base class. The overriddenGetItemsCore()method is the method that is responsible for returning all Web Parts discovered by this source. So in this case the method simply iterates over all available items in the Products list and creates aProductsWebPartGalleryItemobject. Also notice that I added the Guid attribute to the class - we'll need that later.Now it's time to implement the gallery items. This is done in the second class file you created. The ProductsWebPartGalleryItem should be derived from the abstract classWebPartGalleryItemBase. It is implemented as follows:public class ProductsWebPartGalleryItem : WebPartGalleryItemBase {

private readonly string title; private readonly SPListItem item;

public ProductsWebPartGalleryItem(WebPartGallerySource source, Page page, SPListItem item) : base(source, page) { this.item = item; this.title = item.Title; }

public override System.Web.UI.WebControls.WebParts.WebPart Instantiate() { return new ProductWebPart.ProductWebPart(item); }

public override string Category { get { return "Products"; } }

public override string Description { get { return "Show listing for product: " + title; } }

public override string IconUrl { get { return "/_layouts/Wictor.Adder/product.png"; } }

public override string Id { get { return item.ID.ToString(); } }

public override bool IsRecommended { get { return false; } }

public override string Title { get { return title; } }}This implementation has one constructor, taking the source, the current page and the specific list item as arguments. It stores some values locally in the class and passes the source and page to its base class. Before discussing theInstantiate()method let's take a look at the properties. These are the minimum properties required for the implementation to work, but there are several more that can be used to do some nifty stuff! Such as theClientAddmethod which allows you to specify a JavaScript method to execute when the Web Part is added or theRibbonCommandwhich allows you to execute a specific Ribbon command. What they do is pretty self explanatory! Interesting thing here is that you do not need to have the same category on all Web Parts in the source - you can populate several categories in the gallery, new or existing.TheInstantiate()method is responsible for creating the Web Part with the correct properties and is called by the WebPartAdder and the custom source when a Web Part is added to the page. In this case we create the Web Part using the custom constructor and pass in the list item.So now all the code are done and it should compile fine. There is just one small thing left - the mysteriousWebPartAdderExtensionelement. In your empty element SPI open the elements manifest file and make it look like the following:Elements xmlns="http://schemas.microsoft.com/sharepoint/">

As attribute values I use the Visual Studio replaceable tokens for the assembly full name and for the full name of the custom Web Part Gallery source class - here's the usefulness of the Guid attribute, no need to remember the class name and namespace and it allows for easier refactoring.As a final icing on the cake I also added a sweet little image to be used in the gallery. Your solution should look like this:

Ok, we're done!Test the custom Web Part Gallery Source!Now it is time to take this for a test drive. Deploy your solution, go to a page and edit it. Then click on Insert > Web Part. It should look something like this:

The items in the Product list ends up as Web Parts in the Products category, with the sweet little icon. You can now choose a Web Part and insert into the page and see how it renders the correct information!SummaryYou've now seen how you can extend the Web Part Gallery with custom Web Part Gallery Sources. It is fairly simple and it can be very useful if you want to help the users by creating pre-configured Web Parts. I can see really many good use cases of this. Oh, I forgot - this does not work in the Sandbox.

Web Parts

1. Content EditorWebpart:Thiswebpartwill be used for authoring rich content.This will be available in Media and Content section.

Here is an example, i have added a content editorwebpart, and added some text, images, Links, Files to it, you can see the options available on the top. For example if you want to create a simple html menu on the page, use it.

You can even edit the content in a html editor using the "Format Text" ribbon options.

2. MediaWebpart:Thiswebpartis a best pick to host media elemnts like video or Images.Once you add Mediawebpartto page and enter edit mode ofwebpart, you can see options to add a video or images.

Once you did it, here is the result . . .

3. Page ViewerWebpart:If you have a webpage wither internal/external as a part of the web part page, Page Viewerwebpartis a best pick for it. An example is shown below.

4. SilverlightWebpart: Silverlight means rich and powerful applications. Now you can intigrate it at awebpartlevel using Silverlightwebpart. Once you deployed the silverlight application (.xap) to site, just add thiswebpartto page and specify the silverlight application url in the dialog.

5. Business DataWebparts :I have a external content type and there are few actions defined on it using which i can read, write data on to external system. For example i have created a BSC Entity with details and 2 actions defined on it. Now, we will see a few Business Data web parts and how the dispaly gona vary. You will have the flexibility to modify the display using XSLT as well.

Business Data List:

Business Data Item:

Business Data Actions:

6. ChartWebpart:Even though its part of Business Datawebparts, it has wide range of functionality, so it worth to preset as a seperatewebpart.As the name depicts, thiswebpartis used to display the data in a graphical represntation. Once the web part is selected on towebpartpage, you will be presented with options to select the data source.

Step 1:Add web part.Step 2:Select the data source.

Step 3:Choose the axis elements from data feilds.

Step 4:Modify the other display elemnts and the final disply of LandCost chartwebpartis here.

7. Infopath FormWebpart:This is a brand newwebpartin SP2010. This is a best pick if you want to display Infopath enabled / editable Lists or libraries. You can create all three kinds of infopath documents and can display all "Create", "Edit" and "Display List" forms. What to be displayed, that you have to select from EditWebpartwindows as shown below.I have a infopath editform enabled for list named "Land Cost". For which we created a Infopath formwebpart.

Web part displaying Edit - Infopath form for Land Cost list:

8. Content QueryWebpart:The Content Query Web Part is available for pages on sites in which the publishing infrastructure feature has been activated. Probably the most common use of the Web Part is to roll up information from multiple lists into a single view. You can apply filters and styles to make the content look the way you want. Imagine you have a publishing page that displays a certain article and you want to display a list of related stories next to it on the page. Using the Content Query Web Part, you can search all the lists on the site that use the same keywords as the keywords for the featured article, and display them in a list.For exmaple i created a simple list content type called consumer and a list created based on that content type.

Now go toWebpartpage and add a web part and select "Content Query"webpartfrom content rollup section.Now, click on Open the tool pane link and configure the list on which thewebpartshould operate.

Once you click ok, you will see thewebpartgetting populated with the first column of the list, which may not be the desired result everytime. So, go to Presentation part of content query properties window, and change the "Fields to Display" part of configuration.

There are other parts of the configuration, where you can control the query which can control the results fetched under Filters section and the way to display can be controled using Grouping and Sortin section.

Finally the results will be displayed on the Content Querywebpart.