Instantly share code, notes, and snippets.
Created
April 16, 2020 02:10
-
Star
(0)
0
You must be signed in to star a gist -
Fork
(0)
0
You must be signed in to fork a gist
-
Save hfloyd/4335f678b1988e89d464a2835ab06667 to your computer and use it in GitHub Desktop.
A WebAPI Controller for use in an Umbraco 8 Website in the event that you need to re-save/re-publish all Content nodes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace MyProject.Core.WebApi | |
{ | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Net.Http; | |
using System.Text; | |
using Dragonfly.NetModels; | |
using Newtonsoft.Json; | |
using Umbraco.Core.Models; | |
using Umbraco.Web; | |
using Umbraco.Web.Composing; | |
using Umbraco.Web.WebApi; | |
// NOTE: The "StatusMessage" model is present in Dragonfly.Net, which can be installed via NuGet, if desired. (https://github.com/hfloyd/Dragonfly.Net) | |
// Otherwise, edit to return the messages in a different format | |
[IsBackOffice] | |
public class AuthorizedApiController : UmbracoAuthorizedApiController | |
{ | |
private UmbracoHelper umbracoHelper = Current.UmbracoHelper; | |
/// /Umbraco/backoffice/Api/AuthorizedApi/RepublishAllContent?EmptyRecycleBin=false | |
[System.Web.Http.AcceptVerbs("GET")] | |
public HttpResponseMessage RepublishAllContent(bool EmptyRecycleBin = false) | |
{ | |
var returnSB = new StringBuilder(); | |
var msgMain = new StatusMessage(true); | |
var currentUser = Security.CurrentUser; | |
Current.Logger.Info(typeof(AuthorizedApiController), "RepublishAllContent() running for user {User}...", currentUser.Name); | |
msgMain.MessageDetails += $"Running for {currentUser.Name}...\n"; | |
var topNodes = Services.ContentService.GetRootContent().OrderBy(n => n.SortOrder); | |
var allNodeResults = new List<NodeSaveResult>(); | |
foreach (var node in topNodes) | |
{ | |
var loopResults = LoopNodes(node); | |
allNodeResults.AddRange(loopResults); | |
} | |
var nodeMsg = string.Join("\n", allNodeResults.Select(n => n.ResultMsg)); | |
var counterSuccess = allNodeResults.Count(n => n.ResultSuccess == true); | |
var counterFailure = allNodeResults.Count(n => n.ResultSuccess == false); | |
msgMain.MessageDetails += nodeMsg; | |
//Finalize | |
msgMain.Message = | |
$"RepublishAllContent(): {counterSuccess} node(s) were saved/published. {counterFailure} node(s) failed."; | |
if (EmptyRecycleBin) | |
{ | |
Services.ContentService.EmptyRecycleBin(currentUser.Id); | |
msgMain.MessageDetails += "\nEmptyRecycleBin was run."; | |
} | |
Current.Logger.Info(typeof(AuthorizedApiController), "RepublishAllContent() completed for user {User}...", currentUser.Name); | |
string json = JsonConvert.SerializeObject(msgMain); | |
returnSB.AppendLine(json); | |
return new HttpResponseMessage() | |
{ | |
Content = new StringContent( | |
returnSB.ToString(), | |
Encoding.UTF8, | |
"application/json" | |
) | |
}; | |
} | |
private IEnumerable<NodeSaveResult> LoopNodes(IContent ContentNode) | |
{ | |
var allResults = new List<NodeSaveResult>(); | |
var currNode = ContentNode.Id; | |
try | |
{ | |
//Do current Node | |
var result = ReSaveNode(ContentNode); | |
allResults.Add(result); | |
//Look for Children | |
long total = 0; | |
var countChildren = Services.ContentService.CountChildren(ContentNode.Id); | |
if (countChildren > 0) | |
{ | |
var children = Services.ContentService.GetPagedChildren(ContentNode.Id, 0, countChildren, out total).OrderBy(n => n.SortOrder).ToList(); | |
foreach (var childNode in children) | |
{ | |
currNode = childNode.Id; | |
var childResults = LoopNodes(childNode); | |
allResults.AddRange(childResults); | |
} | |
} | |
} | |
catch (Exception e) | |
{ | |
Current.Logger.Error(typeof(AuthorizedApiController), "RepublishAllContent() ERROR at Node {NodeId}", currNode); | |
} | |
return allResults; | |
} | |
private NodeSaveResult ReSaveNode(IContent ContentNode) | |
{ | |
var saveResult = new NodeSaveResult(); | |
saveResult.NodeId = ContentNode.Id; | |
var status = ContentNode.Published ? "Published" : "Unpublished"; | |
saveResult.PublishStatus = status; | |
var resultMsg = ""; | |
if (ContentNode.Published) | |
{ | |
var result = Services.ContentService.SaveAndPublish(ContentNode); | |
resultMsg = result.Result.ToString(); | |
if (result.Success) | |
{ | |
saveResult.ResultSuccess = true; | |
} | |
else | |
{ | |
saveResult.ResultSuccess = false; | |
var allMsgs = result.EventMessages.GetAll().Select(n => n.Category + " - " + n.Message); | |
var eventsString = string.Join(" \n\r ", allMsgs); | |
Current.Logger.Warn(typeof(AuthorizedApiController), "RepublishAllContent() Unable to Save & Publish Node {NodeId}: {EventMessages}", ContentNode.Id, eventsString); | |
} | |
} | |
else | |
{ | |
var result = Services.ContentService.Save(ContentNode); | |
resultMsg = result.Result.ToString(); | |
if (result.Success) | |
{ | |
saveResult.ResultSuccess = true; | |
} | |
else | |
{ | |
saveResult.ResultSuccess = false; | |
var allMsgs = result.EventMessages.GetAll().Select(n => n.Category + " - " + n.Message); | |
var eventsString = string.Join(" \n\r ", allMsgs); | |
Current.Logger.Warn(typeof(AuthorizedApiController), "RepublishAllContent() Unable to Save Node {NodeId}: {EventMessages}", ContentNode.Id, eventsString); | |
} | |
} | |
saveResult.ResultMsg = $"Node #{ContentNode.Id} ({status}) : {resultMsg}"; | |
return saveResult; | |
} | |
} | |
internal class NodeSaveResult | |
{ | |
public int NodeId { get; set; } | |
public string ResultMsg { get; set; } | |
public bool ResultSuccess { get; set; } | |
public string PublishStatus { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment