views:

162

answers:

4

Anyone know if there is already a validator for "type" strings?

I want to make sure that the type attributes in my custom config are one of the following:

type="TopNamespace.SubNameSpace.ContainingClass, MyAssembly"
type="TopNamespace.SubNameSpace.ContainingClass, MyAssembly, Version=1.3.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089"

Writing one is easy enough, I just don't want to reinvent the wheel.

A: 

You'll get an error with resharper's Global Error Analysis if it can't find the namespace or class, but that's not always helpful if your referencing a plugin.

probably the simpliest thing is to put your code to load the app domain in a try catch block.

if the dll is in the bin it will be loaded on startup but it won't throw an error until you use it so if you just new up an instance of ContainingClass. You could pull the namespaces from the config and then try and use each class.

Scott Cowan
Loading the type is easy. What I'm after is to sanity check the string from config before I even try. Writing the validator for that is easy. I just didn't want to do it if one already exists in .NET somwhere.
claco
there's nothing I've seen, but the Regex for it shouldn't be too hard.
Scott Cowan
A: 

I'm pretty sure there is nothing built into the framework for this.

There are a couple of results on regexlib.com. Any of them should work for the scenario you described. However, bear in mind that none of them will properly support the syntax for specifying generic types. In order to properly handle this, a regular expression alone will not be sufficient - you will need to recursively process the same regular expression against the generic type arguments. For example, consider the following type names:

List<>
"System.Collections.Generic.List`1"

List<string>
"System.Collections.Generic.List`1[[System.String]]"

Dictionary<string, string>
"System.Collections.Generic.Dictionary`2[[System.String],[System.String]]"

Dictionary<string, List<string>>
"System.Collections.Generic.Dictionary`2[[System.String],[System.Collections.Generic.List`1[[System.String]]]]"

For more information, see the MSDN documentation on Type.AssemblyQualifiedName.

jon without an h
+2  A: 

I'm not sure what you mean by "custom config", but if you're still working within .NET's configuration framework (e.g., developing a custom configurationSection/configurationElement), you can simply type the property as System.Type (instead of string), and .NET will do the validation automatically.

Abraham Pinzur
A: 

Abraham Pinzur's suggestion is correct if you are writing a custom configuration section.

Type.GetType(...) allows you to do it by hand.

Bryan Watts