SharePoint 2010: Media Web Part

Here is another cool new web part added to SharePoint 2010 – The Audio & Video Web Part [ a.k.a Media Web Part ]

The Media Web Part is a Silverlight Control. Once you edit the page, its available from the Insert tab in the SharePoint Ribbon.

image

This will add the Media Web Part to the page:

image

Clicking on the web part, the Web Part Options tab is revealed in the Ribbon:

image

You can select your source from the Change Media button menu.

image

From SharePoint opens up the Asset Picker dialog through which you can select a video from the current site/subsites:

image

Here is the video playing in the web part:

image

You can also change the image of the web part from the Change Image button in the Ribbon.

Currently, only two styles are available – Dark and Light

image

SharePoint WCM – Breaking the Ice – Content Driven User Controls

In our previous post, we saw how to build user controls and reference the same from our Home Page layout. In this post lets see how we can retrieve the Latest News from a SharePoint List rather than static HTML code.

Latest News

Jet30 publishes their latest news daily and wishes to show them in the Home Page. The Latest News section in our home page reflected this daily news section.

Latest News

Jet30 wants their content authors to manage the daily news and hence they choose to create a new Announcements List called LatestNews where they can manage (add/edit/delete) the daily news. The Latest News section should only display the news of that day.

LatestNews List

As you can see in the above screenshot, we have 2 items which expires today (October 6th) and the other which has expired (October 5th).

Injecting the SharePoint Logic into our user control

We now know our exact job – Query the LatestNews list for the items which expires today

The LatestNews user control now changes to:

 

Latest News User Control

We will use a Label to update today’s date and a Repeater to display today’s latest news.

Below is the updated .ascx code:

<div id="news">
    <h2>Latest News</h2>    
    <h3><asp:Label ID="lblDate" runat="server" /></h3>
    <asp:Repeater ID="rptrNews" runat="server">
        <ItemTemplate>
            <p>
                <span><%# DataBinder.Eval(Container.DataItem,"Title")%></span>
                <%# DataBinder.Eval(Container.DataItem,"Title")%>
            </p>
        </ItemTemplate>
    </asp:Repeater>
    <br class="spacer" />
</div>

And below is the code behind:

/// <summary>
/// Handles the Load event of the Page control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> 
/// instance containing the event data.</param>
protected void Page_Load(object sender, EventArgs e)
{
   AddTodaysDate();
 
   AddTodaysNews();
}
 
/// <summary>
/// Adds the todays date.
/// </summary>
private void AddTodaysDate()
{
    lblDate.Text = String
                   .Format("On {0}",
                         DateTime.Today.ToString("ddd d MMM yyy"));
}
 
/// <summary>
/// Adds the todays news.
/// </summary>
private void AddTodaysNews()
{
    List<LatestNews> latestNewsCollection = new List<LatestNews>();
 
    SPSite site = SPContext.GetContext(HttpContext.Current).Site;
 
    using (SPWeb curWeb = site.OpenWeb())
    {
        SPList lstLatestNews = curWeb.Lists["LatestNews"];
 
        SPQuery camlQuery = new SPQuery();
        camlQuery.ViewFields = "<FieldRef Name='Title' /><FieldRef Name='Body' />";
        camlQuery.Query = 
          "<Where><Geq><FieldRef Name='Expires' /><Value Type='DateTime'><Today/></Value></Geq></Where>";
 
        SPListItemCollection lstLatestNewsCollection = lstLatestNews.GetItems(camlQuery);
 
        foreach (SPListItem latestNews in lstLatestNewsCollection)
        {
            LatestNews news = new LatestNews
                                  {
                                      Title = latestNews["Title"].ToString(),
                                      Body = latestNews["Body"].ToString()
                                  };
 
            latestNewsCollection.Add(news);
        }
 
        rptrNews.DataSource = latestNewsCollection;
        rptrNews.DataBind();
    }
}

Pretty basic ASP.NET and SharePoint code :)

The AddTodaysDate updates the label with today’s date and AddTodaysNews queries the SharePoint list LatestNews items which expires today.

Build the code and deploy to the site.

You should still see the same home page, the only difference this time being that Latest News section is now content driven :)

Latest News Control

What about Web Parts?

You might be wondering why I haven’t used Web Parts and chosen to build User Controls. I think this discussion would take us away from our current trending topic, but do hold on, I will come up with a separate post explaining why I choose to build User Controls and not Web Parts in the WCM world.

What next?

In our next post, we will see the necessity of building custom field controls and build one!

For now, you can download the source code from here.

If you don’t have SPVisualDev, build a WSP package and deploy it to test.

Remember that, until we have our own site definition, we are not done yet and things will be little messy :)

SharePoint WCM – Breaking the Ice – Building User Controls

In our previous post, we saw how to build a Page Layout for our Jet30 site. Today we will see how to build user controls. We will dissect some of the parts of the Home Page and build them as user controls.

So, for those who don’t remember our Home Page, below is a screenshot:

Jet30 Home Page

And weeks back, we also had our initial discussion on dissecting the page into various user controls.

Let us take the simplest of the controls – Latest News and New Services Overviews and turn them into user controls:

user controls

User Controls 101 For SharePoint

If you are an ASP.NET developer, you are already familiar with User Controls. They are nothing different in SharePoint except that they may consume SharePoint API and interact with SharePoint data. Let us initially forget that ‘SharePoint interaction’ and just try to build the user control with the static HTML data we already have. The user controls are going to built as assemblies (.dll) and deployed to GAC.

Where do user controls live?

User controls should be living somewhere so that we can load them in the code. So, where do we put our user controls?

The best and recommended place to put them is in the CONTROLTEMPLATES folder in the 12Hive. You can find many of the out-of-the box SharePoint user controls there:

CONTROLTEMPLATES Folder

Since our user controls are custom built (not out-of-the box), it is always better to put them in a separate folder inside the CONTROLTEMPLATES. So, for Jet30, our user controls will reside in a folder Jet30 inside the CONTROLTEMPLATES:

Jet30 Flder in CONTROLTEMPLATES

But we are not going to create the folder manually, rather deploy them as solutions (.wsp)

Jet30 User Control Solution

To keep things granular, I created a new SPVisualDev solution called Jet30.SharePoint.UserControls :

Jet30.SharePoint.UerControls Solution

I then created the CONTROLTEMPLATES\Jet30 folder:

Jet30 CONTROLTEMPLATE Folder

Added my two user controls (.ascx) to the CONTROLTEMPLATES\Jet30 folder:

User controls added

You can easily add user controls using SPVisualDev item templates:

SPVisualDev Item Templates

Adding the static HTML code to user controls

Now as we have our user controls ready, we are good enough to move the Latest News and New Services Overview sections to their respective user controls from the Home Page layout.

Browse the Home Page layout until you hit the two required sections:

Home Page controls sections

Copy the code inside the news start & news end , services start & services end to the respective user controls.

Latest News user control:

Latest News user control

New Services user control:

New Services user control

Referencing user controls in the Home Page

So, now the only task left is to reference and add these user controls in our Home Page layout.

First, register a tag Jet30 whose src tag match the location of our user controls:

<%@ Register TagPrefix="Jet30"     
    Src="~/_controltemplates/Jet30/LatestNewsControl.ascx" 
    TagName="LatestNews"%>
<%@ Register TagPrefix="Jet30"    
    Src="~/_controltemplates/Jet30/NewServicesControl.ascx" 
    TagName="NewServices" %>

Now, we can make use of the tag prefix and name and reference our user control in the page:

<!--news start -->
<Jet30:LatestNews runat="server" />
<!--news end -->
<--services start -->
<Jet30:NewServices runat="server" />
<!--services end -->
Build and deploy the solution and refresh the Home Page.
 
You should still see the same home page, the only difference this time being that Latest News and New Services are user controls.
 
What next?
In our next blog post, we will go one step further with the user controls. We will store and retrieve Latest News from SharePoint!
 
For now, you can download the source code from here.
 
If you don’t have SPVisualDev, build a WSP package and deploy it to test.
 
Remember that until we have our own site definition, we are not done yet and things will be little messy :)

SharePoint WCM – Breaking the Ice – Building the Home Page Layout

In our previous post, we saw how to build a SharePoint Master Page with custom branding. Let us now build a Page Layout. A page layout defines various components in a page – web parts or field controls or static content etc.,

MSDN describes the relationship between a master page & page layout in the best way possible:

image

So, currently we have our Jet30’s Home Page, which is:

And we were able to build a master page which essentially had everything in it. A master page typically should contain a header, content area and a footer. The page layouts now come in and fill the content area, which makes:

jet30-home-page-layout

Yep, so that separates the header, top navigation, footer and footer navigation.

Home Page Content Type

As we only have home page design at the moment, lets create the Home Page layout, which essentially will become the home page of the site.

Everything is a content type in SharePoint. So does a Page.

image

And our Home Page layout is no exception. Before creating the home page layout, we will create a Home Page content type inheriting from the Page content type. We will then create the page layout and associate this content type to our home page.

Creating the Home Page Content Type

There are several ways to create and deploy content types. The one I follow is – wrap each content type into its own feature – one feature for every content type. Why? This makes much easier to manage the content types, especially when you want to upgrade them.

image

So, I added a new feature using SPVisualDev. With SPVisualDev, its quite easy to create a content type inheriting from another content type.

image

You can see in the above screenshot that SPVisualDev allows you to inherit either from built-in content type or from a content type on a site. Since the content type Page is part of the Publishing Feature, it is available as a content type on a site.

image

And my Home Page content type is ready!

image

That was easy :)

Home Page Layout

Now that our Home Page content type is ready, we can now create our home page layout.

How do we create a page layout?

  • Create a new Feature.
  • Include all your page layouts in this new Feature
  • Add a new Page Layouts module which will tell SharePoint about your page layouts
  • Deploy to your site

Here is how it will look like:

image

The feature Jet30_PageLayouts contains a layout called HomePage.aspx and an elements file PageLayouts.xml

The PageLayouts.xml has the Page Layouts module and our Home Page Layout defined:

image

The Home Page layout is copied to the site’s Master Pages and Page Layouts library with a title Jet30 Home Page. We also associate the Home Page content type by specifying the Home Page Content Type in the PublishingAssociatedContentType property.

How do we move content to Page Layout?

We are dealing with Master Pages, which are nothing but ASP.NET master pages. As we discussed earlier, SharePoint is built on top of ASP.NET platform. So, think SharePoint Master Pages and Page Layouts to be ASP.NET Master Pages and ASP.NET Application Pages in a normal ASP.NET application. All we need to do to move the content area to a page layout is create ContentPlaceHolders in the master page!

So, our Master Page now looks like:

image

If you deploy the new Master Page, the site now looks like:

image

With the contents moved over, our Home Page layout looks like:

image

As you can see, we have brought the home page content area from the Master Page to this Page Layout!

So, now we can go ahead and deploy our new page layout!

Selecting the Home Page Layout

After deploying the page layout, you can find it in the Master Pages and Page Layouts library:

image

If you now create a new SharePoint Page, you should see the Jet30 Home Page listed in the page layouts option:

image

Create the new page and you now have the new Jet30 Home Page (not yet the site default page though ;) )

image

That wasn’t tough!

What next?

In the next post, lets dissect this page layout into various user controls as we discussed earlier!

For now, you can download the source code from here.

If you don’t have SPVisualDev, build a WSP package and deploy it to test.

Remember that until we have our own site definition, we are not done yet and things will be little messy :)

SharePoint WCM – Breaking the Ice – Building the initial Master Page

In our earlier post we got introduced to our new client Jet30, had our initial discussions and we came out with the initial home page/website design.

Jet30 Website Template 

Before getting into the discussion of what would be our site columns, content types and page layouts, let us use this template, create a SharePoint master page and activate it on an existing publishing site and see whether it works. It is always better to go step-by-step than going down and creating everything at once (site definitions, page layouts etc.,). However, if you are quite familiar with this process, you might end up doing everything at once than going this way. But for now, let us build a Jet30 Master Page.

Create a Sample Publishing Site

Create a publishing site (with publishing site features enabled). The master page, style sheets will be deployed to this site for now.

[I created a site called http://jet-thirty]

SharePoint Development Tools Used

1) WSPBuilder

2) SPVisualDev

Building the Master Page

All master pages (and page layouts) reside in the Master Pages and Page Layouts list in the publishing site.

image

It is always the best practice to manage everything and anything using Features in SharePoint. The same applies for our master page too – We will create a SharePoint Feature to deploy the Master Page to the publishing site.

Using SPVisualDev, I created my SharePoint project and added a new feature called Jet30_MasterPages.

image 

The feature has two modules.

  1. Jet30MasterPage
  2. Jet30Css

image

As you can see, both the Master Page and Css files are going to the SharePoint Master Pages and page layouts list in the site.

Modifying the Jet30MasterPage.master

image

If you added the Master Page using SPVisualDev, it will generate the minimal master page with all the necessary placeholders.

image

Insert all the HTML code of the Jet30 website template into this master page after the line

<PublishingConsole:Console runat="server" />

One another change we need to do in the master page is to add reference to the Jet30 style sheet. This can be done in the head section.

<head id="Head1" runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <SharePoint:RobotsMetaTag ID="RobotsMetaTag1" runat="server"/>
    <title><asp:ContentPlaceHolder id="PlaceHolderPageTitle" runat="server"/></title>
    <SharePoint:CssLink ID="CssLink1" runat="server" />
        
    <link rel="Stylesheet" type="text/css" href="/_catalogs/masterpage/jet30-style.css" media="screen" />
    
    <asp:ContentPlaceHolder id="PlaceHolderAdditionalPageHead" runat="server"/>
</head>

Modifying the CSS

There is nothing much to modify in the Jet30 style sheet except for the image references. Images are now available in the /_layouts/images/jet30/ than the template’s images folder.

image

The original CSS file will have entries something like this:

#header{
    background:url(images/header.gif) 0 0 no-repeat;
    width:981px;
    height:274px;
    position:relative;
    margin:0 auto;
}

Which will change to:

#header{
    background:url(/_layouts/images/jet30/header.gif) 0 0 no-repeat;
    width:981px;
    height:274px;
    position:relative;
    margin:0 auto;
}

Images will now be properly referenced.

 

 

 

 

 

 

 

Deploy the Jet30_MasterPages Feature

You are now ready to deploy this feature to your publishing site [I deployed to my sample site http://jet-thirty]

image

As you can see in the above screen-shot, it is quite easy to manage features if you are using SPVisualDev.Once deployed, you can find the master page & CSS style sheet in the SharePoint Master Pages and page layouts list in the site.

image

Selecting the Jet30 Master Page

Now as the master page is installed & activated, we can select the master page in our site.

Go to Site Actions->Site Settings->Modify All Site Settings. Select Master Page from Look and feel section.

Select the Jet30MasterPage for Site Master Page and System Master Page

image

If you browse to your site, you should see the Jet30 template up and running!

image

You can now build the WSP package and deploy it to any other server/site.

image

So, are we done with Master Page?

NO – So far, we have managed to load the master page into an existing site. Since we applied the master page to the whole site and to all page layouts, it has been applied to every page. If you scroll down, you can still see the existing web parts.

image

This is because of the page layout being used which has web part zones in them.

What next?

Our next step is to create the Home Page layout than using the pages in the site.

For now, you can download the source code from here. If you don’t have SPVisualDev, build a WSP package and deploy it to test.

Remember that until we have our own site definition, we are not done yet and things will be little messy :)

SharePoint WCM – Breaking the Ice – A look into the website template, Home Page and other Controls

In the previous post we saw the basic initial steps in getting started with SharePoint and WCM. I also warned you are going to have one hell of a ride with SharePoint and WCM!

Well, lets get started then!

To make things simpler, I have downloaded a website template called Jet30 from Templateworld. Below is the screenshot of how the website looks

jet30_web_template

Jet30 and Home Page

Assume that Jet30 is our new client who is interested to build their website using SharePoint, and has agreed upon the above template for the home page. Its more than enough for us to start the SharePoint development. But before that, we also need to make sure what components make up this home page, things like:

- Which are static content?

- Which contents are editable?

Site Structure

As you can see in the template, Jet30 is interested to have categories or sub-sites or sections in their website, which reflects the horizontal navigation menu at the top

jet30_subsites

To make things simpler again, lets say we create a root site and build the rest as sub-sites.

So, we are going to have a root site (site collection) called Jet30(Home) and the rest are going to be sub-sites:

- About Us

- Services

- Support

- Communication

- Why Choose Us

- News

- Testimonials

- Contact Us

Lets also assume these categories have their own reasons to be a sub-site.

Dissecting the Home Page

After discussing further with Jet30, I am now able to dissect this home page layout into individual components.

So, below is the first section:

final_website_1

and the second section:

final_website_2

As you can see from the screenshots above, below is the list of controls:

  1. Top Menu Control
  2. Home Page Banner Text Control
  3. Page Second Banner Control
  4. Page Pods Control
  5. Main Description Pod Control
  6. Latest News Control
  7. New Services Control
  8. Login Control
  9. Footer Control

Jet30 also confirms that most of these controls will be used in other page layouts too.

Jet30 has also confirmed that the following controls should be editable, meaning contents be managed:

  1. Home Page Banner Text Control
  2. Page Second Banner Control
  3. Page Pods Control
  4. Main Description Pod Control
  5. Latest News Control
  6. New Services Control

Sweet, I think we are now ready to open Visual Studio and do some SharePoint development!

Whats Next?

There is still one thing we haven’t dealt with – the required site columns, content types and site definition – which is what we are going to see in our next blog post!

SharePoint WCM – Breaking the Ice – Getting Started

SharePoint, with its Publishing Feature provides a powerful and extensible platform to build public facing websites, which are otherwise called as internet websites or public facing websites or WCM websites. Some of the top SharePoint (publishing) websites include - Ferrari, Cadbury, Hawaiian Airlines, NZTE (more here & here). Without much discussion, lets get straight to the point – What it is like to build a website using SharePoint?. There are so many myths (which you might hear and read often) surrounding this which conclude SharePoint is not suitable for building such complex websites - Well, SharePoint is indeed a powerful platform not only to build intranet portals, but also WCM sites.

Some of the things you might immediately hear from your customers as well your own team (if the team is new to SharePoint WCM) would be:

Do we really need to use SharePoint to build this website?

I heard SharePoint is used only for Intranet and document management. Are you sure about this?

We don’t have SharePoint here, do you think it is a good idea to invest?

What about branding?

I want to have all those Web 2.0 features in my website. Can I?

How do I manage my content? Will SharePoint provide the ability to backup data regularly?

Search is very important for my website. What options do we have in SharePoint?

I heard something about Content Deployment, can we make use of it too?

Under the hood, SharePoint is nothing but ASP.Net. SharePoint is built on top of the ASP.Net framework, so the same ASP.Net concepts/rules apply to SharePoint too, except that some might be very specific to SharePoint.

So, lets get started and become familiar with few things before we start our long journey!

Make sure you have a look (at least once) at Joel Oleson’s 10 Steps to SharePoint Success

 

SharePoint Server 2007 Publishing Feature

One of the out-of-the box features available in SharePoint Server 2007 is the Publishing Feature. To use the web content management features, this feature must be activated in the site level or site collection level (based on where you need them). This feature provides the basic building block for the web content management websites. Turning on this feature will also install publishing-enabled content types and publishing-enabled site templates. Now, you have the basic platform which you can make use of to build your website!

Sweet, lets go with the Publishing Feature then!

One of the major misconceptions that I hear a lot of times is that the ‘out-of-the box’ Publishing Feature is all what is needed to build a public facing website – NO!

The Publishing Feature gives you nothing but the basic platform, and you as the website builder/developer have the full freedom to build/tweak/customize it to your needs and requirements!

Requirements is the KEY

As it goes with any project, know the requirements before getting down to build that website. Sit with your customer/team, arrange some meetings - get to know them and their requirements, what they want from the website, who would be the users of the website etc., And yes, don’t forget the SharePoint 80/20 Rule. This should roughly give you an idea what your customers are expecting out of this website and how SharePoint can help achieve that.

What would these requirements be?

Requirements can be anything and everything!

Some examples to get you started are:

- Site Structure

- Home Page or Welcome Page Layout

- Other Page Layouts

- Static Content Vs Dynamic Content

- HTML Web design template

- The SharePoint environment where the website is going to be deployed

There is also other requirements which you as a SharePoint consultant or developer need to consider. Some examples are:

- Dissecting every Page Layout into different individual components

- Web Parts Vs User Controls Vs Custom Field Controls

- Managing content in Lists Vs Providing in-place editing experience [More on this later in this series]

- Not to make any promises that everything and anything is possible, rather work out whether it is feasible to do so.

- Know your budget and work accordingly. [Some requirements might just go on and on and empty your pocket!]

[Requirements quoted above are solely to get you started and in no way mean these would be the only requirements list for a particular project]

To design or develop first?

This is a tricky question. I think it is better off if you have a HTML web design template ready by your designers. This would make the branding and development process much easier than what you might think. I am not saying the entire website should be designed, but at least an initial version with few page layouts. Remember that one of the requirements was to dissect the page layouts into different individual components – this task becomes much easier now as you have a template to work with. Now you can go build that master page, page layout(s), user controls or web parts or custom field controls depending on the requirements.

Know the SharePoint environment

This is the most important thing to do – Getting familiar with the SharePoint environment where the website is going to be deployed – Things can get really bad if you don’t configure the environment properly. So make sure you get hold of a SharePoint Administrator or SharePoint Network Infrastructure (or whatever you call them) and examine the available options in the environment. If there is not one yet, then this is the good time you start building one! This becomes entirely a separate challenging task! [ Good times, eh :) ]

Don’t ever under-estimate this task!

SharePoint WCM – Breaking the Ice

This blog post what you are reading is the first post of the kind, in this series. In the upcoming blog posts in this series, I will be taking you through the journey of what its like to build a WCM website using SharePoint.

All Set?

Then you are ready for one hell of a ride with SharePoint :)

IE8 to SharePoint-‘Are you sure you want to navigate away from this page?’

Building ‘easy’ and ‘complex’ user controls or field controls is one of those daily jobs that a SharePoint developer will do when building WCM websites.

Recently whenever I was navigating from the Edit Mode, whether it may be a postback or clicking on a link to a different page, IE8 prompts with this ‘wonderful’ yet ‘awesome’ message:

wcm_editmode_ie_error

Here is my custom field control in edit mode

wcm_editmode_control

So, as you can see in the above screenshot, I have a repeater and then some command arguments – Remove and Sort – Whenever I tried to remove the item or sort, IE8 halts for at least a minute and then prompts me with that message. Clicking on OK does finish the job, but why this message?. This does not happen in IE6, IE7 and Firefox.

Luckily, one of the MSDN forums user Sergioko has found a workaround for this problem:

Hi people,
I have installed Intenet Explorer 8 and started experience a problem. When my publishing page is in Edit mode and I click any link to navigate out to a different page IE8 prints 'Saving Page Content...' in its status bar for about 20 seconds and then displays a message box 'The page took too long to save...'. There were no such error with either IE7 or FireFox. After playing with Javascript debugging, I found that SBN_CallBackHandler() client function of SaveBeforeNavigationControl is not called as it supposed to. It looks like the implementation of XMLHttpRequest object in IE8 is somehow different from the previous release. I'm not sure if it is a bug of IE8 or SharePoint javascript but the problem exists. Fortunatelly, IE8 allows you to turn off its advanced setting 'Enable native XMLHTTP support' (enabled by default) in menu Tools/Internet Options/Advanced. It solves the problem but I would like to have more correct solution :-)  Any ideas?

Yes! Go to Tool->Internet Options->Advanced and disable ‘Enable native XMLHTTP support’ and everything works fine!

wcm_editmode_ie_option

I think the SharePoint Team should be made aware of this bug as this is indeed a show-stopper in regard to user experience in the Edit Mode (which is very common in WCM websites and upgrading to SP2 does not solve this issue)

 

Anyone from the SharePoint Team investigate this issue?

SharePoint Conference – My slide deck and samples

image003

The first ever New Zealand SharePoint Conference which was held last week (July 2nd – 3rd) was a blast! We not only had local speakers, but also international speakers which included:

1) Joel Oleson

2) Paul Culmsee

3) Erica Toelle

3) Steve Smith

4) Paul Papanek Stork

I have uploaded my slide deck and samples for my talk– SharePoint Custom Field Controls.

You can download them below:

Hats off to Chandima, Mark Orange and Debbie Ireland for organizing the conference and everything!

Set Available PageLayouts for your Site

Below is a code snippet for setting available page layouts for your site:

 

List<String> strPageLayoutsToPersist =

        new List<string> { "Home Page", 
                           "General Detail Page", 
                           "Email Me Page", 
                           "Category Page" 
                         };
using (SPWeb spWeb = spSite.RootWeb)
{
        PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(spWeb);
        
        // Get avaialble page layouts for our content types
        PageLayout[] myPageLayouts = pubWeb.GetAvailablePageLayouts().Cast<PageLayout>()
            .Where(p => strPageLayoutsToPersist.Contains(p.AssociatedContentType.Name))
            .ToArray();
 
        // Set the available page layouts to our content type
        pubWeb.SetAvailablePageLayouts(myPageLayouts, false);
 
        // Update the web
        pubWeb.Update();
}

 

This will hide every page layouts except those you specify in the strPageLayoutsToPersist

Highlighting the current page (site) in a custom navigation

When you build your custom navigation menu in SharePoint, highlighting the current page in the navigation menu is one of the various things we like to do. Something like this:

image

You can see how People and Skills Development funding is highlighted and also their parent items – ANZBPF programmes and Australia and New Zealand Biotechnology Partnership Fund

I hope you are using PortalSiteMapProvider to build your custom navigation. Below is a code snippet which gets all the pages in a particular site

PortalSiteMapProvider psmp = PortalSiteMapProvider.CurrentNavSiteMapProvider;
psmp.IncludePages = PortalSiteMapProvider.IncludeOption.Always;
    
SiteMapNode siteMapNode = psmp.FindSiteMapNode(elevatedWeb.ServerRelativeUrl);
List<SiteMapNode> nodes=new List<SiteMapNode>();
 
foreach(SiteMapNode node in siteMapNode.ChildNodes)
{
    nodes.Add(node);
}
 
// now bind the List to repeater or ListView etc.,

Given a SiteMapNode, here is a method which can find whether that particular node is current page

private bool IsCurrentPage(SiteMapNode node)
{
    return node.Url.ToLowerInvariant() == 
             HttpContext.Current.Request.Url.LocalPath.ToLowerInvariant();
}

Now you can easily change the CSS styling for the selected node in your navigation based on whether it is current page or not.

 

 

You can also manipulate the URL and find out whether it is your current site too

Using the Reusable Content to style HTML Contents

Sometimes in your WCM website, you might want users to enter some content in a content area but still apply those styles for the content.

Using the RichHTMLField control, users can enter rich HTML content, but if the content needs some styling or formatting to be applied, then its pretty hard to do it via the editor.

image

What you see above is some content without any styling applied. When you render the field value, the content will be applied without any styling as well. If you still need to apply the styling, you can do it by switching to HTML mode, as shown below.

image

This would be a pretty difficult job for the content editors especially if they want to do the same thing at multiple places.

Is there something that would make the job easier?

 

Yes, and they are called Reusable Contents!

In your Publishing Website, you can see a List called Reusable List. You can use this List to upload your HTML template (with all those styles and formatting) and reuse them across the site and is also accessible right away from the RichHTMLField control!

Content Category

Content Category identifies where the reusable content is going to be available. This is initially empty. So if you want to use in places like RichHTMLField controls, then you need to populate the content category as WYSIWYG Templates

Go to your Reusable List settings and choose the Content Category column from the Columns

image

Under the Additional Column Settings enter the choice - WYSIWYG Templates

image

Now, you can add the new reusable content item

image

Make sure you choose Reusable HTML as the Content Type and WYSIWYG Templates as the Content Category. (Choose to automatically update based on your needs. If you are going to use reusable content as a HTML template for styles or formatting, then it is better not to automatically update)

The reusable content will now be available in the RichHTMLField controls of your website

image

Below is an example of the reusable content popup

image

You can choose the reusable item you want to insert using the above popup.

Customizing the AssetUrlSelector

One of the very useful SharePoint Publishing Controls is the AssetUrlSelector

This control allows users to pick any asset (images or documents or files or pages etc.,) from the site collection

Below is an example of how this control looks when you add it to your page

asset-picker-control

Below is the picker dialog

asset-picker-dialog

If you want to customize the AssetUrlSelector control, you can do so by modifying some of its properties

For example, below is an example code segment:

 

<%@ Register TagPrefix="PublishingWebControls" 
    Assembly="Microsoft.SharePoint.Publishing, 
                   Version=12.0.0.0, 
                   Culture=neutral, 
                   PublicKeyToken=71e9bce111e9429c"
    Namespace="Microsoft.SharePoint.Publishing.WebControls" %>
<PublishingWebControls:AssetUrlSelector ID="urlVideoSelector" 
    IsUrlRequired="true"  
    UseImageAssetPicker="false" 
    AllowExternalUrls="false" 
    runat="server"
    DefaultOpenLocationUrl="~Site/Video Library/Forms/AllItems.aspx"
    OverrideDialogTitle="Video Picker"
    OverrideDialogDescription="Select a video" />

 

As you can see in the above code snippet, I have customized few things:

1) Default open location

2) Picker Dialog title

3) Picker Dialog description

The UseImageAssetPicker is an interesting property which when set to true will open the Images library in the top level site, which is quite handy!

Getting the Url of the selected asset via code is very simple:

string videoUrl = urlVideoSelector.AssetUrl;

Visit this MSDN page for more customization options on the AssetUrlSelector control

Using query parameters in SharePoint page layouts

I had a strange case today where SharePoint was throwing this error

No item exists at http://mytestsite?id=4.  It may have been deleted or renamed by another user.

I use pagination in one of my page layouts and I got the above error when I select a page in the preview display mode when I check in draft. There was nothing wrong in the code that I could change as things seem to work fine if I publish the page.

Googling, I found this thread at the MSDN forums

Never put the same name to your parameters what sharepoint is using as internal or display name.
Give your own name then you never get this problem.

like:- Instead of  http://server/Pages/Publish.aspx?publishFileName=folderName/subfolderName/filename&ID=12

use this  http://server/Pages/Publish.aspx?publishFileName=folderName/subfolderName/filename&PublishItemID=12

Yep, things worked fine for me after changing my query parameter 'id' to something else, like 'pageid'

http://mytestsite?id=4 to http://mytestsite?pageid=4

Its very bad that SharePoint internally uses the query parameter "id" for its internal use. I am sure many developers would choose 'id' as the query parameter for anything they start with. I mean, something like "spid" or "sharepointId" would have been fine, right?

 P.S - http://mytestsite is some randomly chosen name

SharePoint: Customising the EntityEditorWithPicker

I am sure many SharePoint users will be familiar with the EntityEditorWithPicker. Well, if you are wondering what the hell is this EntityEditorWithPicker, below is a screen-shot:

image

Yes, that nice little TextBox portion along with the ‘Check for Names’ and ‘Browse’ button is the EntityEditorWithPicker. Don’t forget that ‘dialog box window’ which comes when you choose to browse ;)

SharePoint being extensible, it is very easy to create your own custom EntityEditorWithPicker. You can implement it such a way that it loads some data from a list and allows the user to select an list item. To do so, you should extend three classes:

Below is a diagram which represents the above:

image

The picker dialog represents that ‘dialog box window’. The results are returned from the simple query control to the picker dialog. The picker dialog is attached to the entity editor so that the entity editor is aware which is that ‘dialog box window’ to open.

Putting the respective classes to their user interface, it becomes:

image   image

Looks easy, isn’t it :)

For code sample, Igor Kozlov has an excellent sample on customising the EntityEditorWithPicker on his blog.

Wouter van Vugt has an advanced sample on creating a CustomField by using EntityEditorWithPicker (You can grab the code sample here)


Creative Commons License
Chaks' Corner Blog by Chakkaradeep Chandran is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.
Based on a work at www.chakkaradeep.com.
Permissions beyond the scope of this license may be available at http://www.chakkaradeep.com.