Add ribbon programmatically

I present in this article how you can add a SharePoint ribbon programmatically: Web Part, User Control or an application page. To have finally the end result of FIG 1.
We will describe also how we can communicate between the ribbon controls and the Web Part controls.

ribbon

Fig 1

 

  1. Two buttons in the ribbon
  2. Two checkBox to enable/ disable the buttons.

We will create two elements:  application page (RibbonPage.aspx) in the mapped folder (layouts/Blog.Ribbon), and script file  “PageComponent.js” in the same folder.

RibbonPage.aspx.cs

private void CreateRibbon()
 {
uint lang = SPContext.Current.Web.Language;
#region MainTab
//custom action xml ribbon
string mainTab = @"<Tab Id='Ribbon.Test'
 Title='Test'
 Description='Tab Test'
 Sequence='500'>
<Scaling Id='Ribbon.Test.Scaling'>
<MaxSize Id='Ribbon.Test.group1.MaxSize'
 GroupId='Ribbon.Test.group1'
 Size='OneLargeTwoMedium'/>
 <Scale Id='Ribbon.Test.group1.Scaling'
 GroupId='Ribbon.Test.group1'
 Size='OneLargeTwoMedium' />
 </Scaling>
 <Groups Id='Ribbon.Test.groups'>
 <Group Id='Ribbon.Test.group1'
 Description='group 1 description'
 Title='group 1'
 Sequence='52'
 Template='Ribbon.Templates.groups'>
 <Controls Id='Ribbon.Test.group1.Controls'>
 <Button Id='Ribbon.Test.group1.cmd1'
 Description='Button 1'
 Command='cmd1'
 Image32by32='/_layouts/images/actionseditpage.png'
 LabelText='Button 1'
 TemplateAlias='btn1'/>
 <Button Id='Ribbon.Test.group1.cmd2'
 Description='Button 2'
 Command='cmd2'
 Image32by32='/_layouts/images/allcontent32.png'
 LabelText='Button 2'
 TemplateAlias='btn2'/>
</Controls>
 </Group>
</Groups>
 </Tab>";

 #endregion MainTab
#region contextualTabTemplate
string contextualTabTemplate = @"<GroupTemplate Id='Ribbon.Templates.groups'>
 <Layout Title='OneLargeTwoMedium' LayoutTitle='OneLargeTwoMedium'>
 <Section Alignment='Top' Type='OneRow'>
 <Row>
 <ControlRef DisplayMode='Large' TemplateAlias='btn1' />
 <ControlRef DisplayMode='Large' TemplateAlias='btn2' />

 </Row>
 </Section>
 </Layout>
 </GroupTemplate>";
#endregion contextualTabTemplate
#region Add Ribbon tab
// get the current ribbon page
 Microsoft.Web.CommandUI.Ribbon ribbon = SPRibbon.GetCurrent(this.Page);
//load the string in  XMLDocument
 XmlDocument ribbonExtensions = new XmlDocument();
//Add our Tab in the Ribbon 
 ribbonExtensions.LoadXml(mainTab);
 ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.Tabs._children");
ribbonExtensions.LoadXml(contextualTabTemplate);
 ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.Templates._children");
ribbon.Minimized = false;
 ribbon.CommandUIVisible = true;
//set id to the Tab
 const string initialTabId = "Ribbon.Test";
 if (!ribbon.IsTabAvailable(initialTabId))
 ribbon.MakeTabAvailable(initialTabId);
 ribbon.InitialTabId = initialTabId;
 #endregion
#region Events
var commands = new List<IRibbonCommand>();
// Load the commands
//define the action to each commanc
commands.Add(new SPRibbonCommand("cmd1", "Bt1Cmd()", "BT1Enabled()"));
 commands.Add(new SPRibbonCommand("cmd2", "Bt2Cmd()", "BT2Enabled()"));

 //Register initialize function par le script Manager
 SPRibbonScriptManager manager = new SPRibbonScriptManager();
 MethodInfo methodInfo = typeof(SPRibbonScriptManager).GetMethod("RegisterInitializeFunction", BindingFlags.Instance | BindingFlags.NonPublic);

 methodInfo.Invoke(manager,
 new object[] { Page,
 "InitPageComponent",
 "/_layouts/Blog.Ribbon/PageComponent.js", //path to the file compenent
 false,
 "RibbonCustomization.PageComponent.initialize()"
 }
 );
// Register ribbon scripts
 manager.RegisterGetCommandsFunction(Page, "getGlobalCommands", commands);
 manager.RegisterCommandEnabledFunction(Page, "commandEnabled", commands);
 manager.RegisterHandleCommandFunction(Page, "handleCommand", commands);
#endregion
}

file PageComponent.js


function ULS_SP() {
 if (ULS_SP.caller) {
 ULS_SP.caller.ULSTeamName = "Windows SharePoint Services 4";
 ULS_SP.caller.ULSFileName = "/_layouts/Blog.Ribbon/PageComponent.js";//accès vers le fichier
 }
}
Type.registerNamespace('RibbonCustomization');
// RibbonApp Page Component
RibbonCustomization.PageComponent = function () {
 ULS_SP();
 RibbonCustomization.PageComponent.initializeBase(this);
}
RibbonCustomization.PageComponent.initialize = function () {
 ULS_SP();
 ExecuteOrDelayUntilScriptLoaded(Function.createDelegate(null, RibbonCustomization.PageComponent.initializePageComponent), 'SP.Ribbon.js');
}
RibbonCustomization.PageComponent.initializePageComponent = function () {
 ULS_SP();
var ribbonPageManager = SP.Ribbon.PageManager.get_instance();
if (null !== ribbonPageManager) {
 ribbonPageManager.addPageComponent(RibbonCustomization.PageComponent.instance);
 ribbonPageManager.get_focusManager().requestFocusForComponent(RibbonCustomization.PageComponent.instance);
 }
}
RibbonCustomization.PageComponent.refreshRibbonStatus = function () {
 SP.Ribbon.PageManager.get_instance().get_commandDispatcher().executeCommand(Commands.CommandIds.ApplicationStateChanged, null);
}
RibbonCustomization.PageComponent.prototype =
{
 getFocusedCommands: function () {
 ULS_SP();
 return [];
 },
getGlobalCommands: function () {
 ULS_SP();
 return getGlobalCommands();
 },
isFocusable: function () {
 ULS_SP();
 return true;
 },
receiveFocus: function () {
 ULS_SP();
 return true;
 },
yieldFocus: function () {
 ULS_SP();
 return true;
 },
canHandleCommand: function (commandId) {
 ULS_SP();
 return commandEnabled(commandId);
 },
handleCommand: function (commandId, properties, sequence) {
 ULS_SP();
 return handleCommand(commandId, properties, sequence);
 }
}
RibbonCustomization.PageComponent.registerClass('RibbonCustomization.PageComponent', CUI.Page.PageComponent);
//you must set the same namespace 'RibbonCustomzation' defined in the SPRibbon script manager
RibbonCustomization.PageComponent.instance = new RibbonCustomization.PageComponent();

NotifyScriptLoadedAndExecuteWaitingJobs("/_layouts/Blog.Ribbon/PageComponent.js");
Code RibbonPage.aspx


<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<script type="text/javascript">

 var bt1EnabledValue = false;
 var bt2EnabledValue = false;

//function defined in TabRibbon (aspx.cs) you must keep the same name => enable / disable the button
 function BT1Enabled() {
return bt1EnabledValue;
 }

//click action
function Bt1Cmd() {
 alert('command 1');
 }
function BT2Enabled() {
return bt2EnabledValue;
 }
function Bt2Cmd() {
 alert('command 2');
 }
function changeBT1() {
 bt1EnabledValue = document.getElementById('Checkbox1').checked;

//refresh the ribbon to activate/ disactivate the buttons
 RefreshCommandUI();
 }
function changeBT2() {
 bt2EnabledValue = document.getElementById('Checkbox2').checked;
 RefreshCommandUI();
 }
</script>
</asp:Content>
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">

 Button 1 <input id="Checkbox1" type="checkbox" onchange="changeBT1()" /><br />
 Button 2 <input id="Checkbox2" type="checkbox" onchange="changeBT2()" />
</asp:Content>

		
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s