While working on my EPiCloud module I came across a snag where I wanted to update page properties (definitions) from code without republishing the page. The page property I'm updating is going to change frequently and I didn't fancy having pages of versions which would be confusing for editors.
After having a play with 'traditional' page editing and publishing in code I was drawing a blank and was toying with the idea of calling the SQL stored procedures for editing properties, although I didn't want to go there! Before trying to go further I posed my problem to the #epicode IRC channel (see here for details - come and join in the discussion!). One of the guys on there, Astinus-, suggested I look at the SaveAction.ForceCurrentVersion enumeration option on the Save method when saving a page. For some reason I must have seen that option many times without actually noticing it.
Unfortunately the SaveAction enumeration isn't really documented that well. In fact, if you look at the SDK entry for the Save method then you'll see that EPiServer themselves tell you that it's there to use but undocumented. If you try to use it you might notice that it doesn't do an awful lot, you might get a read-only error when you change anything, or you might get an error about an INSERT failing. This is because the following all have to be true:
- You must be working on a version with a version ID from an existing page
- You must be working on a writable clone
- You must combine the ForceCurrentVersion with either a Save or Publish action
The following code snippet amends a property on the published version of the current page and saves it as published without a republish (CMS version 5):
1: PageVersion oPublishedVersion = PageVersion.LoadPublishedVersion(CurrentPage.PageLink);
2:
3: PageData oThisPage = DataFactory.Instance.GetPage(oPublishedVersion.ID);
4:
5: PageData oWritablePage = oThisPage.CreateWritableClone();
6:
7: oWritablePage.Property["SomeProperty"].Value = "Value to set";
8:
9: DataFactory.Instance.Save(oWritablePage, SaveAction.ForceCurrentVersion | SaveAction.Publish, EPiServer.Security.AccessLevel.NoAccess);
I hope this code is useful to someone - but be aware that we are doing a couple of sneaky things such as using AccessLevel.NoAccess. Use my code carefully!