String parsing to a model (RegEx model binder?)
Is there any elegant way to bind a string to a model, short of writing a bunch of boilerplate code to do the binding myself? Essentially I have a command line interface to a 3rd party device, via telnet. I am building a web service to expose this CLI to external applications. After issuing the command via telnet, I get a response string back, and need to parse this into a model.
Example:
/> echosnd -if 1 -dn 5551234567
Echo Sounder Test created on Interface CITYCOTTNNN-5ES, Resource 12 with ID #2967232
/>
And I want to bind that string to create the following object:
public class ConfigureTestResponse
{
[CLIResponse(RegEx = "Interface (?<interface>[a-zA-Z0-9]*")]开发者_开发百科
public string Interface { get; set; }
[CLIResponse(RegEx = "Resource (?<resource>[0-9]*)")]
public int Resource { get; set; }
[CLIResponse(RegEx = "#(?<id>[0-9]*)")]
public int TestId { get; set; }
}
To start, I created the CLIResponseAttribute to hold the RegEx filter for that property (although the filters above very possibly don't work - I stuck them in for illustration, only TestId is tested [a little]). I can get them split into groups using Regex, and set the properties that way, but there is a bunch of conversions that I would need to handle (int32, int64, decimal, string, complex model, etc...) based on what the property type is. I am hoping there is some sort of binding that I could provide a name/value pair to, and it would do the appropriate binding - or something even better...
Is there anything out like that? I though of using the MVC DefaultModelBinder, but there would be a good amount of overhead to use it. It would be nice to handle complex types (and lists) that are flattened in a string. What I don't want to do it write specific parsers for each command, as each returns the result in slightly different formats.
Thanks!
(Edit: I would like to move the regex into an attribute on the class, to be able to do an IsMatch on the string. Using groups, I assume I could still bind with the output to the properties.)
Nope, no magic that does it for you there. Better get started! :)
精彩评论