Alex Rivera | Logout

Why does Sitecore publish draft items from the C# API, and how do I stop it doing so?

Asked 2012-09-05T15:41:09.403
9

I'm running a scheduled publish of my Sitecore master DB using the Sitecore publishing API. I call a web service at scheduled intervals during the day which runs the following code (slightly condensed for readability):

// grab the root content node from sitecore
Item contentNode = dbSource.Items[ID.Parse("{0DE95AE4-41AB-4D01-9EB0-67441B7C2450}")];

PublishOptions options = new PublishOptions(sourceDatabase, targetDatabase, PublishMode.Smart, lang, DateTime.Now);

options.RootItem = contentNode;

options.Deep = true;

Publisher p = new Publisher(options);

p.PublishAsync();

When we run the above code it publishes everything in the content node, including all descendants, regardless of workflow state. It's like it is ignoring the workflow completely. This is not what we are after, and is causing lots of problems on our live website.

If we run the same action from within Sitecore Desktop it publishes everything in the content node, including all descendants, that are publishable (I.e. in the final workflow stage). It does not publish any items in the tree that are still in draft mode. This is the required bahaviour.

I have tried implementing the code as a non-admin user by surrounding the above code with the following using statement:

string userName = @"sitecore\******";

Sitecore.Security.Accounts.User user = Sitecore.Security.Accounts.User.FromName(userName, true);

user.RuntimeSettings.IsAdministrator = false;

using (new Sitecore.Security.Accounts.UserSwitcher(user))
{
    ...
}

Unfortunately this has had no effect.

Is there something obvious I've missed, or am I doing it right and Sitecore is doing it wrong? Can anyone help please?

The strange thing I noticed, also, is that the draft items that were published, when viewed on the live database, wer

Edit
Report

1 Answer

15

Likely the issue is that your web service is not running within a site context that has workflow enabled.

The easiest way to do this within your code is to use a SiteContextSwitcher to change to the "shell" site.

using (new SiteContextSwitcher(SiteContextFactory.GetSiteContext("shell")))
{
    //do your publish
}

As for the published items without versions: In theory, that would still happen even with regular publishing. Workflow limits the publishing of item versions, not the items themselves. In your code, when iterating items and in other cases, you need to check whether item.Versions.Count > 0 before rendering.

answered 2012-09-05T15:51:48.847

Your Answer