Sunday, November 28, 2010

SharePoint 2010 Timer Job UpdateProgress

SharePoint 2010 has updated some of its timer job features (see http://pathikhrawal.wordpress.com/2010/08/21/enhancement-in-timer-jobs-in-sharepoint-2010/). Now SPJobDefinition offers an UpdateProgress Method, to show the status of the timer job in a status bar.


UpdateProgress
To check the status of a timer job go to "Central Administration > Monitoring > Check Job Status".

Check Job Status link in the CA


The following code snipplet  is an example of how you could use this method. The job reads a rss feed and uploads some pdf files into a document library. The progress bar is updated by each uploaded file. The snipplet is not complete, because of copyright. I commented out some regions but you can see how you could use the updateprogress function.





public class PressListTimerJob : SPJobDefinition
{
  /// <summary>
  /// We must persist the to have in the execute function
  /// </summary>
  [Persisted]
  private String mRootSiteUrl = String.Empty;        




  public PressListTimerJob() : base() { }


  public PressListTimerJob(string jobName, SPWebApplication webApp, string featureName)
: base(jobName, webApp, null, SPJobLockType.Job)
  {
  using (SPSite rootSite = webApp.Sites[0])
  {
mRootSiteUrl = rootSite.Url;
  }
  }


  public override void Execute(Guid targetInstanceId)
  {            
LoadData();
  }


  private void LoadData()
  {
try
  {
      SaveData();
  }
  catch (Exception ex)
  {
// LOG Exception ...
  }
  }


/// <summary>
/// Writes the data into the SharePoint list
/// </summary>
/// <param name="data">The data to write into the list</param>
  private void SaveData()
  {
  try
  {
  // GET SITE & WEB
using (SPSite site = new SPSite(mRootSiteUrl))
{
using (SPWeb web = site.OpenWeb())
{
// Get list                        
SPFolder pressList = web.Folders[mListName];
Boolean allowupdate = web.AllowUnsafeUpdates;
web.AllowUnsafeUpdates = true;                                               
// Get Rss Items
XmlNodeList items = mData.SelectNodes("//item");
WebClient client = new WebClient();


// Create proxy if needed
if (!String.IsNullOrEmpty(mProxyUrl))
client.Proxy = new WebProxy(mProxyUrl);


#region >> Upload files into library                       


int itemCount = items.Count;
int itemCountPercent = itemCount / 100;


if (itemCount > 0)
{
int itemsUploded = 0;
foreach (XmlNode item in items)
{                               
// Get link
if (!String.IsNullOrEmpty(link))
{
// Download pdf file

// If pdf has content upload to library
if (pdfFile.Length > 0)
{
// Upload file
++itemsUploded;
this.UpdateProgress(itemCountPercent * itemsUploded);
}
}
  }
          }
web.AllowUnsafeUpdates = allowupdate;                        
  }
  }
  }
   catch (Exception ex)
  {
  // Log Exceptions
  }
  }
}

Monday, November 15, 2010

Play a video from a asset library in SharePoint with the built-in Silverlight Media Player

The Problem:
You want to place a link into your SharePoint site which opens the Silverlight player in a lightbox and plays a video from a asset library.

Solution:

1) Place the link within an other HTML element like a div, li or span and give this element an id. The link can be somewhere in this container, also in a deeper level

- the link to the video must be serverrelative
- the link can have a title. This can be used as Video title

<div id="mediaplayer">
   <a href="/site/listname/myvideo.wmv">Video</a>
 ..
 ..
</div>


Video link




2.) Place a script tag for the mediaplayer library and a custom script tag for our custom js. You must place it after or in the onload event, because when you use getElementById the element must exist in the DOM.


<div id="mediaplayer">
   <a href="/site/listname/myvideo.wmv">Open Video</a>
 ..
 ..
</div>
<script type="text/javascript" src="/_layouts/mediaplayer.js"></script>
<script type="text/javascript">
  _spBodyOnLoadFunctionNames.push('mediaPlayer.createOverlayPlayer');
  mediaPlayer.attachToMediaLinks( document.getElementById('mediaplayer'), ['wmv', 'avi', 'mp3']);  
</script>


Silverlight player



The "spBodyOnLoadFunctionNames.push('mediaPlayer.createOverlayPlayer'); " creates the overlay

The methode "mediaPlayer.attachToMediaLinks " needs 4 arguments.
(1) The DOM object which surrounds the links
(2) The extensions to pay attention to. It searches the <a> Tag for this extensions
(3) templateSource. A Template for the player
(4) Use Title. When true the title attribute of the a tag is used as player title


Update 17.02.2011: Modifications for Firefox
A reader has commented that the code above does not function in Firefox, and was right.
So I opened the assest library in Firefox and tried to play the video there. No chance.

After digging deeper into the code of the mediaplayer.js I think now that the problems occurs between the communication of Silverlight and JavaScript, but not sure when. When Silverlight Objects are initialized they create a Wrapper Object for their object DOM Nodes. In MediaPlayer.js the HTML for the object Tag is created automatically by the createMediaPlayer function. Firefox could not always create these DOM Wrappers (but sometimes??) when the object tag is created automatically. So the easiest way to create the player in Firefox is to add the object tag manually:

<div id="mediaplayer">
  <a href="/site/listname/myvideo.wmv">Open Video</a>
...
</div>
<div>  
      <object height="1" width="1" id="Silverlight_Shared_MediaPlayer" data="data:application/x-silverlight," type="application/x-silverlight" style="position: fixed; top: 0pt; left: 0pt; z-index: 50;">  
           <param value="#80808080" name="background">  
           <param value="true" name="enableHtmlAccess">  
           <param value="/_layouts/clientbin/mediaplayer.xap" name="source">  
           <param value="isOverlayPlayer=true" name="initParams">  
           <param value="true" name="windowless">  
      </object>  
 </div>  
 <script type="text/javascript" src="/_layouts/MediaPlayer.js"></script>       
 <script type="text/javascript">  
      mediaPlayer.attachToMediaLinks(document.getElementById('mediaplayer'), ['wmv', 'avi', 'mp3']);  
 </script>  

Friday, November 5, 2010

Setting the default page layout in onet.xml (SharePoint 2010)

In SharePoint 2010 you have the option to choose a default page layout when you create a page.

Setting the default page
When you create a new page, a dialog pops up where you enter the name of the site.



You can configure your onet.xml and define the default page by the defaultpagelayout property in the publishing feature.



Or you can set it programmatically as described in SharePoint Blues.

There are also several other properties offered by the Publishing feature you can set:

  • ChromeMasterUrl
  • WelcomePageUrl
  • PagesListUrl
  • AvailableWebTemplates
  • AvailablePageLayouts
  • NewPageUrlToken
  • AlternateCssUrl
  • SimplePublishing
  • VersioningOnPages / Documents / Images
  • EnableModerationOnPages / Documents / Images
  • EnableApprovalWorkflowOnPages / Documents / Images
  • RequireCheckoutOnPages / Documents / Images
  • EnableSchedulingOnPages /Documents / Images
  • AllowSpacesInNewPageName

Each property needs a different value. You can find a good listing of the properties and values to use on blog post of Carsten Keutmann.

If SimplePublishing is set to false, all the properties concerning versioning, moderation, workflowapproval, checkout and scheduling are set to true. Otherwise all are set to false. But you can override them when you use p.e. "SimplePublishing" = true and set VersioningOnDocuments = true;

Interesting is also the new "AllowSpacesInNewPageName" property. It does what he says. If set to false, the checkbox for "Convert spaces to '-' " in the site property settings is checked and spaces are converted to '-'.

Convert Spaces to '-'
In code-behind the web property "__AllowSpacesInNewPageName" is set to true.

If the Publishing Feature gets activated, a web property called "__PublishingFeatureActivated" is set to true.

Wednesday, November 3, 2010

ContentTypeBinding Error - Object reference not set to an instance of an object

An error occurred binding content type '0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900...' to list '/ct2/Pages' on web 'http://pilatus/ct2'.  Exception 'Object reference not set to an instance of an object.'.

This exception occures when you try to bind an empty or non-existent content type to a list. An empty content type is a content type with no fields.

Example of an empty content type.
<ContentType ID="0x010100C568DB52D9D0A14.."   
  Name="Basic Page"
  Group="Custom.Pages"
  Description="Basic Page">
     <!-- here must be some fields -->
    <DocumentTemplate TargetName="/_layouts/CreatePage.aspx" />  </ContentType>

Tuesday, November 2, 2010

MatchPoint Condition - Show only data from last months

If you have a MatchPoint Composite oder DataGrid WebPart and you want to show data from a list which is from current month, from the last months or coming months you can use following condition(s). The field you check should be DateTime field.

MP Configuration

The condition checks if the content of the Date field is lower than the 1st of the current month. If you want the last day of the month, you can use AddMonth(1).AddDays(-1)

How to hide the SharePoint Ribbon in Non-Edit Mode

If you’ve ever developed a page for SharePoint 2007 you certainly used the EditModePanel control to control content visibility. This control now has changed in SP 2010 and ignores the Page Editmode. But there is a possibility to do this with no custom code.


  1.  Locate the position of the class "s4-ribbonrow" and add a display style. (Or overwrite the class in your css). This will hide the panel in DisplayMode.
    <div class="s4-pr s4-ribbonrowhidetitle" id="s4-ribbonrow" style="display: none;">

  2. Add following code after the ribbon div. This will show the ribbon in EditMode.
    <publishingwebcontrols:authoringcontainer displayaudience="AuthorsOnly" runat="server"><publishingwebcontrols:editmodepanel pagedisplaymode="Edit" runat="server"><script type="text/javascript">  document.getElementById("s4-ribbonrow").style.display = "block";</script></publishingwebcontrols:editmodepanel></publishingwebcontrols:authoringcontainer>


Publishing WebControls must be the namespace "Microsoft.SharePoint.Publishing.WebControls".


Further Links