Skip to content

Latest commit

 

History

History
80 lines (58 loc) · 2.09 KB

EXAMPLES_GuidFormats.md

File metadata and controls

80 lines (58 loc) · 2.09 KB

Back to Package Contents

You can use this class for parsing and formatting Guid values.

Let's see an example using Dynamics 365 API:

using System;

string apiRoot = "/api/data/v9.0/";
string entitySetName = "incidents";
var entityId = Guid.NewGuid();

// The example API endpoint:
// /api/data/v9.0/incidents(incidentid)

// Instead of manually enclosing the Guid value in parentheses
// we can specify that format for parsing and formatting methods.

ToString()

using EgonsoftHU.Extensions.Bcl.Constants;

// Instead of
string formattedEntityId = entityId.ToString("P");
// you can write
string formattedEntityId = entityId.ToString(GuidFormats.Parenthesis);

string entityUrlReference = $"{apiRoot}{entitySetName}{formattedEntityId}";

ParseExact()

using EgonsoftHU.Extensions.Bcl.Constants;

// Instead of
Guid entityId = Guid.ParseExact(formattedEntityId, "P");
// you can write
Guid entityId = Guid.ParseExact(formattedEntityId, GuidFormats.Parenthesis);

TryParseExact()

using EgonsoftHU.Extensions.Bcl.Constants;

// Instead of
if (Guid.TryParseExact(formattedEntityId, "P", out Guid entityId))
{
}
// you can write
if (Guid.TryParseExact(formattedEntityId, GuidFormats.Parenthesis, out Guid entityId)
{
}

Converting from one format to another format

using EgonsoftHU.Extensions.Bcl.Constants;

string input = Guid.NewGuid().ToString(GuidFormats.Brace);
// e.g. {72802294-8a43-4ba9-a360-3498df3cb0c7}

string output = ChangeGuidFormat(input, GuidFormats.Brace, GuidFormats.Parenthesis);
// e.g. (72802294-8a43-4ba9-a360-3498df3cb0c7)

string ChangeGuidFormat(string input, string inputFormat, string outputFormat)
{
    return
        Guid.TryParseExact(input, inputFormat, out Guid value)
            ? value.ToString(outputFormat)
            : throw new ArgumentException("Error parsing the Guid value.", nameof(input));
}