Posts Tagged 'Data Annotations'

Creating and Publishing NuGet Packages

NuGet is one of those tools that gets more and more important all the time. A while back, it was useful for adding small, specialized packages for particular projects. Nowadays, it’s fundamental – and going to be even more so when vNext is live. We all use it to add packages, but how difficult is it to create and publish our own packages? As it turns out, not very difficult at all.

I’d been meaning to turn my data annotation validator into a NuGet package for some time – and today, I finally did something about it. This is how you do it:

1. Get nuget.exe

Go to or and download nuget.exe. Once you’ve got it, save it somewhere nice and easy because you’re going to need to….

2. Add it to the path

Right click on ‘computer’ in windows explorer, select ‘properties’ and then ‘advanced system settings’. Then click on ‘Environment Variables’ in the dialog.

In the Environment Variables dialog, find the Path variable and click Edit.

In the next dialog, add a semi-colon at the end and then put in the full path to nuget.exe (in my case that was c:\Nuget):







3. Create a Nuspec file.

This is a little XML config/specification file used in packaging, and you generate it from the command line. Open a command window, navigate to the folder where you have your Visual Studio project file and type in:

Nuget spec

This, of course, is why you wanted nuget in the path. Nuget.exe will now generate the XML file using your assembly settings, and placing default text where it doesn’t have info. Here’s a raw one:

And here’s one that’s been edited:

4. Pack it ready for publishing

This is again done using the command line, adding an argument to tell it to package the release version, not the default (which is probably debug). I’ve put brackets around the part that you would need to replace with your own package:

nuget pack [DataAnnotationValidator.csproj] -Prop Configuration=Release

The result is another file, this time with the extension nupkg.

5. Publish it to Nuget

That means first you have to go there and sign up – which is all very straight-forward. Once you’re signed up and you’ve clicked on the link in the confirmation email, you will have an API key on your profile page, and that allows you to publish your package. Get your key and then run the following in your command window:

nuget setApiKey [key from profile page]

That means you won’t have to put in your key every time. Now go to the Upload Package page and browse for your nupkg file:


It asks you to verify the details….


And then that’s it – your package is online and available for download.


I installed the package to test it, and the config file was updated….


the reference was added…..


and the dll was in the bin directory:


And that allowed me to add the control to the toolbox and use it as part of my project:


Obviously, there’s a lot more you can do with NuGet – like adding support for multiple frameworks – and I may well look at some of the options in a future post.

Kevin Rattan

For other related information, check out these courses from Learning Tree:

Building ASP.NET Web Applications: Hands-On

Building Web Applications with ASP.NET MVC

Dynamic Data and Web Forms – Part Three

This is the third in a series of posts looking at how to integrate Dynamic Data features into an ASP.NET Web Forms website – and hence take advantage of automated client-side data annotation validation. In the last post, I showed how to connect a label to a dynamically generated TextBox using some complicated data binding code:

It works, but it’s hardly practical. Fortunately, Dynamic Data allows you to create custom templates – and that offers a much more practical solution connecting labels to our UI controls.

Dynamic Data uses conventional names and locations, so the first thing we need to do is add a new folder structure to our Web site – a DynamicData folder, with a nested FieldTemplates folder.

Next, right click on the FieldTemplates folder, select Add New Item and pick Dynamic Data Field:

Name it appropriately – in this case, I went with LabelMapper, and the wizard generated two .ascx controls for me, LabelMapper.ascx and LabelMapper_Edit.ascx:

The first version is read only, and contains a literal control (don’t worry about the red underlining – it compiles and runs despite Visual Studio not being entirely happy):

And here is the edit version:

It’s simplicity itself to connect this to our dynamic controls via the UIHint attribute. Assign the name of the .ascx control as the value of the UIHint attribute, and Dynamic Data will automatically look inside the FieldTemplates folder under the Dynamic Data folder for the matching files.

Notice that I’ve also removed not only my label, but also the default scaffolded text explaining that this is the “from” field. That’s because we’re about to customize the template so that it autogenerates the label.

The first task is to drag a label into the template, and associate it with the TextBox:

Then we need to set the text. The obvious choice for this is the name of the property we’re binding to  (customizable as DisplayName via Data Annotations if the original property name  is unsuitable, e.g. combines two words into one). This information is available as Column.DisplayName inside the Dynamic Data Field:

Now when we run the page, we get labels properly associated with the controls:

But there’s still a problem. The Message field should be a TextArea, not a simple TextBox. We don’t want to have to create a whole separate template for that – and we don’t have to. Simply add a public TextBoxMode property to the template’s code behind, with a default value of SingleLine:

Then add a TextMode attribute to the TextBox and bind the value to the property:

And then set the value as an attribute of the Dynamic Control:

And now we have dynamically generated controls that respect data annotations and generate the controls we want via a couple of simple attribute settings:

And the best thing is – now that we’ve created the template, we can reuse it any time we use Dynamic Data controls with standard Data View controls, and get the benefits of dynamic control generation along with well formed, accessible HTML.

Kevin Rattan

For other related information, check out these courses from Learning Tree:

Building ASP.NET Web Applications: Hands-On

Dynamic Data and Web Forms – Part Two

In my last post, I showed how you can use Dynamic Data with the FormView and similar controls to autogenerate UI controls and associated validation based on data annotations. The one downside was that the scaffolded HTML is horrible – and fixing it is nowhere near as easy as you might hope.

This is some of the markup generated by the wizard in Visual Studio:

This is what the output looks like – notice the horrible ragged edge and the use of inaccessible LinkButtons:

And this is a snippet from generated HTML:

So – we have text where we should have a label, making our page both inaccessible and less functional than it should be, and we have a link button where should have a submit button. We can fix the button just by changing the type, and we can fix the ragged edge by adding in extra line breaks. But it turns out that the labels are much more of a problem than they might at first appear.

First, let’s try adding a label and pointing it at the dynamic control:

That looks like it ought to work… And at first sight, the generated Web page looks a lot better when we run it. The label is now on a separate line from the TextBox, and the styling shows that it is truly is a label control, and not just text:

Unfortunately, it’s not as good as it seems at first glance. A look at the HTML source shows that this label is not properly connected to its TextBox: the for and the id do not match.

The usual fix in these circumstances is to switch to static client side ids. So let’s try replacing our ASP.NET label with a simple HTML label, and setting the dynamic control to have a static ClientIDMode:

Here’s what we get when we run it:

Okay – so let’s try harder by setting the ClientIDMode of the FormView itself to Static and see if that will do the trick…

Unfortunately, that doesn’t help either – though, refreshingly, the problem is different:

Fundamentally, the problem is that the DynamicControl is a container. We need the label to be associated with the TextBox inside the DynamicControl.

First, let’s get rid of those Static ClientIDMode values, as we can’t have every TextBox with the id TextBox. Then let’s see if we can bind the value of the for attribute to the ClientID property of the control. We have to do a bit of digging to get there, as the TextBox is inside a FieldTemplate which is inside the DynamicControl, which is inside the FormView:

And this is the output HTML:

Finally, we have a winner. Except for the fact that Dynamic Data is supposed to simplify the generation of the UI, and there is nothing remotely simple about having to add labels with custom data binding code that includes nested FindControl() methods.

Fortunately, our quest for automated client side data annotation validation does not end there – because it’s possible to customize the templates for DynamicControls, and that offers a much more practical and satisfying solution to the problem of poor scaffolding. And that will be the subject of my next blog post.

Kevin Rattan

For other related information, check out these courses from Learning Tree:

Building ASP.NET Web Applications: Hands-On

How to Use ViewModels Without Sacrificing Encapsulation

I have been using ASP.NET MVC extensively over the past year, and the more I use it, the more I like it. However, there remain a couple of things that bug me. One is the fact that the built-in validation doesn’t work with repeating forms. The other is the “best practice” of placing Data Annotations on a ViewModel class.

For me, validation rules belong on the business object itself, not on the ViewModel. One of the key benefits of encapsulation is that we reduce code duplication. If we don’t encapsulate the validation rules inside the object, then we are doomed to repeat them once for every presentation layer. Data Annotations in an MVC ViewModel are not available to a WPF UI. Not only does this lead to redundancy, it increases the risk of inconsistencies cropping up between UI.

So no problem, you might think. All we have to do is add the Data Annotations to the Model itself, and then add the Model as a property of the ViewModel.

Okay, let’s try that.

Here is the Model:

BasicClass simple C# class

And here is the ViewModel:

The ViewModel class

This looks straightforward enough. But look at what happens when we ask Visual Studio to scaffold the View:

View scaffolding

What happened to our “Basic” Model property? It’s not there. The scaffolding only seems to work for simple properties.

Okay, so let’s add the details of the Model to the View. In fact, let’s cheat. We’ll get Visual Studio to scaffold the inner Model for us. First we’ll create a throwaway View. Then we copy the contents of the form and paste it into the View that’s typed to the ViewModel. All we have to do then is change the lambda expressions to point at model.Basic rather than just model:

Full scaffolding

Problem solved. The View now contains the data we need and also respects our data annotations…

This means we can pass the ViewModel through to a Controller method and pick up the Model we need via the ViewModel’s “Basic” property. There’s only one problem:  How do we use the UpdateModel() method when we’re only interested in a property on the object passed to the method, rather than the whole object? Fortunately, Microsoft anticipated the need and there’s an overload on UpdateModel() that allows us to specify a prefix. In this case, not surprisingly, the HTML helpers have inserted the prefix “Basic”:

UpdateModel() with second argument

As you can see, the Model has successfully been bound, so we now have a mechanism for taking advantage of ViewModels without sacrificing encapsulation.

Kevin Rattan

For related information, check out Building Web Applications with ASP.NET MVC from Learning Tree.

Learning Tree International

.NET & Visual Studio Courses

Learning Tree offers over 210 IT training and Management courses, including a full curriculum of .NET training courses.

Free White Papers

Questions on current IT or Management topics? Access our Complete Online Resource Library of over 65 White Papers, Articles and Podcasts

Enter your email address to subscribe to this blog and receive notifications of new posts by e-mail.

Join 29 other followers

Follow Learning Tree on Twitter


Do you need a customized .NET training solution delivered at your facility?

Last year Learning Tree held nearly 2,500 on-site training events worldwide. To find out more about hosting one at your location, click here for a free consultation.
Live, online training

%d bloggers like this: