2
using System.Linq;
using System.Threading.Tasks;

var assetId = Context.TargetId;

// Ensure assetId is not null
if (assetId == null)
{
    MClient.Logger.Error("AssetId is null.");
    return;
}

// Check if public links don't exist yet
var query = Query.CreateQuery(entities => from e in entities
                                          where e.DefinitionName == "M.PublicLink"
                                          && e.Parent("AssetToPublicLink") == assetId.Value
                                          && e.Property("Resource") == "downloadOriginal"
                                          && e.Property("IsDisabled") == false
                                          select e);
query.Take = 1;

var result = await MClient.Querying.QueryIdsAsync(query);
if (result.TotalNumberOfResults > 0)
{
    MClient.Logger.Info("Public links already exist for asset with id '" + assetId + "'");
    return;
}

// Get the asset's file name
var assetQuery = Query.CreateQuery(entities => from e in entities
                                               where e.Id == assetId.Value
                                               select e);
var assetResult = await MClient.Querying.QueryAsync(assetQuery);

if (assetResult.TotalNumberOfResults == 0)
{
    MClient.Logger.Error("No asset found with id '" + assetId + "'");
    return;
}

// Assuming "FileName" is a property of the asset entity
var assetEntity = assetResult.Items.FirstOrDefault();
var fileName = assetEntity?.GetPropertyValue<string>("FileName");

if (string.IsNullOrEmpty(fileName))
{
    MClient.Logger.Error("No file name found for asset with id '" + assetId + "'");
    return;
}

// Create public links with the file name as the RelativeUrl
await CreateForRendition("downloadOriginal", assetId.Value, fileName);
MClient.Logger.Info("Created public link 'downloadOriginal' with file name '" + fileName + "' for asset with id '" + assetId + "'");

async Task CreateForRendition(string rendition, long assetId, string fileName)
{
    var publicLink = await MClient.EntityFactory.CreateAsync("M.PublicLink");

    if (publicLink.CanDoLazyLoading())
    {
        await publicLink.LoadMembersAsync(new PropertyLoadOption("Resource"), new RelationLoadOption("AssetToPublicLink"));
    }

    publicLink.SetPropertyValue("Resource", rendition);

    var relation = publicLink.GetRelation<IChildToManyParentsRelation>("AssetToPublicLink");
    if (relation == null)
    {
        MClient.Logger.Error("Unable to create public link: no AssetToPublicLink relation found.");
        return;
    }

    relation.Parents.Add(assetId);

    // Set the RelativeUrl property using the file name
    publicLink.SetPropertyValue("RelativeUrl", fileName);

    await MClient.Entities.SaveAsync(publicLink);
}

2 Answers 2

1

In order to set the file name as url in the public link, you will need to add below code.

 publicLink.SetPropertyValue("RelativeUrl", fileName);

You don't need to run the code in which are setting propertyvalue for PublicLinkURL. Instead you need to set RelativeUrl using the above line of code.

This will generate the public link in the below format:

https://{{ContentHubInstanceUrl}}.sitecorecontenthub.cloud/api/public/content/{{fileName}}?v=ff80998e

As an additional note in case you will like to set the v(version) parameter in the query string as well, you can add below code to set that.

publicLink.SetPropertyValue("VersionHash", {{versionHash}});

This version hash needs to be a random alphanumeric string of 8 digits.

Hope this helps!!! Let me know in case you face any issues.

4
  • Hello! I updated my code in my post - does that look correct?
    – H. Thomp
    Commented Aug 15 at 19:19
  • Yes perfect @H.Thomp...let me know in case you face any issues
    – ckhanna
    Commented Aug 15 at 19:31
  • 1
    Figured it out! Someone created a script that was conflicting with mine! THANK YOU!
    – H. Thomp
    Commented Aug 15 at 19:38
  • Glad to hear that @H.Thomp!!!
    – ckhanna
    Commented Aug 15 at 20:48
2

You need to set the RelativeUrl property with the filename instead of the PublicLinkURL property of the public link.

I tried specifying the RelativeUrl in the public link pop-window of an asset and was able to successfully add the file name to the public link.

The public link in my case: https://xxx.sitecoresandbox.cloud/api/public/content/MeltyChocolateChipCookie?v=4196f90f (the sandbox name removed deliberately)

Here are the properties of the public link above:

 "properties": {
    "RelativeUrl": "MeltyChocolateChipCookie",
    "Resource": "downloadOriginal",
    "ResourceType": "content",
    "VersionHash": "4196f90f",
    "IsDisabled": false,
    "ExpirationDate": null,
    "Status": "Completed",
    "Progress": "The link is currently active.",
    "FileKey": "local-61a4c20670d14a99be1b86e8f3adccb0",
    "ConversionConfiguration": null,
    "PublishStatus": {
        "identifier": "Published",
        "labels": {
            "en-US": "Published"
        }
    },
    "PublishStatusDetails": null
},
5
  • I am sorry - I am REALLY new at this - so I need to update the below and change publinkurl to relativeurl? var publicLinkUrl = $"/{fileName}"; publicLink.SetPropertyValue("PublicLinkURL", publicLinkUrl); await MClient.Entities.SaveAsync(publicLink);
    – H. Thomp
    Commented Aug 15 at 18:25
  • @H.Thomp yes, that is correct. I looked at your updated code and it is correct. Did that work for you? Commented Aug 15 at 19:29
  • @Chanddra.Sekaran.V It did not - maybe my trigger is wrong? It keeps putting the GUID in the url path. I have the trigger set as post action.
    – H. Thomp
    Commented Aug 15 at 19:32
  • @H.Thomp Can you move publicLink.SetPropertyValue("RelativeUrl", fileName); next to publicLink.SetPropertyValue("Resource", rendition);? I have a feeling you are setting the relative URL a bit late after you've added the public link to the asset. Commented Aug 15 at 19:36
  • 1
    I figured it out thank you for your help!
    – H. Thomp
    Commented Aug 15 at 19:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.