Sitecore’s ID parsing is crazy

EDIT: I contacted Sitecore support about this one, and it turns out that it is fixed in Sitecore 10.4. (Number 91923 on https://developers.sitecore.com/downloads/Sitecore_Experience_Platform/104/Sitecore_Experience_Platform_104/Release_Notes). I missed that. Of course, there are still a lot of pre-10.4 instances out there, but over time this should cease being an issue)

Sitecore IDs – They’re just Guids, right? I mean, they look like a guid, their string representation is that of a Guid – so they must be Guids, right? Nope! It seems not. Get a load of this:

So here I’m trying to parse a SearchResult “topic”. It’s name is a Guid as a string, in “N” format.

  • Guid.Parse() gives you a Guid. Fine.
  • ID.Parse() gives you an ID. Fine.
  • ID.TryParse() returns false. Apparently it’s not an ID.

What the hell is going on?

Okay, so why? Let’s decompile ID.TryParse() for a look…

Well, much to my astonishment, the ID classes’ methods aren’t just wrappers for the Guid classes methods. In other words, ID.TryParse() doesn’t just wrap Guid.TryParse(). Instead, it does this weird shit. So, what’s going on in the second if statement?

Well, at this point, we need to talk about formats of Guids represented as string. There’s a whole bunch of different formats.

Now, I’ve never seen P or X format in use, but B,D and N are all pretty common. Notably, N format is the shortest string representation of a Guid. That’s probably why it is that format in the search index.

Well, that second if statement doesn’t support N format. N is 32 characters long , but it also doesn’t start with a ‘{‘- so TryParse() ends up calling ID.IsID() (more in a moment) .

I’m… unclear what someone was thinking when they wrote this. If it’s 38 characters and it starts with a ‘{‘ it should be okay? That logic doesn’t account for the end of the string. Or it’s contents. I mean, they could just have called ID.IsID()

…except unfortunately ID.IsID() was also written poorly. It checks length again – but only accepts 38 or 36 character strings. So… B or D format Guids, but not N. <facepalm> Why they didn’t use Guid.TryParse(), I am baffled.

And the depressing thing is that if that if statement were removed, ID.TryParse() would work properly, with all those formats. Or if ID.IsID() accepted 32 character values it would work, though granted, that would also mean disallowing hyphens if you’re parsing N format. Bear in mind that ID.Parse() does support those formats, so to my mind, so should ID.TryParse().

(Personally, I would make ID.IsID() and ID.TryParse() use Guid.TryParse() – and support the same formats as, say, ID.Parse())

Here’s a table of trying the different methods with different formats of ID

Sitecore’s ID parsing is crazy

One thought on “Sitecore’s ID parsing is crazy

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.