20 June 2010

how to get selected metadata for listitem using ECMAScript Client Object Model

SharepPoint 2010 ECMAScript Client Object Model : how to get selected metadata for listitem


Often, it is requried to retrieve information relevant to what we need, especially in the case of client side programming to reduce bandwidth and improve response time. Following are sample code to fetch only selective metadata for a listitem

var context = SP.ClientContext.get_current();
this.web = context.get_web();
var listId = SP.ListOperation.Selection.getSelectedList();
var list = this.web.get_lists().getById(listId);
var items = SP.ListOperation.Selection.getSelectedItems(context);
var itemId = items[0];
this.listItem = list.getItemById(itemId.id);

context.load(this.listItem, '_dlc_DocIdUrl', 'FileLeafRef');

var context = SP.ClientContext.get_current();
this.web = context.get_web();
this.listCollection = this.web.get_lists();

context.load(this.listCollection, 'Include(Title, Id)');

18 June 2010

Ribbon customization : Adding functionality to Ribbon Button

SharePoint 2010 Ribbon customization : Add functionality to the button


pre-requisite
Ribbon Basics

Writing the script in scriptblock
In the basics you saw the command action of the button firing a javascript that was inline. Supposingly if you wanted to call a block of JS code .. you cannot write it inline. For that you will have to use a ScriptBlock attribute of the CustomAction node like the following..


Writing the script in an external js file
The same javascript function can be written in an external *.js file. To achieve this, right-click on the project and Add the layouts mapped folder. In the subfolder under the layouts folder, add a js file.


Next, modify the elements.xml as below
done.


Enabling EcmaScript(JavaScript) IntelliSense in VS2010
To add intellisense to SP COM, add the following lines at the top of the js file..
/// <reference name="MicrosoftAjax.js" />
/// <reference path="file://C:/Program Files/Common Files/Microsoft Shared/Web Server Extensions/14/TEMPLATE/LAYOUTS/SP.core.debug.js" />
/// <reference path="file://C:/Program Files/Common Files/Microsoft Shared/Web Server Extensions/14/TEMPLATE/LAYOUTS/SP.debug.js" />
After adding the above lines, you will notice that the intellisense for the sharepoint client object model is active.

Using Client Object Model to dispplay SharePoint Status bar
Lets modify the HelloWorld function to show the message in the status bar of SharePoint. Below is the modified javascript..
/// <reference name="MicrosoftAjax.js" />
/// <reference path="file://C:/Program Files/Common Files/Microsoft Shared/Web Server Extensions/14/TEMPLATE/LAYOUTS/SP.core.debug.js" />
/// <reference path="file://C:/Program Files/Common Files/Microsoft Shared/Web Server Extensions/14/TEMPLATE/LAYOUTS/SP.debug.js" />

function HelloWorld() {
    this.statusID = SP.UI.Status.addStatus("Hello World", 
"A message from Mano <a href='#' onclick='javascript:closeStatus();return false;'>Close</a>.", true);
    SP.UI.Status.setStatusPriColor(this.statusID, "green");
}

function closeStatus() {
    SP.UI.Status.removeStatus(this.statusID);
}

Using Client Object Model to display current selected listItems and the list id
Now that we are able to access the SP namespace, we should be able to access the SharePoint entities like the site and the web for our use. In the code snippet we will be looking at how to get the selected items and the list Id from where these items are displayed.
function ShowListInformation() {
    // get all selected items
    var items = SP.ListOperation.Selection.getSelectedItems();
    var itemCount = CountDictionary(items);
    
    // get the current list
    var listID = SP.ListOperation.Selection.getSelectedList();

    // Remove all previous status
    SP.UI.Status.removeAllStatus(false);

    this.statusID = SP.UI.Status.addStatus("Selection Information", "Item Count : " 
+ itemCount.toString() + " List ID : " + listID.toString(), true);
    SP.UI.Status.setStatusPriColor(this.statusID, "blue");
}
Note: Make sure that you change the CommandAction attribute in the elements.xml with the new function
Why is the above code important ?
This code opens a whole new arena for us to play with , including to enable the button based on a condition, which we will see as we dwell deeper.

Tip: Make sure that the latest code is used to render the button
1. Make sure the app pool is recycled
2. Make sure that the browser cache is cleared

Ribbon customization : Basics

SharePoint 2010 Ribbon customization : Basics


This article is the first of a series of articles planned to address a real-world ribbon customization requirement. In this article, we will look at the basic architecture of the Ribbon in Sharepoint 2010.

To see ribbon’s internal you need to look into CMDUI.xml file, which you can find at location 14\template\global\xml\cmdui.xml.

But it is too confusing right now.. so the best way to look at it is look at the hierarcy of Ribbon. It starts with the base Ribbon implementation which is something like this

Ribbon > Tabs > Groups > Controls

A ribbon can have mutiple tabs, each tab mutiple groups and each group multiple controls. These controls can be a Button, CheckBox, Dropdown etc. The complete list is here ..

We will start with a hello world example and then build functionlity. We are not going to create a custom tab or group, but just add a button first to an existing location. It is better to understand this way.
Below is a snapshot of the xml that will add a new button..


Description of some of the elements in the screenshot above..
  1. this will determine where the new item to be created will reside.. whether is the ribbon or the ECB ( thats the contextual dropdown on the list item) or the Site Actions Menu or on the Backup & Restore page in central admin or whereever; this will decide where it is to be created. Here is a list of all possible locations . The ones we are interested are..
    • CommandUI.Ribbon.ListView
    • CommandUI.Ribbon.NewForm
    • CommandUI.Ribbon.EditForm
    • CommandUI.Ribbon.DisplayForm
    • CommandUI.Ribbon
    if you dont know where exactly you want it to be place except for the fact that it should be a ribbon.. then select 'CommandUI.Ribbon'
  2. This is the most important entry you will be making. This will determine where in the ribbon will it show up. As already mentioned, we just want to add a button. But as per the hierarchy, the button is a control and its parent is a group. So you will have to find the appropriate group name add your button.. but how ?

    As an example, we want the button available for a document, under the Manage group
    Here is a list of all possible locations you can choose from. It lists the groups and the controls that are in each group. You are interested in the group, so search for a group that matches close to the group name "Manage" and also should be present in a tab named "Document". Here you go the group name location "Ribbon.Documents.Manage"


    Now, since you got your groupname.. you have to specify that you are going to add a child control.. the syntax is "Controls._children". Hence your complete location is "Ribbon.Documents.Manage.Controls._children"

    The sequence also place a role where it is placed within the group.
  3. This is just a name to the new control, in this case a button. Typically I take the group name "Ribbon.Documents.Manage" and prefix this with the company name I am developing this for "ManoInc" and postfix with a unique button name "HelloWorld" .
  4. This is the command that is execute when the button is clicked. Again, you can be innovative in giving a name. Make sure you use the same name defining the command the "CommandUIHandler section
  5. This is the image that is rendered for the button that you have defined.


    Note that I have used the OOTB image in this case that is "formatmap32x32.png". This is a special image where it a collection of images in one image. when you use this image or any other image where there is collection of image in a single file, you have to use the Image32by32Top and the Left attributes to render properly.

    Basically, A negative integer representing an offset for the left edge of the image. Use this attribute when the Image32by32 attribute points to an image file that contains images for many icons.

    The value of the Image32by32Left attribute is used to set the CSS left attribute for the inline style of an HTML img tag. For example, setting the Image32by32Left attribute to "-160" and the Image32by32Top attribute to "-448" results in an inline style that is similar to the one in the following HTML markup:

    
    


    A simple way to calculate this co-ordinates is opening the image in MS Paint and place you cursor on the corner of the image you want. If you look at the bottom left of the MSPaint, you will see the co-ordinates e.g 259, 127px. This value is the left and the top co-ordinate of the image. All images in this file are 32x32px. if you caluclate a multiple of 32, the nearest value of 259 is 256 and the nearest to 127 is 128. Here you have it, the Image32by32Left = 256 and Image32by32Top = 128



Build your 'Hello World' Ribbon
Now that you know the basics, lets build the feature and deploy and test it..
1. Create a new sharepoint project in VS 2010. Make sure you specify the proper Url for this to deploy and make note of this url.

2. Add a new item of the type "Empty Element" to the project.

3. Add the following xml in the elements file
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction Id="DocFinalRibbon" Location="CommandUI.Ribbon">
    <CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition Location="Ribbon.Documents.Manage.Controls._children">
          <Button
            Id="ManoInc.Ribbon.Documents.Manage.HelloWorld"
            Sequence="40"
            Command="ManoInc.Ribbon.Documents.Manage.HelloWorld.cmdSayHelloWorld"
            Image16by16="/_layouts/1033/images/formatmap16x16.png" Image16by16Top="-144" Image16by16Left="0"
            Image32by32="/_layouts/1033/images/formatmap32x32.png" Image32by32Top="-128" Image32by32Left="-256"
            LabelText="Hello World"
            ToolTipTitle="Click button to prompt 'Hello World'"
            ToolTipDescription="Once you click this button, you will get a hello world dialog box "
            TemplateAlias="o1"/>
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <CommandUIHandler
          Command="ManoInc.Ribbon.Documents.Manage.HelloWorld.cmdSayHelloWorld"
          CommandAction="javascript:alert('Hi Mano');" />
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>
</Elements>
4. Hit F5 to deploy. Navigate to a document libary, click on the document tab and there you have it, your Ribbon button.

Ribbon customization : Hide Ribbon Programmatically

Ribbon customization : how to hide Ribbon programmatically

 

Note: To Add or Replace buttons programmatically refer to :
http://howtosharepoint.blogspot.com/2012/10/add-replace-or-remove-ribbon-buttons.html 

 

programmatically hide a Ribbon

public void HideRibbon()
{
  SPRibbon current = SPRibbon.GetCurrent(this.Page);

  if (current != null && !this.Page.Request.IsAuthenticated)
  {
    current.CommandUIVisible = false;
  }
}

Programmatically hide a Group

SPRibbon ribbon = SPRibbon.GetCurrent(this.Page);
if (ribbon != null)
{
ribbon.TrimById(“RibbonGroupId”);
}

 

programmatically hide a single ribbon button

public void HideRibbonItem()
{
 //if this is a System.Web.UI.Page
 SPRibbon ribbon = SPRibbon.GetCurrent(this);
 ribbon.TrimById("Ribbon.ListItem.New.NewFolder");
}

programmatically hide the status bar

public void HideStatusBar()
{
   string script = "document.onreadystatechange=fnRemoveAllStatus; function fnRemoveAllStatus(){removeAllStatus(true)};";
   this.Page.ClientScript.RegisterClientScriptBlock(typeof(HideTheRibbon), "statusBarRemover", script, true);
}

programmatically hide the SiteActions Menu

public void HideSiteActionsMenu()
{
  SiteActions actions = SiteActions.GetCurrent(this.Page);

  if (actions != null && !this.Page.Request.IsAuthenticated)
  {
       actions.Visible = false;
  }
}



Ref: http://www.elumenotion.com/Blog/Lists/Posts/Post.aspx?ID=106