Skip to content

Add utility method to encode node names #58

@mbreissi

Description

@mbreissi

When writing links that interact with external systems it is often that case that node names are created dynamically from names in the external system. Those external systems may have different naming rules than DSA (e.g., banned characters). For that reason, it would be helpful to provide a standard encoding method for developers to use to encode names. This can also be useful when for node names created by action parameters that can be typed in by users who may not be aware of the naming rules. What follows is the code for a method that mirrors the implementation in the Java SDK:

using System;
using System.Linq;
using System.Text;
using DSLink.Nodes;
using System.Globalization;

namespace DSLink.Util
{
    // ReSharper disable once ClassNeverInstantiated.Global
    public class StringUtils
    {
        public static string EncodeNodeName(string str)
        {
            if (str == null)
            {
                return null;
            }

            StringBuilder builder = new StringBuilder();

            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] == '%' && i+2 < str.Length)
                {
                    // check to see if this is already a hex encoded value
                    // and, if so, leave it alone
                    string possibleHexVal = str.Substring(i+1, 2);
                    if (int.TryParse(possibleHexVal, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var intVal))
                    {
                        builder.Append(str[i]).Append(possibleHexVal);
                        i += 2;
                    }
                    else
                    {
                        builder.Append(str[i]);
                    }
                }
                else if (Node.BannedChars.Contains(str[i]))
                {
                    builder.Append('%').Append(Convert.ToByte(str[i]).ToString("x2").ToUpper());
                }
                else
                {
                    builder.Append(str[i]);
                }
            }

            return builder.ToString();
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions