Sunday, April 4, 2010

ASP.net MVC 2.0 Attribute-based Validations using metadata

I have been meaning to publish this for a while. This is a terrific shortcut to quickly create the metadata scaffolding from the Data Access Layer (DAL) created from LINQ2SQL. You will need to download and install Expresso, and be a little familiar with the tool, as well as it will help if you know a bit about regular expressions.

1. Regenerate DAL (I recommend you use SQLMetal).
2. Copy required tables from designer.cs into Expresso regex editor (Test Mode) "test area"
3. Simple find "public (?!e|E|.*\().*" (without the quotes). Then Run Match
(this gets rid of all junk except class name and properties)
4. Take the Match Results and copy-to-clipboard, them paste back into the "sample text" area (REPLACING the existing text from step 2).

5. Now we do a regex find/replace in Expresso.
Go into Design Mode:
Search String: "public (?!partial)[^ ]+ (.+)"
Replace String: (copy the entire string without the quotes, but include the carriage return at the end)
"public object $1 { get; set; }
"
Back to Test Mode and click "Replace"

6. Copy the replaced-text area back into the sample-text (same as step 4)

7. Finally decorate the class and add braces:
Go into Design Mode:
Search String: "public partial class (\w+).*"
Replace String: (copy and paste the entire block below exactly as shown, without the quotes, and including the carriage return at the end.
"}
[Bind(Exclude = "Id")]
[MetadataType(typeof($1MetaData))]
public partial class $1{}
public class $1MetaData
{
"
Back to Test Mode and click "Replace"

8. That's it! copy the final text into a new visual studio "metadata.cs" in the models. You have nice clean scaffolding to add your validation attributes. The [Bind] attribute is a placeholder.

No comments: