Sharepoint - How to enable publishing feature using CSOM?

How to activate feature via Managed Client Object Model:

public void ActivateFeature(string webFullUrl,Guid featureId,bool force,FeatureDefinitionScope featdefScope)
{
    using (var ctx = new ClientContext(webFullUrl))
    {
       var features = ctx.Web.Features;
       ctx.Load(features);
       ctx.ExecuteQuery();

       features.Add(featureId, force, featdefScope);
       ctx.ExecuteQuery();
    }
}

About feature activation via CSOM

According to MSDN the FeatureCollection.Add method has the following signature

public Feature Add(
    Guid featureId,
    bool force,
    FeatureDefinitionScope featdefScope
) 

which is intended for adding the feature to the collection of activated features and returns the added feature

Parameter FeatureDefinitionScope is used for specifying the feature scope for a feature definition. At the same time the documentation says:

It must have the value of FeatureDefinitionScope.Site or FeatureDefinitionScope.Farm

It basically means that the method FeatureCollection.Add does not accept FeatureDefinitionScope.Web value for featdefScope and therefore feature activation with Web scope is not supported in CSOM.


In your case one of the features is Web scoped

PublishingWeb SharePoint Server Publishing 94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb Web

and therefore it could not be activated via CSOM since FeatureDefinitionScope.Web is not supported

P.S. This is not correct statement, see the update section below.

Update

In order to activate Web level feature specify FeatureDefinitionScope.None, the following example demonstrates how to activate SharePoint Server Publishing (Web) feature:

using (var ctx = new ClientContext(webUri))
{
    ctx.Credentials = new SharePointOnlineCredentials(userName, securePassword);

    var featureId = new Guid("94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb");
    var features = ctx.Web.Features;
    features.Add(featureId, true, FeatureDefinitionScope.None);
    ctx.ExecuteQuery();
} 

Has been verified in SharePoint CSOM v16.


How to verify feature scope

$feature = get-spfeature featureId
if ($feature -eq $null -or $feature -eq "") {
    echo "no feature found with id"
} else {
  echo ("feature found. Scope is  " + $feature.Scope)
}

You can use this method:

function ActivateFeature(featureGuid)
{
var clientContext = new SP.ClientContext.get_current();
var site = clientContext.get_site();
var guid = new SP.Guid('{'+featureGuid+'}');

var featDef = site.get_features().add(guid, false, SP.FeatureDefinitionScope.site);

clientContext.executeQueryAsync(Function.createDelegate(this, this.OnSuccess), Function.createDelegate(this, this.OnFail));
}

function OnSuccess(sender, args) {
    alert('Success!');
}

function OnFail(sender, args) {
    alert('Fail: ' + args.get_message() + '\n' + args.get_stackTrace());
}

http://www.learningsharepoint.com/2010/07/09/activate-feature-with-client-object-model-sharepoint-2010/

Tags: