Archive | Sharepoint 2013 RSS for this section

Sharepoint 2013 – Configure Search with Power Shell

The following script will configure the Search Service and Components on a SharePoint 2013 Server:

$AppSearch = "SERVERNAME"

$SearchAppPoolName = "SharePoint_SearchApp"

$SearchAppPoolAccountName = "domain\username"

$SearchServiceName = "SharePoint_Search_Service"

$SearchServiceProxyName = "SharePoint_Search_Proxy"

$DatabaseName = "SharePoint_Search_AdminDB"

#Create a Search Service Application Pool

$spAppPool = New-SPServiceApplicationPool -Name $SearchAppPoolName -Account $SearchAppPoolAccountName -Verbose

#Start Search Service Instance on all Application Servers

Start-SPEnterpriseSearchServiceInstance $AppSearch -ErrorAction SilentlyContinue

Start-SPEnterpriseSearchQueryAndSiteSettingsServiceInstance $AppSearch  -ErrorAction SilentlyContinue

#Create Search Service Application

$ServiceApplication = New-SPEnterpriseSearchServiceApplication -Partitioned -Name $SearchServiceName -ApplicationPool $spAppPool.Name -DatabaseName $DatabaseName

#Create Search Service Proxy

New-SPEnterpriseSearchServiceApplicationProxy -Partitioned -Name $SearchServiceProxyName -SearchApplication $ServiceApplication

$clone = $ServiceApplication.ActiveTopology.Clone()

$AppSSI = Get-SPEnterpriseSearchServiceInstance -Identity $AppSearch

#Configure Search Components

New-SPEnterpriseSearchAdminComponent –SearchTopology $clone -SearchServiceInstance $AppSSI

New-SPEnterpriseSearchContentProcessingComponent –SearchTopology $clone -SearchServiceInstance $AppSSI

New-SPEnterpriseSearchAnalyticsProcessingComponent –SearchTopology $clone -SearchServiceInstance $AppSSI

New-SPEnterpriseSearchCrawlComponent –SearchTopology $clone -SearchServiceInstance $AppSSI

New-SPEnterpriseSearchQueryProcessingComponent –SearchTopology $clone -SearchServiceInstance $AppSSI

$PrimaryIndexLocation = "C:\Data"

$ReplicaIndexLocation = "D:\Data"

#We need two index partitions and replicas for each partition. Follow the sequence.

New-SPEnterpriseSearchIndexComponent –SearchTopology $clone -SearchServiceInstance $AppSSI -RootDirectory $PrimaryIndexLocation -IndexPartition 0

New-SPEnterpriseSearchIndexComponent –SearchTopology $clone -SearchServiceInstance $AppSSI -RootDirectory $ReplicaIndexLocation -IndexPartition 1

$clone.Activate()

Sharepoint 2013 App with Custom Lists

This post is about how to create a SharePoint 2013 App in Visual Studio 2012 with a Custom List.
To start that, you need to create an “App for SharePoint 2013” project:
CL7

Then, add a new item to your project and select “List”:

CL1

You’ll go through a wizzard where you can select if you want to create a list instance, based on an existing template, where you can’t change that template.

Or, if you want to create a list, and a template, that you can change, based on an existing template. 

Let’s start with a list based on a template that you can’t change:

CL2

Create a list named “CustomList” based on a Document Library template:

CL3

Now, let’s choose the other option and create CustomList2:

CL4

In this case, you’ll have another step, where you can define your document’s template:

CL5

And another step, where you can add more columns, in my case, I add an Attachments column:

CL6

Now, I edited my default.aspx file, to include links to my new lists:

<ahref=”/SampleApp06/Lists/CustomList”>CustomList</a>

 <ahref=”/SampleApp06/Lists/CustomList2″>CustomList2</a>

Finally, deployed my solution and see my new app with these two Custom Lists.

Sharepoint 2013 Create a Minimal Master Page

To create a minimal Master Page in SharePoint 2013, you can use the Design Manager.

MP1

Choose the option “4 – Edit Master Pages” and then “Create a minimal master page”.

MP2

Give a name to your page and create it. Next, go to your master pages gallery, and you’ll see your new master page.

You can now, download a copy from your master page, and create a Visual Studio 2012, SharePoint 2013 empty project to deploy your new master page.

You need to add a new module to your project, add your master page file, and configure your elements.xml file:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="SampleMinimalMaster" Url="_catalogs/masterpage">
    <File Path="SampleMinimalMaster\SM12.master" IgnoreIfAlreadyExists="TRUE" Type="GhostableInLibrary" Url="SM12.master" />
  </Module>
 </Elements>

I made some changes to the original master page, to use the PublishingWebControls:AuthoringContainer control:

<%-- SPG:

This HTML file has been associated with a SharePoint Master Page (.master file) carrying the same name.  While the files remain associated, you will not be allowed to edit the .master file, and any rename, move, or deletion operations will be reciprocated.

To build the master page directly from this HTML file, simply edit the page as you normally would.  Use the Snippet Generator at http://win-f9pitqqtmf3/_layouts/15/ComponentHome.aspx?Url=http%3A%2F%2Fwin%2Df9pitqqtmf3%2F%5Fcatalogs%2Fmasterpage%2FMinimalTest%2Emaster to create and customize useful SharePoint entities, then copy and paste them as HTML snippets into your HTML code.   All updates to this file will automatically sync to the associated Master Page.

 --%>
<%@Master language="C#"%>
<%@Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>
<%@Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>
<%@Register TagPrefix="wssucmui" TagName="MUISelector" Src="~/_controltemplates/15/MUISelector.ascx"%>
<%@Register TagPrefix="wssucw" TagName="Welcome" Src="~/_controltemplates/15/Welcome.ascx"%>
<%@Register TagPrefix="PublishingRibbon" TagName="PublishingRibbon" Src="~/_controltemplates/15/Ribbon.ascx"%>
<%@ Register Tagprefix="PublishingWebControls" Namespace="Microsoft.SharePoint.Publishing.WebControls" Assembly="Microsoft.SharePoint.Publishing, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<!DOCTYPE html >
<SharePoint:SPHtmlTag dir="<%$Resources:wss,multipages_direction_dir_value%>" ID="SPHtmlTag" runat="server" >
    <head id="Head1" runat="server">
        <meta http-equiv="X-UA-Compatible" content="IE=10" />
        
        
        
        
        <meta name="GENERATOR" content="Microsoft SharePoint" />
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta http-equiv="Expires" content="0" />
        <SharePoint:RobotsMetaTag ID="RobotsMetaTag1" runat="server" />
        <SharePoint:PageTitle ID="PageTitle1" runat="server">
            <asp:ContentPlaceHolder id="PlaceHolderPageTitle" runat="server">
            <SharePoint:ProjectProperty ID="ProjectProperty1" Property="Title" runat="server" />
            </asp:ContentPlaceHolder>
        </SharePoint:PageTitle>
        <SharePoint:StartScript ID="StartScript1" runat="server" />
        
        <SharePoint:CssLink ID="CssLink1" runat="server" Version="15">
            
        </SharePoint:CssLink>

        <SharePoint:ScriptLink ID="ScriptLink1" language="javascript" name="core.js" OnDemand="true" runat="server" Localizable="false" />
        <PublishingWebControls:AuthoringContainer runat="server" id="AuthoringContainer1" DisplayAudience="AuthorsOnly">
            <SharePoint:ScriptLink ID="ScriptLink2" language="javascript" name="menu.js" OnDemand="true" runat="server" Localizable="false" />
            <SharePoint:ScriptLink ID="ScriptLink3" language="javascript" name="callout.js" OnDemand="true" runat="server" Localizable="false" />
            <SharePoint:ScriptLink ID="ScriptLink4" language="javascript" name="sharing.js" OnDemand="true" runat="server" Localizable="false" />
            <SharePoint:ScriptLink ID="ScriptLink5" language="javascript" name="suitelinks.js" OnDemand="true" runat="server" Localizable="false" />
        </PublishingWebControls:AuthoringContainer>



        <SharePoint:CacheManifestLink ID="CacheManifestLink1" runat="server" />
        <SharePoint:PageRenderMode ID="PageRenderMode1" runat="server" RenderModeType="Standard" />
        <SharePoint:CustomJSUrl ID="CustomJSUrl1" runat="server" />
        <SharePoint:SoapDiscoveryLink ID="SoapDiscoveryLink1" runat="server">
            
        </SharePoint:SoapDiscoveryLink>
        <SharePoint:AjaxDelta id="DeltaPlaceHolderAdditionalPageHead" Container="false" runat="server">
            <asp:ContentPlaceHolder id="PlaceHolderAdditionalPageHead" runat="server">
            </asp:ContentPlaceHolder>
            <SharePoint:DelegateControl ID="DelegateControl1" runat="server" ControlId="AdditionalPageHead" AllowMultipleControls="true">
            </SharePoint:DelegateControl>
            <asp:ContentPlaceHolder id="PlaceHolderBodyAreaClass" runat="server">
            </asp:ContentPlaceHolder>
        </SharePoint:AjaxDelta>
        <SharePoint:CssRegistration ID="CssRegistration1" Name="Themable/corev15.css" runat="server" />
        <SharePoint:AjaxDelta id="DeltaSPWebPartManager" runat="server">
        <WebPartPages:SPWebPartManager ID="SPWebPartManager1" runat="server" />
        </SharePoint:AjaxDelta>
        
        
    </head>
    <body onhashchange="if (typeof(_spBodyOnHashChange) != 'undefined') _spBodyOnHashChange();"><SharePoint:SPClientIDGenerator ID="SPClientIDGenerator1" runat="server" ServerControlID="DeltaPlaceHolderMain;DeltaPlaceHolderPageTitleInTitleArea;DeltaPlaceHolderUtilityContent" /><SharePoint:ImageLink ID="ImageLink1" runat="server" /><SharePoint:SharePointForm ID="SharePointForm1" onsubmit="if (typeof(_spFormOnSubmitWrapper) != 'undefined') {return _spFormOnSubmitWrapper();} else {return true;}" runat="server"><asp:ScriptManager id="ScriptManager" runat="server" EnablePageMethods="false" EnablePartialRendering="true" EnableScriptGlobalization="false" EnableScriptLocalization="true" />
        <div id="ms-designer-ribbon">
            
            <div id="TurnOnAccessibility" style="display:none" class="s4-notdlg noindex">
                <a id="linkTurnOnAcc" href="#" class="ms-accessible ms-acc-button" onclick="SetIsAccessibilityFeatureEnabled(true);UpdateAccessibilityUI();document.getElementById('linkTurnOffAcc').focus();return false;">
                    <SharePoint:EncodedLiteral ID="EncodedLiteral1" runat="server" text="&lt;%$Resources:wss,master_turnonaccessibility%&gt;" EncodeMethod="HtmlEncode">
                    </SharePoint:EncodedLiteral>
                </a>
            </div>
            <div id="TurnOffAccessibility" style="display:none" class="s4-notdlg noindex">
                <a id="linkTurnOffAcc" href="#" class="ms-accessible ms-acc-button" onclick="SetIsAccessibilityFeatureEnabled(false);UpdateAccessibilityUI();document.getElementById('linkTurnOnAcc').focus();return false;">
                    <SharePoint:EncodedLiteral ID="EncodedLiteral2" runat="server" text="&lt;%$Resources:wss,master_turnoffaccessibility%&gt;" EncodeMethod="HtmlEncode">
                    </SharePoint:EncodedLiteral>
                </a>
            </div>
            <PublishingRibbon:PublishingRibbon runat="server" />
            
        </div>
        <SharePoint:SPSecurityTrimmedControl ID="SPSecurityTrimmedControl1" runat="server" AuthenticationRestrictions="AnonymousUsersOnly">
            <wssucw:Welcome runat="server" EnableViewState="false" />
        </SharePoint:SPSecurityTrimmedControl>
        <div id="s4-workspace">
            <div id="s4-bodyContainer">
                <div>
                   
                    <SharePoint:AjaxDelta id="DeltaPlaceHolderMain" IsMainContent="true" runat="server">
                        <asp:ContentPlaceHolder ID="PlaceHolderMain" runat="server">
                            <div class="DefaultContentBlock" style="border:medium black solid; background:yellow; color:black;">
                                This area will be filled in by content you create in your page layouts.
                            
                            </div>
                        </asp:ContentPlaceHolder>
                    </SharePoint:AjaxDelta>
                    
                </div>
            </div>
        </div>
    <SharePoint:AjaxDelta id="DeltaFormDigest" BlockElement="true" runat="server"><asp:ContentPlaceHolder id="PlaceHolderFormDigest" runat="server"><SharePoint:formdigest ID="Formdigest1" runat="server" /></asp:ContentPlaceHolder></SharePoint:AjaxDelta></SharePoint:SharePointForm><SharePoint:AjaxDelta id="DeltaPlaceHolderUtilityContent" runat="server"><asp:ContentPlaceHolder id="PlaceHolderUtilityContent" runat="server" /></SharePoint:AjaxDelta><asp:ContentPlaceHolder id="PlaceHolderTitleAreaClass" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderTitleBreadcrumb" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderGlobalNavigationSiteMap" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderGlobalNavigation" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderSearchArea" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderLeftNavBar" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderHorizontalNav" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderTopNavBar" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderLeftNavBarDataSource" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderCalendarNavigator" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderLeftActions" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderLeftNavBarTop" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderSiteName" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderPageTitleInTitleArea" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderPageDescription" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderPageImage" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderTitleLeftBorder" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderMiniConsole" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderTitleRightMargin" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderTitleAreaSeparator" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderNavSpacer" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderLeftNavBarBorder" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderBodyLeftBorder" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderBodyRightMargin" Visible="False" runat="server" /><asp:ContentPlaceHolder id="WSSDesignConsole" Visible="False" runat="server" /><asp:ContentPlaceHolder id="SPNavigation" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderQuickLaunchTop" Visible="False" runat="server" /><asp:ContentPlaceHolder id="PlaceHolderQuickLaunchBottom" Visible="False" runat="server" /></body>
</SharePoint:SPHtmlTag>

Sharepoint 2013 App Custom Action

This post is about how to create a Custom Action using a SharePoint 2013 app project.

In this sample I’ll use a Menu action, that will be available to list items in Page Library based lists.

This menu action will update a field in the target list item.

Start creating a SharePoint 2013 app Visual Studio 2013 project, SharePoint Hosted.

Then add a new item of type “Menu Item Custom Action”:

AppRA1

Select “List Template” and “Page Library”:

AppRA2

Select your action name and target page:

AppRA3

Your Menu Action elements.xml file should be like:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction Id="56b2571e-1ae7-48e8-be14-2652fc86bc79.Action1"
                RegistrationType="List"
                RegistrationId="850"
                Location="EditControlBlock"
                Sequence="10001"
                Title="Action1">
    <!--
    Update the Url below to the page you want the custom action to use.
    Start the URL with the token ~remoteAppUrl if the page is in the
    associated web project, use ~appWebUrl if page is in the app project.
    -->
    <UrlAction Url="~appWebUrl/Pages/Default.aspx?{StandardTokens}&amp;SPListItemId={ItemId}&amp;SPListId={ListId}" />
  </CustomAction>
</Elements>

In app Menu Action or Ribbon Action you can’t add javascript code to your Command Action (like in this post), so you need to define the  behaviour of your action in the navigation page.
My Default.aspx file includes the App.js file, I edited this file and add the following code:

 'use strict';

var list;
 var parentWeb;
 var currentItem;

$(document).ready(function () {

var hostweburl = GetSiteUrl();

var clientContext = new SP.ClientContext.get_current();
 var parentCtx = new SP.AppContextSite(clientContext, hostweburl)
 var parentWeb = parentCtx.get_web();
 clientContext.load(parentWeb);
 list = parentWeb.get_lists().getById(GetListId());
 clientContext.load(list);
 currentItem = list.getItemById(GetItemId());
 clientContext.load(currentItem);
 if (currentItem != null) {
 currentItem.set_item('Category', 'Cat1');
 currentItem.update();
 }
 clientContext.executeQueryAsync(onListLoadSucceeded,
 onRequestFailed);
 });

function onListLoadSucceeded() {
 $('#message').text('Done');
 }

function onRequestFailed(sender, args) {
 alert('Error:' + args.get_message());
 }

function getParameterByName(name) {
 var name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
 var regexS = "[\\?&]" + name + "=([^&#]*)";
 var regex = new RegExp(regexS);
 var results = regex.exec(window.location.href);
 if (results == null)
 {
 return "";
 }
 else
 {
 return decodeURIComponent(results[1].replace(/\ /g, " "));
 }
 }

function GetListId() {
 return getParameterByName("SPListId");
 }

function GetSiteUrl() {
 return getParameterByName("SPHostUrl");
 }

function GetItemId() {
 return getParameterByName("SPListItemId");
 }
 

After deployed my solution, I can see and execute my Custom Action:

AppRA4

Sharepoint 2013 Open a Modal Dialog from a Custom Ribbon Action

This post is a sequence from this one (https://raquelalineblog.wordpress.com/2013/05/28/sharepoint-2013-custom-ribbon-action-to-update-a-list-item-field/).

In this post I’ll show how to call a modal dialog and get a value from that to update a list item field value.

The first thing was to create a mapped folder in my SharePoint 2013 project, to Layouts folder.

Then I add a new application page, where I have a text area to get data from user, an Ok button and a Cancel button.
My application page is this:

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GetCategory.aspx.cs" Inherits="SharePointCustomMenuAction.Layouts.SharePointCustomMenuAction.MoveDocs" DynamicMasterPageFile="~masterurl/default.master" %>

<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">

</asp:Content>

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">

     <Sharepoint:ScriptLink ID="ScriptLink1" Name="sp.ui.dialog.js" LoadAfterUI="true" Localizable="false" runat="server"></Sharepoint:ScriptLink>
     <script type="text/javascript" language="javascript">

            function onCancel(sender, args) {
                SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, '');
            }

            function onOk(sender, args) {
                SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, document.getElementById('txtCategory').value);
            }
    </script>
    <form id="aspnetForm" action="">

        <p>
            <label id="label1">Enter Category Value</label>
        </p>
        <p>
            <textarea id="txtCategory" rows="1" cols="10"></textarea>

        </p>
        <p>
            <button  id="Ok" value="Ok" onclick="onOk();">Ok</button>&nbsp;&nbsp;<button id="Cancel" value="Cancel" onclick="onCancel();">Cancel</button>
        </p>
    </form>
</asp:Content>

<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
Get Category
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
Get Category
</asp:Content>

I changed my Custom Action’s elements.xml file to call the modal dialog and get the result and value.

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/"> 
    <CustomAction
    Id="Ribbon.Library.Actions.AddAButton"
    Location="CommandUI.Ribbon"
    RegistrationId="101"
    RegistrationType="List"
    Title="MoveDocs Ribbon Button">
    <CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition
          Location="Ribbon.Library.Share.Controls._children">
          <Button Id="Ribbon.Library.Share.NewRibbonButton"
            Command="MoveDocsButtonCommand"
            LabelText="UpdateCategory"
            TemplateAlias="o2" />
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <CommandUIHandler
          Command="MoveDocsButtonCommand"
          CommandAction="javascript:
            var context;
            var notifyId;
            var currentItem;
        
          function onQuerySucceededUpdate (sender, args) {
              alert('item updated');
          }    

          function onQueryFailedUpdate(sender, args) {
            alert('Error occured' + args.get_message());
          }  
          
          function UpdateCategory(val)
          {
             context = SP.ClientContext.get_current();
             var web = context.get_web();
             context.load(web, 'Title');  
             var currentlibid = SP.ListOperation.Selection.getSelectedList();
             var currentLib = web.get_lists().getById(currentlibid);
             var selectedItems = SP.ListOperation.Selection.getSelectedItems(context);
             for(var i in selectedItems)
              {
                currentItem = currentLib.getItemById(selectedItems[i].id);
                context.load(currentItem);
                if(currentItem != null) {
                  currentItem.set_item('Category', val);
                  currentItem.update();
                }
                context.executeQueryAsync(Function.createDelegate(this, onQuerySucceededUpdate), Function.createDelegate(this, onQueryFailedUpdate));
              }//End for
          }//End UpdateCategory


          var dlg=SP.UI.ModalDialog.showModalDialog({url: '{SiteUrl}/_Layouts/SharePointCustomMenuAction/GetCategory.aspx', dialogReturnValueCallback:function(res, val) {       
                if(res=='1')
                  {
                    UpdateCategory(val);
                  }
                else
                {
                  alert('Operação Cancelada');
                }
               }
              });
          
          
           
"/>
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>
  
  <Module Name="CustomAction">
  </Module>
</Elements>

Sharepoint 2013 Custom Ribbon Action To Update a List Item Field

In this post I’ll show how to develop a Custom Ribbon Action, that iterates through selected document library (with a custom column named Category) items and updates  a field value (category).

I want to do another post to  get the value from a modal dialog, but for now, the updated value will be hard coded.

I started creating a SharePoint 2013 empty project in Visual Studio 2012 (selected the deployment as a farm solution, but could also be sandbox).

Add a new module to my project called “CustomAction”, and add the following code, to elements.xml file:

 

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/"> 
    <CustomAction
    Id="Ribbon.Library.Actions.AddAButton"
    Location="CommandUI.Ribbon"
    RegistrationId="101"
    RegistrationType="List"
    Title="MoveDocs Ribbon Button">
    <CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition
          Location="Ribbon.Library.Share.Controls._children">
          <Button Id="Ribbon.Library.Share.NewRibbonButton"
            Command="MoveDocsButtonCommand"
            LabelText="UpdateCategory"
            TemplateAlias="o2" />
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <CommandUIHandler
          Command="MoveDocsButtonCommand"
          CommandAction="javascript:
            var context;
            var currentItem ;
          
        
          function onQuerySucceededUpdate (sender, args) {
              alert('item updated');
          }    

          function onQueryFailedUpdate(sender, args) {
            alert('Error occured' + args.get_message());
          }  
          
          function UpdateCategory(val)
          {
            context = SP.ClientContext.get_current();
            var web = context.get_web();
             context.load(web);
             var currentlibid = SP.ListOperation.Selection.getSelectedList();
             var currentLib = web.get_lists().getById(currentlibid);
             var selectedItems = SP.ListOperation.Selection.getSelectedItems(context);
             for(var i in selectedItems)
              {
                currentItem = currentLib.getItemById(selectedItems[i].id);
                context.load(currentItem);
                if(currentItem != null) {
                  currentItem.set_item('Category', val);
                  currentItem.update();
                }
                context.executeQueryAsync(Function.createDelegate(this, onQuerySucceededUpdate), Function.createDelegate(this, onQueryFailedUpdate));
              }// End for
          
          }//End UpdateCategory

          
          UpdateCategory('Cat1');
           
"/>
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>
  
  <Module Name="CustomAction">
  </Module>
</Elements>

Sharepoint 2013 Custom Workflow Activity SingleTask with Custom Content Type

In this post I’ll talk about how to develop a custom Workflow Activity that creates a SingleTask, with a custom Content Type,  collect data from user and update the target list item with that data.

This post is a sequence from (https://raquelalineblog.wordpress.com/2013/05/11/sharepoint-2013-workflow-custom-declarative-activity/), where I explain in more detail the steps to create a custom Workflow Activity.

I started creating a SharePoint 2013 Empty Project, deployed as a sandbox solution.

I added a new item of type “Content Type”:

CT1

Then I followed the wizard to configure my new Content Type, selected to inherit from item:

CT2

Defined my new content type columns:

CT3

And the basic settings:

CT4

Then I added a new item to my project, of type “Workflow Custom Activity”, and added the actions to have the logic I needed:

CT5

The first actions in my Activity are to get the username of the current’s item author. I used that username in my SingleTask action, in the “Assigned to” field.

CT51

After that I started configuring my Single Task action.

Since I wanted to use a custom Content Type, I started to get my content’s type id. I got that from my content’s type elements.xml file:

CT6

Then I configured my Single Task as in the next picture:

CT7

In the next actions I did the logic to get the value of the Category field from my Workfflow Single Task, and add that field’s  value to the field Category in my target workflow item.

The fisrt step was to get the TaskListId:

CT8

Next I got the Task Item from the Task List, using the taskId, returned in my Single Task action:

CT81

Then I got the value of Category field from the TaskItem:

CT82

And finally I updated my Workflow target list item with that value:

CT83

I created a SharePoint Designer Workflow that calls my new Activity:

CT9

Run my Workflow, and saw my task with my new Content Type (I had to configure my Task List to support this Content Type, in List Settings. This is possible to be done automatically by code):

CT10

Completed my Workflow:

CT11

And saw my Item with the value collected from my task:

CT12