Content Hub Web SDK – Programmatically update assets in Content hub from items in Sitecore

Getting the entity

IEntity entity = await _connector.Client.Entities.GetAsync(long.Parse(assetId));

assetId can be a string or a long. The string is mostly used when IDs look like an alphanumeric hash. If we want an image with asset Id of 99551 then use long.

Getting a relationship with an entity

IRelation relation = entity.GetRelation("AssetTypeToAsset");
IList<long> values = relation.GetIds();
//if (values.Count == 0) then we know there is no value set, otherwise there is already a value set for that relation

Setting up a related value

IEntity imageAssetEntity = await _connector.Client.Entities.GetAsync("M.AssetType.Custom");
IChildToOneParentRelation assetEntityRelation = await entity.GetRelationAsync<IChildToOneParentRelation>("AssetTypeToAsset");
assetEntityRelation.Parent = imageAssetEntity.Id.Value;
//This will set up the selected asset entity's AssetType as Custom

Set a property for an entity

string alt = item["Alt"] ?? "";
ICultureInsensitiveProperty altProperty = entity.GetProperty<ICultureInsensitiveProperty>("Alt");
altProperty.SetValue(alt);
//This will get the Alt field value of an item from sitecore and update an asset with that value in the Alt property

Debug your code and attach it to processes running inside Docker

There I was, one fine afternoon, having a deep-fried twinkie and writing some commands for Sitecore. Sitecore was running in docker. so every code change, build, deploy, and sometimes run up.ps1 if there is an error, and cross my fingers and test the command. I wanted to attach Visual Studio to the w3wp process running on the cm image.

In Visual Studio follow these steps

Select Docker from the connection type dropdown

Click on “Find”
is this is your first time, visual studio will install a package in your docker from nuget so that it’s discoverable

Once you are connected to the right image

find your process and attach it.

Enjoy all your breakpoints.

~ Do not block someone else’s driveway. They may have to go somewhere. ~

The problem with multiple Sitecore instance management, using favicons.

Like thousands of other developers, our there who are working with Sitecore will face this problem.

The problem:

  • Working with multiple environments.
  • Working with multiple clients.
  • Working with duplicated tabs of Sitecore backend.

Screen Shot 2020-03-30 at 6.08.04 PM

There are multiple solutions out there.

  • Modifying the header area to mention the environment or database.
  • Updating the color to determine the environment.
  • Working with the configs to change the look for the backend.

But what I was looking for is to know before I clicked on the tabs as seen above. The page title and the favicons were the easiest things to change for that.

Just go to your site’s root/Sitecore/images/ and replace the favicon.ico with your client’s favicon.

That’s it. Now I know who’s Sitecore I will be unleashing before I open the tab. I found this to be the least intrusive and simplest solution to my problem.

Let me know if you know a better way. Please.

 

~ Be kind, be brave, be happy.~

See who is logged in to your Sitecore CM environment

Who had this problem where you have to make some changes to your CM server, you told the authors to get out, but they never leave. They love Sitecore so much you can’t get them out by themselves.

So, I wanted to know who is using the server at the time. and thus created a page that lists the logged-in users at that time.

Sitecore has this functionality on the kick users/boost user page. So, that’s where I started. Did you know /sitecore/admin/sessionsummary.aspx is a page that’s actually there. But it doesn’t work. I get 500 error. Screen Shot 2020-02-14 at 3.19.04 PM

 

So, Dotpeek it is and I made the following.

@{
	List<Sitecore.Web.Authentication.DomainAccessGuard.Session> newList = Sitecore.Web.Authentication.DomainAccessGuard.Sessions;
}
<div><h3>Maximum Sessions Allowed in this instance:</h3>  @Sitecore.Web.Authentication.DomainAccessGuard.MaximumSessions</div>
<div>
@if (newList.Any())
{
	<H3>logged in users:</H3>
	<table border="1">
	<tr>
		<td>Session ID</td>
		<td>User Name</td>
		<td>Created Date</td>
		<td>Last Request Date</td>
		<td>Active For (Minutes)</td>
	</tr>
	@foreach (var dg in newList)
	{
	<tr>
		<td>@dg.SessionID</td>
		<td>@dg.UserName</td>
		<td>
			@DateTime.Parse(dg.Created.ToString()).ToLocalTime()
		</td>
		<td>
			@DateTime.Parse(dg.LastRequest.ToString()).ToLocalTime()
		</td>
		<td>
			@((int)((dg.LastRequest - dg.Created).TotalMinutes))
		</td>
	</tr>
	}
	</table>
}
</div>

 

I stuck this in my /Sitecore/admin folder, or put it wherever you need.

This will give you following page.

Screen Shot 2020-02-14 at 3.22.24 PM

I added an auto-refresh on the page as well just for fun, you all know how to do that, right 🙂

Enjoy!!!

 

~ Fight, Flight, Food & Fuck, The four F’s of Life’s Basics. ~

Register Bundle not registering Bundle?

I have a not-so-custom register bundle pipeline.

<processor type="namespace.Pipelines.Initialize.RegisterBundles, namespace" />

It’s supposed to bundle all my CSS and js into one file.

But it was NOT, thus this post.

 

ALL I had to do is to remember that I was building the solution in debug configuration mode. Bundling doesn’t happen if you are not in RELEASE mode. so, please change your Build configuration to release and save yourself some debugging time when deploying an app.

 

 

 

~ Life is not a sprint, it’s a marathon. ~

@Html.Sitecore().Placeholder() | CS1061: ‘System.Web.WebPages.Html.HtmlHelper’ does not contain a definition for ‘Sitecore’ |Error on master page layout file

Sitecore is hard. But being everything in life is hard, I was setting up another Sitecore instance. everything was ready to go and when the time came. I hit the homepage.

Alas! the yellow screen of death.

Server Error in '/' Application.
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1061: 'System.Web.WebPages.Html.HtmlHelper' does not contain a definition for 'Sitecore' and no extension method 'Sitecore' accepting a first argument of type 'System.Web.WebPages.Html.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)
Source Error:
Line 6:  	<div class="row">
Line 7:  		<div class="column--standard col-xs-12 col-lg-6 col-lg-push-3">
Line 8:  			@Html.Sitecore().Placeholder("page-details")
Line 9:  			@Html.Sitecore().Placeholder("more-top")
Line 10: 			@Html.Sitecore().Placeholder("content")
Source File: d:\home\site\wwwroot\Areas\CLIENT\Views\Master\StandardPage.cshtml    Line: 8

Compiler Warning Messages:
Warning: CS1702: Assuming assembly reference 'System.Interactive.Async, Version=3.0.1000.0, Culture=neutral, PublicKeyToken=94bc3704cddfc263' matches 'System.Interactive.Async, Version=3.0.3000.0, Culture=neutral, PublicKeyToken=94bc3704cddfc263', you may need to supply runtime policy
Source Error:
[No relevant source lines]

Show Detailed Compiler Output:
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.3429.0

What the actual Eff, right? Check the dlls, they were the right version. Right before I was going to pull out the last three hairs on my head without critically thinking about the error, my colleague came up with the idea of checking the web.config in the Views folder.

And, there it was. web.config didn’t get deployed inside the folder. Once I had the file copied over, the view knew which dll to load and everything was peachy Dory.

 

~ Is web.config one word or two, grammatically? ~

Connect using C# to cloudAMQP

Still using RabbitAMQP?

Have to keep using it?

Move to the Cloud…

I am using CloudAMQP.

ConnectionFactory factory = new ConnectionFactory();
factory.Uri = new Uri("amqp://[username]:[password]@[server]/[vhost]");
factory.RequestedHeartbeat = 15;
factory.AutomaticRecoveryEnabled = true;
connection = factory.CreateConnection();

I could not find a better way of doing this after looking around.

So, Use it and move on!!!

 

~ Do not fix what’s not broken. ~

Custom fields on Coveo Search result templates with conditions

Do you run Sitecore?

Do you have Coveo for searching the sites?

You are getting results back but now you want to add one of your fields in the result. This post is for you.

    • I have a meta_description field.
    • this is mapped to the description field from meta.
    • Once these are indexed I wanted these to show up on my search results.
    • If I didn’t have a description set then I would use Coveo’s auto-generated excerpts to show on the search result.
    • below is what I did:
    • <div class="coveo-result-cell">
          <% if(raw.meta_description){ %>
          <span class="description">
              {{= raw.meta_description}}<br />
          </span>
          <% } else { %>
              <span class="CoveoExcerpt description"></span>
          <% } %>
      </div>
      
      
    • And I had to add one more trick on js to get this field returned with the raw data from Coveo Cloud.
    •     Coveo.$$(searchRoot).on('buildingQuery',
              function (e, args) {
                  args.queryBuilder.addFieldsToInclude([
                      "meta_description"
                  ]);
              });
    • That’s it.

 

 

 

~ Don’t fall asleep when you are awake. ~

 

Visual Studio – Project Target Framework Not Installed

Image result for project target framework not installed

Seen this before?

Downloading the targeting pack didn’t work? Now you are on the hunt on the internet and finally ended up here?

Go to C:\Program Files (x86)\Microsoft Visual Studio\Installer

run the vs_installer.exe

Remember you have to close all open visual studio instances while this is installing.

when the installation is complete, load up visual studio and your project. all should be well.

 

~ We are all bald under our hair. ~

 

 

 

Format Dates in Sitecore Model

We recently started using FieldRenderer.Renders everywhere.

Along came the practice of using HtmlStrings all over as well.

 

so most fields looked like

Body = new HtmlString(FieldRenderer.Render(item, "Body")),

But when it comes to Date fields, found this shortcut very handy.

PostedDate = new HtmlString(FieldRenderer.Render(item, "Posted Date", "format=MMMM d, yyyy")),

 

 

Enjoy!

~ Don’t lie. Hide the truth. That way you can reveal it later. ~