SharePoint 2010 Custom Ribbon Button–Copy Task

by josh 19. November 2010 07:19

The SharePoint 2010 Ribbon is highly customizable. This paper will demonstrate how to add a button to the View Item form that will create a copy of the current item in the list. This example will use the Tasks list, but the steps are generally applicable for any list type. The general steps are as follows:

 

1. Create a new Visual Studio SharePoint 2010 project of the type Empty SharePoint Project

2. Enter the web site for testing and choose Deploy as a sandboxed solution. (Note: If deploying along with workflows or other customizations that required GAC-installed DLLs or files on the file system you will want to use a Farm Solution)

3. In Solution Explorer, right click the project name and click Add -> New Item.

4. Choose Empty Element from the item types and give it a name, such as CustomActions

5. At this point you will have an empty elements file

1_thumb[1]_thumb[3][3]


 

Add the following XML between the Elements tags:

 

<CustomAction   Id="Contoso.CustomActions.CopyTaskAction"
Location="CommandUI.Ribbon"
RegistrationId="107"
RegistrationType="List"
Sequence="1">
<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition Location="Ribbon.ListForm.Display.Manage.Controls._children">
<Button Id="Contoso.Ribbon.CopyTask"
Command="Contoso.Ribbon.CopyTask"
Sequence="5"
Image16by16="/_layouts/images/NoteBoard_16x16.png"
Image32by32="/_layouts/images/NoteBoard_32x32.png"
Description="Uses the notification area to display a message."
LabelText="Copy Task"
TemplateAlias="o1"/>
</CommandUIDefinition>
</CommandUIDefinitions>
</CommandUIExtension>
</CustomAction>


<CustomAction>

(http://msdn.microsoft.com/en-us/library/ms465980.aspx)

The CustomAction tag is used for deploying custom actions to the SharePoint UI. This includes many types of customizations, such as the Site Actions menu and the item context menus, as well as the ribbon.

The Location attribute specifies where the custom action will be created. For the Ribbon, the location should be CommandUI.Ribbon.

The RegistrationId and RegistrationType attributes specify what type of objects to attach the customization to as well as the specific IDs of the specified type. In this case, we want the customization to be attached to a list of type 107 (107 is the list template ID for the Tasks list).

Sequence is used throughout SharePoint declarative programming and refers to the order in which an element appears in the UI. Lower sequences appear first. SharePoint typically uses multiples of 10, but you will probably have to check the definitions yourself if you’re trying to place a customization in a very specific location, like between two other SharePoint elements.

<CommandUIDefinition>

(http://msdn.microsoft.com/en-us/library/ff458373.aspx)

This is used for adding specific elements to the SharePoint UI.

The Location attribute of the CommandUIDefinition specifies exactly where in the Ribbon the customization should be located. In this case we want the button to appear in the Manage group of the list item Display form. Specifying Controls._children tells SharePoint to add the customization to the controls collection of the specified group.

<Button>

(http://msdn.microsoft.com/en-us/library/ff458366.aspx)

As might be expected, the Button tag represents a button in the Ribbon.

The Command attribute specifies the command to be executed when the button is clicked. This will be used in the CommandUIHandler to execute some JavaScript code.

The Image16by16 and Image32by32 attributes allow specify the large and small icons to be used with the button. The 16 and 32 represent pixel sizes for the respective images.

The LabelText attribute is the text that will be displayed on the button in the Ribbon.

The TemplateAlias attribute specifies a display template for the button. These are defined by SharePoint and can be found in the SharePoint root directory at TEMPLATE\GLOBAL\XML\CMDUI.XML. In this case, setting the attribute to “o1” will display a large icon similar to the “Edit Item” button, and “o2” will display a small icon similar to the “Delete Item” button.

 

6. Deploy the solution from Visual Studio. At this point you will see the button in the View form but it will be disabled because there are no handlers defined for it yet.

2_thumb_thumb_thumb[3]


 

Now copy the following XML between the closing CommandUIDefinitions and the closing CommandUIExtension tags:

 

<CommandUIHandlers>
<CommandUIHandler
Command="Contoso.Ribbon.CopyTask"
CommandAction
="javascript:
if(confirm('Copy Task, are you sure?')){
var ctx;
var taskList;
var web;
var taskItem;

//Get client context
ctx = new SP.ClientContext.get_current();
//Get reference to current web
web = ctx.get_web();
//Load web into context
ctx.load(web);

//Get reference to current list
taskList = web.get_lists().getById('{ListId}');
//Load list into context
ctx.load(taskList);

//Get reference to current list item
taskItem = taskList.getItemById('{ItemId}');
//Load listitem into context, including specified columns.
ctx.load(taskItem);

//Perform batched queries on server
ctx.executeQueryAsync(onQuerySucceeded, onQueryFailed);
}




function onQuerySucceeded(sender, args) {

//Create ListItemCreationInformation for use when creating new task item
var taskItemInfo = new SP.ListItemCreationInformation();

//Create new request item
newTask = taskList.addItem(taskItemInfo);

//Set properties on new request from current request
newTask.set_item('Title','COPY OF TASK {ItemId}');
newTask.set_item('Body',taskItem.get_item('Body'));
newTask.set_item('AssignedTo',taskItem.get_item('AssignedTo'));
newTask.set_item('DueDate',taskItem.get_item('DueDate'));
newTask.set_item('Priority',taskItem.get_item('Priority'));
newTask.set_item('StartDate',taskItem.get_item('StartDate'));
newTask.set_item('TaskGroup',taskItem.get_item('TaskGroup'));

//Update database with changes
newTask.update();

//Load new request into context
ctx.load(newTask);

//Perform batched operations on server
ctx.executeQueryAsync(requestAddSucceeded, requestAddFailed);

}



function requestAddSucceeded(sender, args) {
//Notify user that copy succeeded
SP.UI.Notify.addNotification('Task copied successfully');
}

function requestAddFailed(sender, args)
{
//Notify user that copy failed
SP.UI.Notify.addNotification('Task failed to copy!');
}

function onQueryFailed(sender, args)
{
//Notify user that an error occurred
SP.UI.Notify.addNotification('Error copying task!');
}

"
/>
</CommandUIHandlers>


<CommandUIHandler>

(http://msdn.microsoft.com/en-us/library/ff458385.aspx)

This tag defines a handler for a custom action command. In this case we want to define a handler for the Contoso.Ribbon.CopyTask command, which we specify in the Command attribute.

The CommandAction attribute is where we define the handler for the command. Here we add the javascript to actually perform the copy using the SharePoint ECMAscript Client Object Model. I won’t go into detail here about programming against the Client OM, but there are many good articles, blog posts, etc. out there. Some good ones I’ve found are *here*…

In a nutshell, the javascript code gets a reference to the task using the {ListId} and {ItemId} tokens, which are replaced at runtime with the IDs of the list and item from the current context (e.g. the item being displayed in the View form). Then a new task is created in the same list and the properties are populated from the current task. As far as I can tell, this is the best way to perform a copy on a list item. There is no CopyTo method or anything like that, at least that I could find.

 

7. With the CommandUIHandlers code added, redeploy the solution. You will now be able to click the Copy Task button. 

3_thumb_thumb_thumb[3]


and when you click the button you will be prompted to confirm your desire to copy the task… 


4_thumb_thumb_thumb[3]


and when you click OK you will be notified, using the new notification framework, that the task copied successfully.


5_thumb_thumb_thumb[3]

 

8. Refreshing the list view, you will see the original task and the new copy.


6_thumb_thumb_thumb[3]

 

Here’s a few helpful blog posts related to Ribbon Customizations and the ECMAscript Client OM:

  • Chris O’Brien’s series on Ribbon Customizations
  • Channel 9 Developer Training videos on the Client OM

Presenting 2 Sessions at SharePoint Saturday Huntsville

by josh 13. April 2010 08:14

I'll be presenting 2 sessions at the upcoming SharePoint Saturday event in Huntsville, AL on May 1, 2010.

Building a  Cloneable, Scripted SharePoint 2010 Development Environment

SharePoint 2010 Workflow – Business Analyst to Developer

 

 This is actually my first SharePoint Saturday to attend or present, so I'm excited. For those in Huntsville or the surrounding areas, you can register here.

 

Creating a cloneable SharePoint 2010 Development Environment with PowerShell, Windows Sysprep, and SQL Server 2008 R2 Sysprep – PART 1

by josh 26. March 2010 02:53

In the previous post, I outlined the steps involved in creating a cloneable image that can be quickly spun up into a working SharePoint 2010 development machine. In this post, I want to visit Steps 1-5 in more detail.

 

  1. Install a virtual machine with Windows Server 2008 R2, PowerShell 2.0 and all other desired client software (Visual Studio, Office, SharePoint Designer, etc…)
  2. Install SQL Server 2008 R2 as a Prepared Image
  3. Install SharePoint 2010 Prerequisites (http://technet.microsoft.com/en-us/library/cc262485(office.14).aspx) either manually or using the Prerequisites Installer tool
  4. Install SharePoint 2010 bits, but DO NOT run configuration wizard
  5. Run Sysprep.exe to prepare server

 

Step 1 – Install OS and Client software

I won’t go into a whole lot of detail on this step because it should be pretty straightforward. For my SharePoint 2010 development machine I run Windows Server 2008 R2 and the following client software:

  • Visual Studio 2010
  • SQL Management Studio
  • Office 2010 (including Visio Premium for workflow visualization)
  • SharePoint Designer 2010
  • Other useful tools (Reflector, U2U CAML Query tool, CodeRush/Refactor Pro, …)

Step 2 – Install SQL Server 2008 R2 as a Prepared Image

**This is a feature of R2. SQL Server 2008 (pre-R2) does not have the Sysprep functionality.

Performing these steps will install the SQL Server 2008 R2 bits and prepare the server to be configured at a later time.

  1. Run the SQL Server 2008 R2 setup executable.
  2. On the Installation Center dialog, choose Advanced from the menu on the left. 
    sql installation center
  3. Click the Image preparation of a stand-alone instance of SQL Server link. 
    sql installation center - prepare image
  4. When the System Configuration Checker completes, click OK.
  5. Accept the license terms and click OK.
  6. On the Setup Support Files screen, click Install.
  7. When the setup files are installed, click Next and choose the features to be installed. 
    sql install feature sel
    **Only server features are available as part of the image preparation. Client features, such as Management Studio, can be installed normally before running Sysprep on the machine.
  8. On the Instance Configuration screen, enter an Instance ID for the instance being prepared. This will be required when completing the image after cloning. 
    sql installation center - instance config
  9. On the Disk Space Requirements screen, review requirements and click Next.
  10. On the Prepare Image Rules screen, verify that there are no errors or warnings and click Next.
  11. On the Ready to Prepare Image screen, review settings and click Prepare.
  12. On the Complete screen, click Close.

Step 3 – Install SharePoint 2010 Prerequisites

SharePoint 2010 includes a new Prerequisites installer that will automatically download and install the necessary prerequisites. Of course, you must be connected to the internet for the prerequisites to be downloaded. You can alternatively download the prerequisites manually and install them one-by-one. (http://technet.microsoft.com/en-us/library/cc262485(office.14).aspx)

  1. Open the SharePoint 2010 installation media and run PrerequisiteInstaller.exe.
  2. Review the prerequisites that will be installed and click Next
    spprereq1
  3. Accept the license terms and click Next.
  4. When the installation completes, click Finish.
  5. Restart the VM.

Step 4 – Install SharePoint Server 2010 Binaries

  1. Open the SharePoint 2010 installation media and run Setup.exe.
  2. Enter the license key and click Continue.
  3. Choose Server Farm install.
  4. On the Server Type screen, choose Complete and click Install Now.
  5. When installation is compl ete, on the Run Configuration Wizard screen, clear the Run the SharePoint Products Configuration Wizard now checkbox and then click Close
    sharepoint install 1

Step 5 – Run Sysprep to Prepare Machine for Cloning

  1. Navigate to C:\Windows\System32 and run Sysprep.exe
  2. In the System Preparation Tool dialog, in the System Cleanup Action section, choose Enter System Out-of-Box Experience(OOBE) and select the Generalize checkbox.
  3. In the Shutdown Options section, choose Shutdown and click OK
    sysprep dialog
  4. Sysprep will configure the machine and then automatically shut down.

The base virtual machine image is now ready to be cloned. I’ll detail the process of cloning the VM and scripting the configuration of SQL Server and SharePoint in the next post…

Creating a cloneable SharePoint 2010 Development Environment with PowerShell, Windows Sysprep, and SQL Server 2008 R2 Sysprep – Overview

by josh 26. March 2010 02:50

Goal: To be able to execute a single command and have a fresh, sysprepped, SharePoint 2010 development environment ready to go within minutes.

 

**Note I’m using VMware Workstation, but you should be able to use other virtualization software as long as it supports 64-bit operating systems)

 

With most SharePoint development being done in VMs, it is useful to have a set of sysprepped base VMs that can be cloned at any time to create a new environment, whether it be for a new project, to test some tool or software, or whatever. Sysprep is a great tool for virtual domains because it will generate a new security ID (SID) for every server created from the sysprepped image to prevent conflicts between servers on the same domain.

 

Most of the software needed for development can be installed prior to running sysprep on the virtual machine,but SQL Server and SharePoint (at least the configuration of SharePoint) are generally exceptions. These apps typically must be installed post-sysprep in order for them to operate correctly, and this is an involved and tedious process. Fortunately with SQL Server 2008 R2, we now have SQL Server Sysprep, which will allow SQL Server to be installed and imaged, but not configured until a new VM is created from the base image. Woohoo!

 

So, the general steps are as follows:

  1. Install a virtual machine with Windows Server 2008 R2, PowerShell 2.0 and all other desired client software (Visual Studio, Office, SharePoint Designer, etc…)
  2. Install SQL Server 2008 R2 as a Prepared Image
  3. Install SharePoint 2010 Prerequisites (http://technet.microsoft.com/en-us/library/cc262485(office.14).aspx) either manually or using the Prerequisites Installer tool
  4. Install SharePoint 2010 bits, but DO NOT run configuration wizard
  5. Run Sysprep.exe to prepare server
  6. Clone server
  7. Boot clone and execute PowerShell script to perform the following actions:
    • Complete configuration of sysprepped SQL Server 2008 R2 database server
    • Configure SharePoint 2010 farm

 

The PowerShell script can perform as much (or as little) configuration of the SharePoint environment as you wish. There are a whole slew of new cmdlets (Gary LaPointe lists all 535 of them here) that come with SharePoint 2010, so most actions are as easy as finding the appropriate cmdlet to run.

 

I’m going to split the detailed steps into two separate posts to make them a little more manageable. The first will cover steps 1-5 above, and the second will cover the rest of the steps.

Lightning Conductor Web Part Sample XSL

by josh 15. March 2010 10:33
We've been looking for a good web part to use for rolling up list data from various site collections within a SharePoint web application.  After trying a couple of different ones, including the Bamboo List Rollup Web Part and the Lightning Conductor Web Part, I have chosen the Lightning Conductor web part for our list roll-up needs.  It works very similar to the Content Query Web Part that comes with MOSS Enterprise, but will roll-up data across multiple site collections.  It also has some added features like the ability to specify which columns to display in the gridview, and you can turn on paging and specify how many items to display on each page all from the toolpane window.  Very nice!
 
The purpose of this post was actually not an overview of the LCWP - there's already a good one here.  One of the options available with the web part is the ability to specify your own XSL file for formatting.  My current project involves a highly customized branding of the portal, so we don't want to have the plain old SharePoint blue web part stuck on this branded page.  We wanted to use our own custom color scheme, images, formatting, etc.  So I started trying to come up with an XSL file to do this, and then remembered I know nothing about XSL.  So after a quick intro to XSL, I opened up one of the sample XSL files and began to poke around. 
 
Without really knowing what the input xml looked like I wasn't sure of the xpath to use to access the list items being rolled up.  Well finally, after searching through the sample XSL file I figured it out. To loop through all rows returned, you can use the following XSL:
 
image
 
And then to access the value of a specific column you can use
 
 
image
 
where InternalColumnName is the Internal Name of the column you're referencing.
 
Hopefully this will save someone a little bit of time.  Thanks to the folks at Lightning Tools for a great web part!!
 
jgm

SQL Server 2008 R2 Adds Sysprep functionality

by josh 12. March 2010 10:13

Just stumbled across this blog entry talking about the new Sysprep functionality in SQL Server 2008 R2.  I have to say I am thrilled to find out that you will now be able to use SQL Server sysprep along with Windows Server sysprep to create sysprepped machines with SQL Server installed! I've been working on a scripted install of a SharePoint 2010 development machine for a client and this just made my job A LOT easier. Now i can abandon the SQL Server 2008 + SP1 + CU2 slipstream install that I've been putting together and just script the SharePoint portion of the install. if only there was a SharePoint sysprep...