Brian Hinchey Brian Hinchey - 1 year ago 88
ASP.NET (C#) Question

How can I convert arbitrary strings to CLS-Compliant names?

Does anyone know of an algorithm (or external library) that I could call to convert an arbitrary string (i.e. outside my control) to be CLS compliant?

I am generating a dynamic RDLC (Client Report Definition) for an ASP.Net Report Viewer control and some of the field names need to be based on strings entered by the user.

Unfortunately I have little control over the entry of the field names by the client (through a 3rd party CMS). But I am quite flexible around substitutions required to create the compliant string.

I have a reactive hack algorithm for now along the lines of:

public static string FormatForDynamicRdlc(this string s)
//We need to change this string to be CLS compliant.
return s.Replace(Environment.NewLine, string.Empty)
.Replace("\t", string.Empty)
.Replace(",", string.Empty)
.Replace("-", "_")
.Replace(" ", "_");

But I would love something more comprehensive. Any ideas?

NOTE: If it is of any help, the algorithm I am using to create the dynamic RDLC is based on the BuildRDLC method found here:

Answer Source

Here's the algorithm I use to create C/C++ identifiers from arbitrary strings (translated to C#):

    static void Main(string[] args)
        string input = "9\ttotally no @ # way!!!!";
        string safe = string.Concat("_", Regex.Replace(input, "[^a-z0-9_]+", "_"));

The leading underscore is unnecessary if the first character of the regex result is not numeric.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download