Skip Ribbon Commands
Skip to main content

SharePoint Developer Reference - Blog

:

Home
December 04
Slides and demos of my session at SPSUK2014

Hello everybody, thanks again for attending my session about “Real life experiences with the SharePoint Workflow” at the SPSUK2014.

Here you can find the slides (in PDF format) of my session.

I decided to share the demos with the whole SharePoint Community through the great Office365 PnP project.

Some of the demos I showed you are already available in the Office 365 PnP project, in the master branch, while the others are already available in the dev branch, and will be published shortly in the master branch.

Enjoy!

October 30
SP Friday Budapest 2014 – Publishing SharePoint Apps on Microsoft Azure - Demos and Slides

Here I am with slides and demos of my talk at the latest SP Friday Budapest. I really enjoyed being part of the event, and I want to thank Agnes for inviting me.

About the demo, let me briefly explain the main steps to publish a SharePoint App on Microsoft Azure.

In case of need, let’s create a new Office 365 Developer Subscription, going to the following URL.

Start Visual Studio 2013 and create a SharePoint App project.

  1. Target SharePoint Online in Office 365 or SharePoint Server 2013 on-premises
  2. Choose your preferred development model. My one is ASP.NET MVC.
  3. If you are targeting SharePoint Online, choose Azure Access Control Services (ACS) for apps Authorization. If you are targeting SharePoint 2013 on-premises, choose the Server to Server (High Trust) authorization model.

Now, develop your app. I would suggest you to replace the out of the box file in Views/Shared/_Layout.cshtml with this new one, which includes all the stuff needed to support the Office 365 and the SharePoint Chrome control. The new file mainly declares the chrome control placeholder and includes the spcontext scripts needed to support SharePoint and the SharePoint App model. In order to properly support the SharePoint Chrome control you should also replace the out of the box Scripts/spcontext.js file in SharePoint app web site with the following one. It will include a bunch of JavaScript loaded from the host web site and declared in the SP.UI.Controls.js file. You should also add the app icon AppIcon.png to the target SharePoint App web site project.

SpApp-Project-Outline

Implement your business logic and debug your solution. Once you’re ready to test the SharePoint App, just press F5 and play with it. The local IIS Express engine will provide you all the capabilities to run the app locally.

Whenever you will be ready to publish your app, simply right click on the SharePoint App project and choose “Publish” from the context menu.

Publish-Screen

Visual Studio 2013 will ask you to create or select a publishing profile.

Publish-Your-App

To target Microsoft Azure and an Azure Web Site, you will simply need to create an Azure Web Site using the Microsoft Azure management portal. Then, download the publishing profile file and choose it from the following Visual Studio wizard.

Publishing-Profile-Step1

Just after that, you will have to provide the Client ID and the Client Secret for your SharePoint App. You can get these values using the Reseller Dashboard provided by Microsoft, if you want to publish your app on the Office Store. If you are targeting the Corporate App Catalog (on Office 365 or on-premises), which is more often the case, you can simply open the App Catalog site collection and navigate to the /_layouts/15/AppRegNew.aspx page of that site.

AppRegNewPage

There you will be able to register a new Client Id and the Client Secret for your app, from an OAuth 2.0 perspective. Record the generated values, because after creating them you will not be able to access the Client Secret anymore. Write those values into the “Set app identity” step of the “Publish apps” wizard.

Publishing-Profile-Step2

Now, within the “Publish your app” page select the “Deploy your web project” button. Visual Studio 2013 will publish your SharePoint App Web Site on the target Azure Web Site. Visual Studio will also change the web.config file of the target Web Site in order to include the Client ID and Client Secret you just registered.

After that, you can click the “Package app” button in the “Publish your app” page and create the .app file that describes your app. Upload the output .app file onto the App Catalog, under the “Apps for SharePoint” library, or onto the Reseller Dashboard if you are targeting the Office Store.

Now, you are ready to add your app on a target Site Collection. Enjoy!

October 30
SharePoint Days Slovenia 2014 – Slides

Here I am with the slides of my sessions at SharePoint Days Slovenia 2014.

I hope you enjoyed my sessions and let’s see in the future. Feel free to contact me in case of need at paolo(at)pialorsi.com or via Twitter (@PaoloPia).

October 30
SPC Adriatics 2014 – Demos and Slides

Sorry for being late, but I had some personal troubles that didn’t allowed me to follow up earlier. Nevertheless, in this post I want to provide slides and demos of my sessions at SPC Adriatics 2014.

  • D1S3DEV - Lifecycle Management with SharePoint Apps and Solutions: slides.
  • D2S4DEV - Best practices with development of enterprise-scale SharePoint solutions: demos and slides.

As usual it was a great event, and I really want to thank Toni, Adis, and Nenad for such a well managed event. Well done guys!

Feel free to contact me - paolo(at)pialorsi.com or @PaoloPia - in case of need.

September 23
Workflow Tasks with Predecessors

During the last weeks I had to work around a workflow project with some specific requirements. In particular, one of the requirements was to support workflow tasks with predecessors. As you probably know, tasks in SharePoint are based on the well-known Task content type (ID: 0x0108), and “Workflow Task (SharePoint 2013)” content type inherits from it (ID: 0x0108003365C4474CAE8C42BCE396314E88E51F). Thus, because the Task content type has a Predecessors field of type LookupMulti in its set of fields, it should be easy to satisfy the customer’s requirement.

However, you know … we’re in the SharePoint world and … what’s looks easy is not always that easy Sorriso

SharePoint Designer 2013 Native Actions

In fact, if you take a look at the “Assign Task” action in SharePoint Designer 2013 - as you can see from the following figures – it is missing the option to configure predecessor.

spd2013-task-form-01    spd2013-task-form-02

And it is the same for the “Start a task process” action.

Visual Studio 2013 Native Activities

Thus, I moved to Visual Studio 2013 … just to check how the corresponding activities (SingleTask and CompositeTask) behave in the low level workflow designer. However, even in Visual Studio 2013 there is the same lack of capability (see next figures), of course!

vs2013-task-form-01  vs2013-task-form-02

One more time, the same happens with the CompositeTask activity, as well.

Never Give Up!

Trying to figure out a possible solution, I created a bunch of tasks with relationships in a classic tasks list. Then, using the powerful REST API of SharePoint 2013 I queried for a task item, which I manually created with some predecessors. In the following figure you can see the OData/XML content of such a task.

ie-task-content-01

Let’s concentrate on the PredecessorsId element:

ie-task-content-02

In JSON (Accept: application/json;odata=nometadata) the same content looks like the following one:

json-task-01

Again, the PredecessorsId property, under the cover in JSON source text, will look like this:

{ “PredecessorsId”: [14,15] }

The Developer Solution

Thus, here is the solution to my requirement! I can simply leverage a bunch of REST API calls to update a task created either in SharePoint Designer 2013 or in Visual Studio 2013, in order to set the content of the PredecessorsId field.

I used Visual Studio 2013, just because in my case that was the tool used to create the whole SharePoint App solution. However, you can do almost the same within SharePoint Designer 2013, as well.


To accomplish my goal, I created a custom workflow activity in order to reuse this capability whenever I will need it. Here you can see the outline of the custom activity.

custom-activity-01

The custom activity accepts a couple of input arguments:

custom-activity-arguments-01

Those are the target WorkflowTaskId (IN: Int32), and the list of predecessors provided as an input argument of type ICollection<Int32>, in order to support multiple predecessors.

First of all, I retrieve the URL of the target web site, which in my case is the app web site. Then, I retrieve the FormDigest value, using another custom activity of mines, in order to being able to safely submit the task item update request via REST.

The custom activity to retrieve the FormDigest is really trivial. Here it is:

custom-activity-02

I simply query the _api/ContextInfo URL using a POST method, and providing an HTTP Header of type Accept with a value of “application/json;odata=nometadata”. Then, I retrieve the FormDigestValue property from the JSON object returned by the HTTP REST call.

Just after retrieving the FormDigest value I can create a JSON request for updating the target task item. Using a ForEach<Int32> activity over the ICollection<Int32> input argument, I collect all the IDs of the predecessors into a String variable, which at the end will assume a value like this:

{ “PredecessorsId”: [14,15] }

This JSON content will be the content of the REST API request to update the target task item.

Then, I build a DynamicValue variable, which will hold the HTTP Request Headers, which are required to submit the update request. Here you can see the configured headers:

rest-request-headers-to-update

As you can see, I configure the following headers:

  • [Accept: application/json;odata=nometadata] in order to instruct SharePoint to answer using JSON light, without metadata
  • [X-RequestDigest: formDigest] to provide the FormDigest value
  • [X-HTTP-Method: MERGE] to instruct SharePoint to merge our properties (the PredecessorsId field in our case) with the other fields of the target item
  • [IF-MATCH: *] to ignore concurrency update conflicts, if any
  • [content-type: application/json;odata=nometadata] to inform SharePoint that the request content will be in JSON light format
  • [content-length: lenghtOfTheJSONRequest] to properly complete the HTTP request

Lastly, I simply call an HttpSend activity providing all these information and configuring a POST method with the URL of the target task item, which will be something like this:

https://tenant-appID.sharepoint.com/sites/HostSite/AppName/_api/web/lists/getByTitle('WorkflowTaskList')/Items(16)

And you’re done … the task will be configured to support predecessors!

I hope you will find this post useful. Please, feel free to contact me via Twitter (@PaoloPia) or email (paolo at pialorsi.com) in case of any further need.

August 16
How to create a “special” custom Home Page for SharePoint Online in Microsoft Office 365

Introduction

In this post, I would like to illustrate a real scenario that I think is really interesting and useful. During the last months we had to satisfy a customer’s requirement about designing the home page of a corporate Intranet network based on Microsoft Office 365 and SharePoint Online, together with the deployment of an hybrid scenario that leverages a bunch of VMs (about 25) in Windows Azure IaaS for hosting an “on-premises” (even if on Microsoft Azure) SharePoint 2013 farm and an ADFS environment, as well. Thus, the customer has some workloads on-premises, based on the VMs in Microsoft Azure, and some other workloads in Office 365. All the users are managed through Federated Identities, using ADFS 3.0 and Windows Server 2012 R2.

We decided to provision the SharePoint 2013 farm on Windows Azure IaaS because we needed to provide some services that aren’t available (yet) in Office 365. They were mainly Business Intelligence services and workloads, as well as some kind of direct integrations with a completely on-premises deployment of Microsoft Dynamics Ax, which is installed in the headquarters of the customer. Thus, we also have a site-to-site VPN between the headquarters and Microsoft Azure.

The customer is quite big – at least from my country perspective – because there are about 1.000 people all over the country. We provisioned multiple site collections to hold contents for the various departments and units. For instance we have a site collection for the Insurance unit, another for the IT department, another for the Accounting unit, and so on. Moreover, there are some other cross-company contents that we placed in the root site collection.

The customer’s requirement was to have a unique home page (with responsive design) for the corporate Intranet, through which accessing and sharing all the latest information and documents available all over the distributed network (remember: something is completely on-premises in the headquarters, something is in IaaS on Azure, and something else is in Microsoft Office 365). Lastly, there a bunch of SharePoint Apps (provider hosted apps on Azure PaaS) to enrich the Intranet network.

Overview of the Solution

We defined a solution that I think is really interesting:

  • We designed a “nice” (or supposed to be :-) …) and user friendly graphical solutions based on HTML5/CSS3/jQuery
  • We placed the page in SharePoint Online, as the default home page of the root site collection
  • We used the Enterprise Search Engine of SharePoint to index all the contents, leveraging an hybrid topology
  • We provided a unique and aggregated view of new items, documents, and tasks of every department/unit to which the current user has access to
    • Thanks to the security trimming features of the Enterprise Search Engine of SharePoint, every single user has a “personal” view of the contents (i.e. everyone sees only what is in target for him, of course!)
  • We provided an easy to use and fast to access entry point for any other search
  • We allowed the company to provide quick and fast company news in the home page

Here, in the following figure, you can see a sample of the final result (the contents are in Italian language and obfuscated, for privacy reasons):

Intranet-FFF-Home-Obfuscated

As you can see, the home page takes inspiration from the well-known tiles of Windows 8, and provides animated contents to provide dynamic contents and live feedbacks to the end users, leveraging the metaphor of the live tiles.

You can find further “non-technical” details about the solution in the case study published by Microsoft Italy.

The Solution from a Technical Perspective

I know, I know :-) … you’re used to read technical contents on this blog … and here we are. Thus, how we made it, from a technical perspective?

We simply made an HTML5/CSS3/jQuery page that leverages the powerful REST API of SharePoint 2013/Online and we used some AJAX requests to query the Search Engine.

First of all, we provisioned a support list (custom list with a custom content type) to hold the list of all the available contents (site collections, SharePoint apps, search targets, etc.), which can be part of the home page. Then we used that list to feed a custom JavaScript/jQuery function that queries the sites for new contents (documents or tasks).

Here you can see a sample of the code we used to search for all the documents changed within the last 3 days (which is a suitable timeframe to consider a content “new” or “refreshed”):

$.ajax({
    url: searchDocumentsUrl,
    type: "GET",
    headers: {"accept": "application/json;odata=verbose"},
    success: function (data) {
        var c = data["d"]["query"]
            ["PrimaryQueryResult"]["RelevantResults"]["RowCount"];
        $("#" + targetItem.attr("data-area") + "-docs-count")
            .text(c.toString());                   

        totalItemsCount += c;
        $("#" + targetItem.attr("data-area") + "-total-count")
            .text(totalItemsCount.toString());

        targetItem.show();
    },
    error: function (err) {
        console.log("Error query search for: " + targetUrl);
    }
});

The key part of the AJAX request is the URL (the variable highlighted in red color) that we used to query the search engine. Here you can see a sample URL (simplified to make it more readable):

https://{tenant}.sharepoint.com/sites/{sitecollection}/_api/search/query?
querytext='IsDocument:true Path:https://{tenant}.sharepoint.com/sites/{sitecollection}/'&
sortlist='LastModifiedTime:descending'
&selectproperties='Title,Url,ContentTypeId,IsDocument'
&refinementfilters='write:range(2014-08-13T15:07:48.0000000Z,max,from="gt",to="le")'

The base URL is the one of the search namespace provided by the REST API (the one highlighted in red color), followed by the invocation of the query method. The querystring parameters make the real work. Thus, here is a in depth explanation of the querystring parameters:

  • querytext: defines that we are looking for documents (IsDocument:true) and that we are targeting a specific site collection (via the Path constraint)
  • sortlist: it is just for the sake of completeness, it simply orders the results by modified date time descending
  • selectproperties: declares to retrieve a “brief” list of items, including only Title, Url, ContentTypeId and the IsDocument properties/fields
  • refinementfilters: this is the most interesting part of the query. Here we define to retrieve all those items that have a modified datetime (write) greater than (gt) the point in time in which we are executing the query, and lower or equal to (le) max (i.e. infinite) – credits to my friend Mikael Svenson for explaining that on his blog.

And the result will be something like this (in JSON format):

image

Where the “d/query/PrimaryQueryResults/RelevantResults/RowCount” path will contain the number of items found.

And now you can also use the JSON light format, announced and released a few days ago, getting the following result (using “odata=nometadata”):

image

In case you want to search for new or updated tasks, the query will be almost the same as before, but we will use a slightly different query rule in the querytext parameter. Here is an example:

https://{tenant}.sharepoint.com/sites/{sitecollection}/_api/search/query?
querytext='ContentTypeId:0x0108* Path:https://{tenant}.sharepoint.com/sites/{sitecollection}/'&
sortlist='LastModifiedTime:descending'
&selectproperties='Title,Url,ContentTypeId'
&refinementfilters='write:range(2014-08-13T15:07:48.0000000Z,max,from="gt",to="le")'

The search filter will be based on the content-type ID (see the syntax highlighted in red color). We query for every item with a content-type ID inherited from 0x0108, which means every kind of SharePoint task (including workflow tasks).

And the game is done! Feel free to reuse any part of these ideas, queries, and code. And feel free to give any feedback through email (paolo at pialorsi.com), twitter, or whatever else.

Now I’ll go back to my summer vacation … see you in September.

July 12
Updating declarative custom actions for SharePoint 2013 Workflows

Let’s say you have created a declarative custom action for a SharePoint 2013 workflow, like I have illustrated in this post. Now, let’s say you want to update it, changing the .actions4 file or updating its inner workings in the .xaml file.

When you upload the .WSP sandboxed solution, which includes the custom action, and then you activate the feature that deploys the custom action, under the cover SharePoint 2103 creates a folder (with the name of the custom action) under the Workflows folder in your site, as you can see in the following screenshot of Microsoft SharePoint Designer 2013.

image

Each of the folders, which are inside of the Workflows folder, contains the .actions4 and .xaml files of a declarative custom action, as you can see in the following screenshot.

image

This behavior happens because the feature element file, which is created by the Visual Studio action template, internally declares exactly to do that. Here you can see a sample Elements.xml file that is related to a sample declarative custom action.

image

Well now, imagine that you want to update the custom action, as I stated at the very beginning of this post. You can simply update it in Visual Studio, rebuild the .WSP package, release an updated version of the solution and upgrade or deactivate/re-activate the feature. However, it could happen that the action doesn’t upgrade. Do you guess why?

It doesn’t update the action because the Elements.xml file syntax provisions the files just once, and then doesn’t update the .actions4 and .xaml files in case of any future updates. In order to change this behavior, you can simply change the Elements.xml file adding the ReplaceContent attribute with a value of TRUE to each of the File elements. Here you can see the updated Elements.xml file.

image

That’s all! This way, whenever you will update the feature that provisions the declarative custom action, the files will be overwritten and the action will be updated!

February 13
Publishing SharePoint apps that leverage SharePoint Workflow Services

Just a quick reference for those of you, who are developing SharePoint apps that leverage the SharePoint Workflow Services. If you are using Microsoft Visual Studio 2013, you can see the app publishing process has been improved and simplified. You simply right-click on the SharePoint app project, you select “Publish …”, and you are prompted with a nice and friendly page with all the buttons for managing your publishing phase.

image

Moreover, the publishing process is available whether you are publishing an app on the Office Store, or whether you are publishing the app on-premises on a Corporate Catalog.

image

Well, first of all by using this nice and friendly UI you can configure a publishing profile, providing information about the Client ID and Client Secret to use for publishing the app on Office 365 using OAuth, or you can provide the Client ID, the .PFX certificate file and password, and the Issuer ID if you plan to leverage a Server to Server deployment for on-premises farms.

You can deploy the web app directly to the target server (web deploy, web deploy package, FTP, file system).

image

Then, you can create the .APP package file for publishing the app to the target store (Office Store or Corporate Catalog) by clicking the “Package the app” button.

image

Notice that the “Package the app” wizard accepts only apps published via HTTPS. Thus, you will have to provide an SSL secured URL for your app, which is good and safe … but not always possible, for instance if you are packaging a test app and you do not want to use an SSL certificate. Keep in mind that in a production environment you should always use SSL!

Well, now if your app is leveraging one or more of the services available in SharePoint, those services will be listed in the AppManifest.xml file as Prerequisites. However, if you are using a workflow inside the app … the SharePoint Workflow Services requirement will make your app deployment to fail!

In fact, the AppManifest.xml generated by Visual Studio 2013 will reference a Capability with ID:

CDD8F991-B459-4512-8048-03D5A03FF27E

Here is a sample AppManifest.xml file generated by Visual Studio 2013:

<?xml version="1.0" encoding="utf-8"?>
<App xmlns="
http://schemas.microsoft.com/sharepoint/2012/app/manifest" Name="NameOfYourApp" ProductID="{777fd9aa-cf34-4de3-bc86-e5d0c00b58bc}" Version="1.0.0.0" SharePointMinVersion="15.0.0.0">
  <Properties>
    <Title>Title of your App</Title>
    <StartPage>
https://host.domani.tld/?{StandardTokens}</StartPage>
    <SupportedLocales>
      <SupportedLocale CultureName="en-US" />
    </SupportedLocales>
  </Properties>
  <AppPrincipal>
    <RemoteWebApplication ClientId="35f7958e-a9b3-44c0-86b1-cf363c716f90" />
  </AppPrincipal>
  <AppPermissionRequests>
    <AppPermissionRequest Scope="
http://sharepoint/content/sitecollection/web" Right="FullControl" />
  </AppPermissionRequests>
  <AppPrerequisites>
    <AppPrerequisite Type="Capability" ID="CDD8F991-B459-4512-8048-03D5A03FF27E" />
  </AppPrerequisites>
</App>

This is also documented here. However, as clearly stated by a comment in that article, the ID for the SharePoint Workflow Services is wrong. Meanwhile, the right ID is:

B1DDD88F-6ADD-4700-B5CD-18E451635E24

If you try to publish the app, let’s say in the Corporate Catalog, with the wrong ID in the AppManifest.xml file … the result will be something like that:

image

Moreover, by clicking on the “Find out why” link, you will see something like that:

image

A friendly message stating “Sorry, this app is not supported on your server.” will inform you that your target farm does not satisfy the declared requirements of your app. This could happen also if you reference a real requirement with a valid Capability ID, which is not available in the target farm. But in the case of SharePoint Workflow Services, the issue is related to the wrong Capability ID referenced in the AppManifest.xml file.

Well, to fix and solve the issue you simply need to edit the .APP file content, which under the cover is a .ZIP file. You can open it with WinZIP, WinRAR, or something like that. Then, you have to provide the proper Capability ID, which is B1DDD88F-6ADD-4700-B5CD-18E451635E24 and you are done! Upload the new and updated .APP file and enjoy your app!

I hope this will help.

January 25
Understanding the REST API of SharePoint 2013–Slide and Demo (#SPSSTHLM17)

Here you can find the slides and demos of my session “Uderstanding the REST API of SharePoint 2013” provided at the SharePoint Saturday Stockholm on 25th January 2014.

I hope you enjoyed the session, and I’m looking forward to meet you again at the upcoming events, where I will have speeches.

SPSSthlm_header31[1]

Thanks to Matthias, Erwin, and Hannah for this really great and well managed event!

November 22
How to create a Workflow Custom Action for SharePoint Designer 2013 using Visual Studio 2013

Quite often customers ask me about how to create custom Workflow Custom Actions, for SharePoint Designer 2013, using Microsoft Visual Studio. Because on the network there are a lot of contents, some of them not very complete or clear … let me try to clarify this topic, or add some more entropy :-) …

Thus, I will show you how to create a Custom Action to Move a file from one document library to another. Because the move action requires write permissions on the source and target folders, and because you are not guaranteed that the user running the workflow has appropriate permissions … I will show you also how to create this Action elevating your identity and acting as the app only. Where the app will be the workflow app. For further details about this topic, you can also read the following document on MSDN: Create a workflow with elevated permissions by using the SharePoint 2013 Workflow platform.

Pre-requirements

First of all, you should have to properly configure your environment. Thus, because the current Custom Action needs to use app permissions, you have to configure the target web site to support App Step sequences. In order to do that, open your site and navigate to the Site Settings page. There, select the “Manage Site Features” option in the “Site Actions” group of actions. In the resulting page, at the very end, you should see a feature called “Workflows can use app permission”. Activate that feature.

image

Then, you will have to configure the permissions for the workflow app. Go back to the Site Settings page and click on the “Site app permissions” link in the “Users and Permissions” group of actions. If you have already created and published at least one workflow with the new SharePoint 2013 workflow engine, you should find an app named “Workflow” (or whatever you say “Workflow” in your language, if you are using a localized UI for SharePoint 2013). If you do not find an app with name “Workflow”, open Microsoft SharePoint Designer 2013 and create a fake workflow, publish it and go back to the “Site app permissions” page. Here you can see how your page should look like.

image

Copy the ID of the “Workflow” app, which is the value between the last | and @ in the App Identifier field. In my sample image it is “f189f858-5565-4221-8d33-0099df9306fd”.

Change the web browser URL in order to navigate to the page /_layouts/15/appinv.aspx, which is not available in the “Site Settings” page. You will be prompted with the following form.

image

Fill the “App Id” field with the ID you have just copied, click the “Lookup” and compile the “Permission Request XML” with an XML permission request like the following one:

<AppPermissionRequests>
<AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web"

    Right="FullControl" />
</AppPermissionRequests>

Or something like that, in order to properly configure the permissions you want to assign to the “Workflow” app. For further details about the available permissions for apps, you can read my book :-) or you can read the following article on MSDN: App permissions in SharePoint 2013.

As soon as you will click on the “Create” button, you will be prompted to trust the “Workflow” app. Click the “Trust it” button, if you want to trust it and assign the declared permissions to it.

Implementing the Move File Custom Action

Now you are ready to implement the custom action. This action will use the REST APIs provided by SharePoint 2013 in order to retrieve a reference to a file in a library, and will invoke the MoveTo method of the File class (Microsoft.SharePoint.Client) in order to move that file somewhere else.

Start Microsoft Visual Studio 2013, choose “New Project” and select a “SharePoint 2013 – Empty Project” template.

WF-Custom-Action-01

Select to create a Sandboxed Solution, in order to being able to leverage the custom action both on-premises and on Office 365.

WF-Custom-Action-02

Right click on the project item in the Solution Explorer and add a new item. Choose the “Workflow Custom Activity” template. Name the new item “MoveFileActivity”.

WF-Custom-Action-03

That action will add a new feature and a new feature element made of three files:

  • Elements.xml: it is the feature element used to provision the new activity.
  • MoveFileActivity.actions4: it is an XML file that will be used to describe the custom action. We will talk about it later in this article.
  • MoveFileActivity.xaml: it is the real markup-based (XAML) custom activity.

Keep in mind that now, with SharePoint 2013 and the new workflow engine based on Workflow Manager, any custom activity suitable for SharePoint 2013 on-premises and online has to be markup based. You can also implement code-based activities, but those will be suitable for on-premises farms only.

On the designer area of Visual Studio you will find an activity designer with a Sequence activity ready to go. In the lower side of the designer, click on the Arguments tab in order to add some input arguments that will be used by SharePoint Designer 2013 to provide a reference to the file to move, and to the target library.

image

The arguments will be:

  • ItemGuid – In – System.Guid
  • ListId – In – System.Guid
  • TargetFolder – In – System.String

Then, you can open the toolbox and drag’n’drop on the designer surface the following activities:

  • WebUri (available under the “SP – Current Context” group of activities)
  • LookupSPListItemId (available under the “SP – List” group of activities)
  • AppOnlySequence (available under the “SP – Utilities” group of activities)

The WebUri activity will be used to retrieve the URL of the current web site. Define a workflow variable with name currentWebUri and store the result of the WebUri activity into it.

WF-Custom-Action-04

Now you can retrieve the ID of the source item using the LookupSPListItemId activity. Provide the ListID and the ItemGuid values as filters for selecting the ID. Save the result in a variable named ItemId, of type System.Int32, like shown in the following screenshot.

WF-Custom-Action-05

Now you are ready to compose the URL of the REST request for moving the file. As already stated, the REST API that we will use is the MoveTo method of the File class of the client object model. The URL of that method, from a REST perspective, will look like the following one:

{currentWebUri}/_api/web/lists/GetById(guid'{ListId}')/Items({sourceItemID})/File/MoveTo(newUrl='{targetFolder}',flags='1')

Where the tokens wrapped in { } will be the variables and arguments just defined, and the last parameter named flags with a value of ‘1’ means: overwrite any already existing file on the destination. You can find the full documentation of the MoveTo method here.

Thus, you are ready to prepare the REST request. Within the AppOnlySequence drag’n’drop a new Sequence activity, and inside it define the following activities:

  • Assign (available under the “Primitives” group of activities)
  • BuildDynamicValue (available under the “DynamicValue” group of activities)
  • HttpSend (available under the “Messaging” group of activities)

The Assign activity will be used to compose the target URL of the REST API to invoke. Define a String variable named restAPIUri and assign it the following value:

String.Format("{0}_api/web/lists/GetById(guid'{1}')/Items({2})/File/MoveTo(newUrl='{3}',flags='1')", currentWebUri, ListId, sourceItemID, TargetFolder)

Now define a variable named restHttpHeaders of type DynamicValue and assign it an item with path “Accept” and value “application/json;odata=verbose”, using the BuildDynamicValue activity. That header will instruct the REST API to respond using JSON (JavaScript Object Notation).

image

Now you are ready to configure the HttpSend activity like the following.

WF-Custom-Action-06

The HTTP Method property will have a value of “POST”, the Uri will be the restAPIUri variable, and the RequestHeaders will be the restHttpHeaders variable. In some cases, depending on the REST API you are invoking, you should have to provide some other HTTP Headers like X-RequestDigest, IF-MATCH, etc. It is out of scope of this article to cover this topic, too. However, consider that to retrieve such information you can still use one or more HttpSend activity instances. For example, to retrieve a value for the X-RequestDigest you can invoke the /_api/ContextInfo URI via POST and parse the JSON response.

Publishing the Custom Action

So far, you are almost ready. You simply need to publish the Custom Action. In order to accomplish this task you have to define the .actions4 file mentioned above. This file is mainly an XML based definition of the action, of its input and output arguments, and of the bindings between the UI of SharePoint Designer 2013 and the arguments expected by the action. Unfortunately there are not so much documents online available about the schema of .actions4 files. However, you can read the following article: WorkflowActions4 schema reference.

Nevertheless, the best thing to do - in order to understand the schema and to learn the supported values for elements and attributes of .actions4 files - is to inspect the out of the box available .actions4 files deployed by the standard setup of SharePoint 2013. The .actions4 files are deployed in the SharePoint15_Root\TEMPLATE\{Language LCID}\Workflow folder. There you can open already existing files using Notepad or any other text editor … and do inspection.

Here you can see the .actions4 file for the current custom action.

<Action Name="MoveFileActivity"
ClassName="DevLeap.SP2013.MoveFileAction.MoveFileActivity"
    Category="Files" AppliesTo="all">
    <RuleDesigner Sentence="Move item from %1 to %2">
        <FieldBind Field="ListId,ItemGuid" Text="this document" Id="1"
            DesignerType="ChooseDoclibItem" DisplayName="Item" />
        <FieldBind Field="TargetFolder" Text="target" Id="2"
            DesignerType="TextArea" DisplayName="Target" />
    </RuleDesigner>
    <Parameters>
        <Parameter Name="ListId" Type="System.Guid" Direction="In" DesignerType="Hide" />
        <Parameter Name="ItemGuid" Type="System.Guid" Direction="In" DesignerType="ListItem"
            Description="ID of the list item used by this action." />
        <Parameter Name="TargetFolder" Type="System.String, mscorlib" Direction="In"
            Description="Target Folder where the file will be moved to." />
    </Parameters>
</Action>

As you can see the ClassName and Name attributes map to the corresponding elements in the Visual Studio 2013 project. Within the RuleDesigner element are defined the fields to prompt to the end users, while in SharePoint Designer 2013, in order to fill out the item to move (field with Id 1) and the target folder (field with Id 2). Furthermore, in the Parameters section you can see the real input arguments expected by the custom action, whose Name attribute map to the Field attributes of the FieldBind elements.

Build the project, publish the .WSP package and upload it onto the target SharePoint 2013 Site Collection inside the list of Sandboxed Solutions (“Site Settings” –> “Web Designer Galleries” –> “Solutions”), whether it is on-premises or on SharePoint Online. Activate the solution and the target feature, as well. Start SharePoint Designer 2013, or close and restart it, and create a new workflow definition. You will find the new action available in the “Files” group of actions. In the following figure, you can see the output in SharePoint Designer 2013.

WF-Custom-Action-07

Sometime, the custom action do not show up in SharePoint Designer 2013. In that situation, try to clear the cache of the tool simply by deleting the folder named with the name of the target site collection and available under the folder user profile\appdata\local\microsoft\websitecache\sitename.

That’s all … Enjoy with your custom actions!

Here you can download the code related to this article.

1 - 10Next
 
Visit my company: PiaSys.com 
 

 About this blog

 
About this blog

Welcome to the SharePoint Developer Reference Blog. I'm Paolo Pialorsi and I'm a senior consultant, author and trainer, focused on SharePoint development and customization. I'm based in Italy, but I work whereever it is needed (mainly EMEA). I'm a Microsoft Certified Master on SharePoint 2010.

You also can follow me on twitter: @PaoloPia

 MCM.png

I'm speaking at TechEd Europe 2014