Display Template and Current Item Index

A little while ago we had request where we were spouse to build a content lift up that displays the latest news pages. Very common and nothing new. The solution should be done with SharePoint OOTB features (be Office 365 compatible), so I decided to use a search and search web parts like I have done a multiple times before. What customer wanted was something like in this wireframe.

(Again here’s the link to source code used in this example: GitHub Mikko Koskinen)

The news post should be listed from newest to oldest. The most recent one should have a title, some text and image when others should show only title and short text from the news body. Because I wanted to keep things light from performance point of view I wanted to accomplish this with one web part only. You could do this with two separated web part for sure.

But if we think of the concept of search web part and display templates we know that we have two elements in template; a control display templates and item display templates. This concept is explained nice in Paul Matthews display template series where the following image can be found. If the concept of display templates and using them is new to you please read Matthews posts first.

searchTempaltesControltem

Same item template is used to every single item that is returned to us from the index. If so how can we style the first item element differently than others?

After going through basically every single value from ctx.CurrentItem I finally found the answers. The detail I need is not in CurrentItme but in context it self. There is a value for current item id found and we can use that to solve our small problem.

Only thing we need to do is to check what is the idx value of the current item in display template and change the styling based on that.


var shortText = String.format('<div class="ms-noWrap newsBody" title="{0}" id="{1}" >{2}...</div>',
				$htmlEncode(line2.defaultValueRenderer(line2)), line2Id, line2.toString().substring(0,100));


var index = ctx.CurrentItemIdx;

if (index == 0){
_#-->
	<div class="mainNews" id="_#= containerId =#_" data-displaytemplate="_#= $htmlEncode(dataDisplayTemplateTitle) =#_">
			<div class="newsImage" id="_#= pictureContainerId =#_">
				<!--#_
				if(!linkURL.isEmpty)
				{
				_#-->
				<a href="_#= linkURL =#_" title="_#= $htmlEncode(line1.defaultValueRenderer(line1)) =#_" id="_#= pictureLinkId =#_">
				<!--#_
				}
				_#-->
					_#= pictureMarkup =#_
				<!--#_
				if(!linkURL.isEmpty)
				{
				_#-->
				</a>
				<!--#_
				}
				_#-->
			</div>
			<div class="newsTitle" id="_#= dataContainerId =#_">
				<!--#_
				if(!linkURL.isEmpty)
				{
				_#-->
					<a href="_#= linkURL =#_" title="_#= $htmlEncode(line1.defaultValueRenderer(line1)) =#_" id="_#= line1LinkId =#_">
				<!--#_
				}
				_#-->
					<h2 class="ms-noWrap" id="_#= line1Id =#_"> _#= line1 =#_</h2>
				<!--#_
				if(!linkURL.isEmpty)
				{
				_#-->
					</a>
				<!--#_
				}
				_#-->
			
				<div class="newsBody" title="_#= $htmlEncode(line2.defaultValueRenderer(line2)) =#_" id="_#= line2Id =#_" > _#= line2 =#_</div>
			</div>
		</div>
<!--#_	
}
else{
_#-->
	<div id="_#= containerId =#_" data-displaytemplate="_#= $htmlEncode(dataDisplayTemplateTitle) =#_">
			<div class="newsTitle" id="_#= dataContainerId =#_">
				<!--#_
				if(!linkURL.isEmpty)
				{
				_#-->
					<a href="_#= linkURL =#_" title="_#= $htmlEncode(line1.defaultValueRenderer(line1)) =#_" id="_#= line1LinkId =#_">
				<!--#_
				}
				_#-->
					<h2 class="ms-noWrap" id="_#= line1Id =#_"> _#= line1 =#_</h2>
				<!--#_
				if(!linkURL.isEmpty)
				{
				_#-->
					</a>
				<!--#_
				}
				_#-->
			
				_#= shortText =#_
			</div>
		</div>
<!--#_	
}
_#-->

After this we can have nice one web part solution with OOTB tools to our problem. You can find the full source from my GitHub (link at the beginning the post).

SharePoint 2013 and Search-Driven Content

For the last year I have done a lot of concept and architecture design together with development in cases where SharePoint is used as organization internal communication, news, announcement and general information channel. Basically I mean traditional Intranet with news pages, announcements lists, blogs, HR content sites, department sites etc. For this reason I have spent my time looking the new SharePoint 2013 Preview (SP2013 on this point of view. There is so much to look into and learn that you better start from something you are familiar with. I have tried to find out what there is new for my customers that are using SharePoint with Publishing Portal features inside their company. So few upcoming posts, including this one, will include my thoughts and findings on this point of view.

Here is how the Publishing Portal looks in right after creation

Search-Driven Content web parts

First big thing that you should notice are new web parts related to search. They are called Search-Driven Content web parts. When showing something like announcements in page on SharePoint 2010 (SP2010) you basically had four options 1. List View web part 2. Content Query web part 3. Search Result web part 4. Custom web part. In all of these there are pros and cons and you can still use them.

But SP2013 introduced a whole set of new search-driven web part. It seems that Microsoft really wants us to use search index when fetching and publishing content on the site. And I don’t claim them from doing so. Search index is very efficient and safe way to do it.

Content query web part is create but there is a possibility that your site is slowing down if you get content from a large site. That is why search is a create option. Only problem in SP2010 is that Search Result web part isn’t very useful way to do things and you are able to use List View web part only on that site where the list is located (without some SharePoint Designer hacks). So I have to say that in quite many occasion we went to road of making custom web part for some needed components on the site. Now I think that we can change this thinking at least in quite many occasion.

Available web parts

  1. Content Search – Web Part will allow you to show items that are results of a search query you specify.
  2. Articles – Web Part will show any items that are derived from the Article Page content type.
  3. Catalog – Item Reuse Web Part to reuse or republish the content of an item from a catalog.
  4. Items from a Catalog – Web Part will show items from a catalog configured for this site.
  5. Items Matching a Tag – Web Part will show items that are tagged with a term.
  6. Pictures – Web Part will show any items that are derived from the Picture or Image content type.
  7. Popular Items – Web Part will show items that have been recently viewed by many users.
  8. Recently Changed Items – Web Part will show items that have been modified recently.
  9. Recommended Items – Web Part will show content recommendations based on usage patterns for the current page.
  10. Videos – Web Part will show any items that are derived from the Video content type.
  11. Web Pages – Web Part will show any items that are derived from the Page content type.
  12. Wiki Pages – Web Part will show any items that are derived from the Wiki Page content type.

All of these web parts can fetch, except Recommended Items and Catalog-Item Reuse that have special features, data from current site, current site collection, specified URL or whole index (=Don’t restrict results by location). You are able to control this with query builder in web part properties. I will tell you more about this later. This really means that you fetch and show items from almost every possible location. This is why using index in these web parts is so powerful.

Use cases that customers wants

As you can see there are a lot of good and useful web parts for your intranet site. Something like popular items, articles (news pages) or recently changed items are something that customers ask almost every time. I can really see that these will be used a lot when people learn how to use them and can recommend those to customers. You can also create extra value in you intranet with these web parts because you can focus content more closely to users in different places regardless where the content is actually created and saved.

You can for example show department related news or blog post in department community site with Items Matching a Tag web part. Only thing you have to do is create necessary managed metadata and use those when publishing different kind of content. I really think that if organizations start to use these web parts effectively we will see good and really useful intranets in the feature. Laura Rogers has written a good overall look to Content Search web part that you should take a look at: SharePoint 2013 Web Part: Content Search

Something like popular items, articles (news pages) or recently changed items are something that customers ask almost every time.

And just as a site note Content Query Web Part has also this new Query builder that I like already. Catalog mentioned on some web parts, by the way, is a new thing is SP2013. Catalogs are used in cross-site collection publishing. MVP Liam Cleary gives a nice example of using catalogs and search-drive web parts here: SharePoint 2013 – Cross Site Collection Publishing Part 1. More information from cross-site collection publishing can be found here: What’s new in web content management for SharePoint 2013 Preview publishing sites.

Plan the metadata and search!

Of course using these web parts means that you have to plan, maintain and implement your search and metadata model well. Otherwise you can’t take a really advantages from these web part. I have notice that even though many people sees that metadata and terms are important it’s not that easy to implement and adapt them to organization. Now is the real time you start to think about these things and start to discuss about metadata. Remember that that metadata is not about technical issues, it’s about real life artefacts and content. You can create metadata model without SharePoint and IT department J. We can make many nice technical solutions but if people don’t tell what kind of items they save to SharePoint we can’t take full advantages from the possibilities.

Continuous crawl

Other important thing to release here is that index is not real time. You have to tell this to your customers and make clear that they understand this limitation. Corey Roth has written a create post about search in new SP2013: Search is Everywhere! What you need to know about Search in SharePoint 2013 Preview. One basic thing is to master and schedule your content sources. SP2013 introduced a new thing called continuous crawl.


Here is what Corey he says about continuous crawl:

“This crawls your content source continuously (every 15 minutes by default). However, there is some magic that occurs now and new items can appear in the index within seconds.”.

I think that in the environment that we are talking about you should definitely use this crawling option.

I wrote down a little more about continuous crawl and configuration about it in a separated post Using and Configuring Continuous Crawl.

So everything is perfect now?

Well as you can guess from the topic I think there are still things that could have done differently. One of mine top ranked wishes for the new SP was easier handling of xsl files in content query web part. This didn’t unfortunately come true. The same thing concerns also these search-driven web parts. Styling is done is xsl file. You still have to open/copy the xsl file, make the changes and save them back to styles library. Of course you can use SharePoint Designer or Visual Studio to make the changes. And if you want to link the web part to another style sheet than OOTB one you still need to take the road of SPD or Visual Studio solution. What I was expecting was xsl editor in web part level, or minimum of possibility to link you own custom xsl file like in List View Web Part. But this didn’t come, at least not in this preview version.

One of mine top ranked wishes for the new SP was easier handling of xsl files in content query web part. This didn’t unfortunately come true.

Other missing thing in these search-driven web parts is that you are not able to create personalized views or behavior to them. For example there is no possibility to filter the search results based on user profile value like department. You can only give the department value as static property. For sure you can use target audience and but multiple web part to the site but is always a maintenance hazel. Ok, to accomplish there should be some kind of scripting possibility on the query builder.


Luckily there is always my favorite framework solution MatchPoint that can handle these two issues. MatchPoint has web part called Composite Web Part. This web part can be connect to different data sources, you can modify the query with easy to use editor and you also have an editor to handle the styling. Composite also have a special expression framework that you can use to make dynamic queries during the load time. With this web part we have made solutions where we have fetched data from different sources based on user profile values and styled them with xsl. Here’s basic information about Composite web part but I will post more details of MatchPoint Composite web part little later: MatchPoint Composite Web Part

Using Search-Driven Web Parts – Example

I think that let’s stop this novel writing and let’s look something practical example. Here is on example of using search-driven web parts in communicational Intranet – SharePoint 2013 and Search-Driven Content – Articles Web Part.

SharePoint Application Configuration part 1 – Property Bag

Property bags are power full and good way to store properties and static details that is used in SharePoint. Earlier the most common way was to store for example some URL information in web-config. And still web.config is a good place to store information. Only administrators are able to modify web.config so the information is saved in quite save way. One disadvantage (a big one even) there is with web.config. If you have multi server farm you have to make web.config changes to every server so that everything would work.

However property bags are handles through code or xml file and application server is handling the information so that information is always reachable. You can store information in many different level and object like SPFarm, SPServer, SPWebApplication, SPContentDatabase, SPWeb, SPFolder, SPListItem, SPFile. “Each property bag allows you to store a collection of key/value pairs, each key is unique, and the value has to be a string. If you need more advanced capabilities, you could choose to store complex data in the string using serialization.[1]” Property bag are available both on server solutions and sandbox solutions (from site collection level and below). Even external application can use them if they connect to SharePoint environment through API.

Advantages to use property bags

· There are provided to you out of the box.

· They are saved straight to SharePoint databases.

· There is good and simple API to use them.

Disadvantages

· No out of the box UI to modify them. But there is an good farm level solution found from Codeplex http://pbs2010.codeplex.com/

How to use property bag?

But let’s have an example of how you can use property bag in our solutions. This example is light version from real life case. Our customer wanted to have web part that can be used in multiple sites and multiple times in a site. The request also was that they want to make multiple predefined style themes from which site administrators can choose from. This meant that on a site there could be multiple web parts but all of them have different style layout (font color etc.).

On this post I will leave the creating of visual web part with editor part out. But you can download the source code from the link below and there are a lot of examples found with Google of course.

Our web part fulfilled the requirements in a following way.

a) Make the web part based on visual web part and add custom style classes to every control on the page.

b) Themes can be made so that there will be necessary CSS styling done and user can change this style to a single web part.

c) Make editor part where users sees drop down box and styles (like Blue Theme, Red Theme) from where to choose from.

d) This list of styles should be centrally defined by administrators.

e) Theme list will be saved in property bag and administrator can update it with pbs2010 tool found from Codeplex.

First we need to create the actual property bag. On this demo we create the properties on site (or web) level.

1. Create an empty module to your visual studio solution.

2. Into element.xml file here is the xml definition we used to list the possible style themes. More information about property bag xml schema can be found here: Property Bag Schema.

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <PropertyBag ParentType="Web">
    <Property Name="pbpost.messageboxstyling" Type="string" Value="Blue Theme, Red Theme" />
  </PropertyBag>
</Elements>

3. Save the element file and create a feature that will install the module to the site.

Getting the property bag information

As I told there is a editor part where we want to show list of possible styles in drop down list. The styles are saved to web property bag with a key pbpost.messageboxstyling. Teams are saved as comma separated string so we also have to decrypt them as single items.

Here is the create CreateChildControl function where we are creating the drop down list and start to fill that with the values from property bag.

protected override void CreateChildControls()
        {
            try
            {
                //Create the Dropdown list
                SelectedNewCssClass = new DropDownList();
                //Add the item from property bag
                addCSSStyles(SelectedNewCssClass);

                Label lblControl = new Label();
                lblControl.Text = "Box Custom CssClass";
                Controls.Add(lblControl);
                Controls.Add(new LiteralControl("<br/>"));
                Controls.Add(SelectedNewCssClass);
                Controls.Add(new LiteralControl("<br/>"));
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0,
new SPDiagnosticsCategory("UsingPropertyBag", TraceSeverity.Unexpected,
EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
            }
        }

And here is the actual function that reads the values from the bag and saves them as items to the drop down list.

private void addCSSStyles(DropDownList CssClass)
        {
            CssClass.Items.Add("");

            if (SPContext.Current.Site.RootWeb.AllProperties.ContainsKey
("pbpost.messageboxstyling"))
            {
                string[] cssValues = SPContext.Current.Site.RootWeb.AllProperties
["pbpost.messageboxstyling"].ToString().Split(',');

                foreach (string value in cssValues)
                {
                    CssClass.Items.Add(value);
                }
            }

So here was the short example and information about SharePoint property bags. You can find the complet Visual Studio 2010 solution from my SkyDrive (zip file names as UsingPropertyBag.zip

References:

[1] Course 10232A: Designing and Developing Microsoft® SharePoint® Server 2010 Applications material

SharePoint Application Configuration – Application Configuration

imageLately I’ve been worked a lot with projects where we have tried to find a good way to give site collection owner or farm admins possibilities to maintain and even change the way how our custom SharePoint application (web part, controls etc.) work. The answer to this is by using configuration data. The main reason to use configuration is of course flexibility. User can change things, like connection strings, if they need to.

Other thing related to this is reusability. On organization things can and will change after the new applications is finished and taken to production. When we are talking about SharePoint this is an everyday situation because the whole platform is meant to change when you organization is changing. Having the things behind some configuration you can develop features that can be used in many different organizations and cases.

For development firms this means saving on development time and better contribution marking. I have always liked the idea to make features and solutions reusable. It takes a little bit more time to plan things but in many cases this consideration will mean better, cleaner and more user friendly solutions. But to make configuration really works it means that during the planning and development you have to find answer to the following questions.

1. What things should users to be able to change?

2. How to code this solution so that it can be changed and maintained with configurations?

3. Where to store the necessary configurations?

For question one and two there is no easy answer and it always depends on the case. Of course it’s always easy to forget question number two or actually all the questions. Just make the solutions that work on this case and don’t give users and possibility to change anything. Fast, but not very lasting on long term.

But for question number three there are few good possibilities that SharePoint offers.

· SharePoint Property Bag

· Web.config

· SharePoint List

· SharePoint Web Part

· Hierarchical Object Store

On this series I will go through them and try to give you a short idea of how they work, what are the pros and cons of them so that you can consider which of them could suite for your application. I will start with one of my favorites Property Bag. My first attend was that this post would include the actual how to part also, but I want to keep things short and the introduction part became longer that I was expected. I know how frustrating it is to read how to post where it too much scrolling before they get to the point.

So the first how to part will be published in a few days.

SharePoint Application Configuration part 1 – Property Bag

MatchPoint Framework to SharePoint

As you may have noticed I have every now and then mentioned MatchPoint and SharePoint. Company where I’m working is the first official MatchPoint partner in Finland. I’m also a certified developer of the framework. But what actually is MatchPoint and why should you use it together with your SharePoint solution?

First of all MatchPoint is a framework solution that brings more flexibility and possibilities to solution developers and administrators. Framework is made by company called Colygon from Switzerland. It means that the framework internationality used and maintained. What I can say as developer is that the flexibility is create and the response time from the community (www.matchpointcommunity.com) and support team from Colygon is support is good.

One important thing to notice is that MatchPoint isn’t solution that offers for example readymade web parts or complete functionality. Offered tools are especially target to developers, heavy users and administrators. What the frameworks offers are things like extended metadata and tag management, more flexible template management, easier and faster web part development components and true reusable framework for web parts.

On the images below you can find all the reusable web parts frames included to MatchPoint framework.

image

On this other image you can find all the components from the service layer and API level.

image

Why to Use?

If I should give you 7 reasons why you should use MatchPoint framework they would be:

  1. You are able to extend you solution with features not available OOTB.
  2. Development time is much lower than usually.
  3. You are able to maintain your custom solution from one place.
  4. You can do more things straight from UI than with OOTB SharePoint = no coding.
  5. Even your or your customers power users can easily learn and maintain the system.
  6. The framework is internationally maintained and developed = lower risk in continuation, support and upgrades.
  7. There is active developer community and very low organization from framework developers and customer support to partners and developers.

Of course you have to ask why not to use it? One thing is that using a framework means that you are doing some kind of customization. Some one could thing that is bad but almost in all SharePoint environments there is some customization done. When I have to change OOTB features I rather do it with controlled tools that has been proven earlier in other projects.

From my opinion the tag and provision framework are the best things that MatchPoint can offer. OOTB SharePoint term management is great but MatchPoint offers a lot more like. Tag inheritance and automatic tag creation. Inheritance means that I can tag some site (or library etc.) with tag like Finland and every item or document can then inherit this information from the site level.

Provision framework offers more flexible way to create templates right from the browser. Users can for example create a team site, add new lists and web parts and then save this site as a template. Others can then use this template to create new team sites. Ok this can also be done with OOTB SharePoint but what if you have to add new web part to default page and add n column to the task list? Normally this would mean quite a lot time or even work especially if you are using templates made with Visual Studio. But with MatchPoint you will have one XML file that holds all the necessary elements and settings of the template and you can modify that file with easy to use editor.

Short Example

Here you can find a short video of an example where I’m making a very simple web part that is listing links from link lists from multiple sites. I won’t go this through very deeply, at least not yet. But what this video can show you are how fast and easy you can make web parts and nice functionality compared to traditional development.

The scenario here is that we have a site that has multiple sub sites. On each site there is and Announcement list called Announcements that has an extra column called Highlight. The request is that on the top level site all the announcements marked as Highlight will be shown on a web part.

More information about the framework can be found from the web site www.colygon.com/technical-features. I will also cover these things more deeply on upcoming post. If you have some questions just send me and message or contact people from Colygon. They also have very nice webinars where you can see this MatchPoint in actions.