Skip to content

Instantly share code, notes, and snippets.

@lowedown
Last active November 29, 2021 10:09
Show Gist options
  • Save lowedown/f729d01ef4a48425c88965993fc8c7e9 to your computer and use it in GitHub Desktop.
Save lowedown/f729d01ef4a48425c88965993fc8c7e9 to your computer and use it in GitHub Desktop.
API controller that returns references to a ContentHub asset by assetId plus an example widget for use on a contentHub asset details page
using Sitecore.Abstractions;
using Sitecore.ContentSearch;
using Sitecore.ContentSearch.Linq;
using Sitecore.ContentSearch.Linq.Utilities;
using Sitecore.Data.Items;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
namespace MyProject.Controllers.Api
{
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class ContentHubAssetUsageController : ApiController
{
private readonly BaseSettings _settings;
public ContentHubAssetUsageController(BaseSettings settings)
{
_settings = settings;
}
[HttpGet]
public IHttpActionResult GetUsages(long assetId)
{
if (!_settings.GetBoolSetting("ContentHubCustomisations.EnableAssetUsageController", false))
{
return Unauthorized();
}
return Ok(GetRelevantItems(assetId).Where(i => i != null).Select(MapFields));
}
private IEnumerable<Item> GetRelevantItems(long assetId)
{
ISearchIndex index = ContentSearchManager.GetIndex(_settings.GetSetting("ContentHubCustomisations.IndexName"));
using (IProviderSearchContext context = index.CreateSearchContext())
{
SearchResults<ContentHubImagesSearchResultItem> results =
context.GetQueryable<ContentHubImagesSearchResultItem>()
.Where(x => x.ContentHubAssetIds.Contains(assetId.ToString()))
.GetResults();
if (results.Any())
{
return results.Hits.Select(h => h.Document.GetItem());
}
return new List<Item>();
}
}
private AssetUsage MapFields(Item item)
{
return new AssetUsage()
{
ItemId = item.ID.ToString(),
ItemName = item.Name,
ItemPath = item.Paths.FullPath,
Language = item.Language.Name,
Version = item.Version.Number
};
}
}
public class AssetUsage
{
public string ItemId { get; set; }
public string ItemName { get; set; }
public string ItemPath { get; set; }
public string Language { get; set; }
public int Version { get; set; }
}
}
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/"
xmlns:set="http://www.sitecore.net/xmlconfig/set/"
xmlns:role="http://www.sitecore.net/xmlconfig/role/">
<sitecore>
<settings>
<setting name="ContentHubCustomisations.IndexName" value="sitecore_master_index" />
<setting name="ContentHubCustomisations.EnableAssetUsageController" value="true" role:require="ContentManagement or Standalone" />
</settings>
</sitecore>
</configuration>
<div class="panel-container form-horizontal panel-container--view-mode panel--shadowed skin-m-default custom-related-by-collection-panel">
<h3 class="header-caption text-overflow-hidden flex-1">Asset usage in CMS</h3>
<div>
<button class="btn btn-primary js-get-usage-button">Show usage</button>
</div>
<div class="custom-cms-usage-results">
</div>
</div>
var self = this;
var entityLoadedSubscription = options.mediator.subscribe("entityLoaded", function(entity) {
self.entityId = entity.systemProperties.id();   
});
$('.js-get-usage-button').click(function(event) {
showUsages('local', 'https://my-sitecore-management'); // This should point to your management server
});
function showUsages(title, baseUrl) {
var url = baseUrl + "/api/ContentHubAssetUsage/GetUsages?assetId=" + self.entityId ;
const maxResults = 50;
$.get( url, function( data ) {
if (data.length <= 0) {
$('.custom-cms-usage-results').append(`<h4 style="margin-top: 5px;">${title}</h4><small>No usage of this asset found.</small>`);
return;
}
$('.custom-cms-usage-results').append(`<h4 style="margin-top: 5px;">${title} (${data.length})</h4>`);
$('.custom-cms-usage-results').append(`<table class="table">` + data.slice(0, maxResults).map(function(item) { return ResultItem(item, baseUrl); }).join('') + `</table>`);
if (data.length > maxResults) {
$('.custom-cms-usage-results').append(`<small>Max ${maxResults} results are shown.</small>`);
return;
}
$('.js-get-usage-button').hide();
});
}
// Template for result item
const ResultItem = (item, baseUrl) => `
<tr>
<td>
<a href="${baseUrl}/sitecore/shell/Applications/Content Editor?id=${encodeURIComponent(item.ItemId)}&amp;vs=1&amp;la=${item.Language}&amp;sc_content=master&amp;fo=${encodeURIComponent(item.ItemId)}&amp;ic=People%2f16x16%2fcubes_blue.png&amp;he=Content+Editor&amp;cl=0" target="_blank">
${item.ItemName}
</a> <br/>
<small>${item.ItemId}</small><br/>
<small>${item.ItemPath}</small>
</td>
<td><small class="text-nowrap" title="Version">${item.Version}</small></td>
<td><small class="text-nowrap">${item.Language}</small></td>
</tr> `;
@lowedown
Copy link
Author

API controller can be called through /api/ContentHubAssetUsage/GetUsages?assetId=<myAssetId>
If you haven't set up api routing in your solution yet, see details here.
You'll also need to register the API controller with the DI framework through a IServicesConfigurator.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment