Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add utility method to encode node names #58

Open
mbreissi opened this issue Sep 6, 2018 · 0 comments
Open

Add utility method to encode node names #58

mbreissi opened this issue Sep 6, 2018 · 0 comments

Comments

@mbreissi
Copy link

mbreissi commented Sep 6, 2018

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();
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant