Thursday, November 25, 2010

WebFormContrib – Web Forms more like ASP.NET MVC




Lately I’ve been stuck working on projects using Web Forms and after reading one of Jimmy Bogard’s recent blog posts, I was inspired to create a small library similar to MVC Contrib, but for Web Forms. Obviously my little library won't be nearly as good as MVC Contrib because I'm not as talented as the guys at HeadSpring. However, I'm hoping this will be a good start to something great. Anyhow, the main thing that stuck out to me was the strongly-typed views, which I never used to do with Web Forms. With all that said, I thought I’d share what I created.

The project I’m currently working on is built on a 3rd party system and it’s difficult to add 3rd party references into our add-ons. So, I added a very basic validator into this thing, which will most likely be refactored, but works for now.

Onto the code I suppose…

So, first things first, let’s look at my WebForm view, which in this case is a UserControl, but the same thing can be done with a regular aspx Page.

<%@ Control Language="C#" AutoEventWireup="true" Inherits="WebFormContrib.Sample.Core.UI.Model.SampleControl" %>
<%
@ Import Namespace="WebFormContrib.Controls" %>
<%
@ Import Namespace="WebFormContrib.Helpers" %>
<h1>Employee Form</h1>
<%=ErrorMessages.ToList("Important Message").CssClass("err") %>
<div id="success" runat="server" enableviewstate="false" visible="false">Employee saved.</div>
<
p><%=Html<TextBox>(f=>f.FirstName).Label("First Name:<br/>").Width("300px").CssClass("tb") %></p>
<
p><%=Html<TextBox>(f=>f.LastName).Label("Last Name:<br/>").Width("300px") %></p>
<
p><%=Html<TextBox>(f=>f.EmailAddress).Label("Email Address:<br/>").Width("300px") %></p>
<
p>Do you want to receive emails?<br />
<%=Html<YesNoRadioButtonList>(f=>f.ReceiveEmails) %></p>

<
p><%=Html<TextArea>(f=>f.Bio).Width("500px").Label("Bio:<br/>") %></p>

<
asp:Button ID="bSend" runat="server" Text="Save Employee" CausesValidation="true" OnClick="Save" />

There are a few things to notice. First is the fact that there’s no code-behind page. Everything is inherited from my core project, just like I setup my MVC apps. You can see how I do that in this post.

As you can see, this is a total rip-off of the MVC type of HTML page. I left in a couple ASP controls too. There are a couple of controls that didn’t exist before like YesNoRadioButtonList and TextArea. These two objects were added as helpers.

All these extensions that make it look like fluentHtml are just extension methods on string. For example:

public static string Label(this string html, string label)
{
return string.Format("<label for=\"{0}\">{1}</label> {2}", html.GetId(), label, html);
}

So what does the SampleControl look like? It looks like this:

    public class SampleControl : BaseUserControl<EmployeeView>
{
private IEmployeeRepository _repository;
protected void Page_Load(object sender, EventArgs e)
{
_repository =
DI.CreateRepository();

if (Page.IsPostBack)
return;

loadEmployee();
}

private void loadEmployee()
{
var e = _repository.GetBy(Page.User.Identity.Name);
ViewModel =
EmployeeView.MapEmployeeToView(e); //Could user AutoMapper
}

protected void Save(object sender, EventArgs e)
{
if (!Page.IsValid || !ModelIsValid(ViewModel))
return;

var form = ViewModel.MapToEmployee(); //Could user AutoMapper
_repository.Save(form);

C<
HtmlGenericControl>("success").Visible = true;
}
}

This is all there is to my little employee edit user control. You should notice I set the ViewModel to a mapped version of my domain model to my view. In the save, I’m having to call both Page.IsValid and ModelIsValid…although since I don’t have any ASP validators, I could technically just call the ModelIsValid(ViewModel). Other than that, I map back to my domain model from my view model and call save. Then I use a generic control finder built into the BaseUserControl<T> to get my ASP success generic html control. You can also see that I added comments on where you might benefit from AutoMapper with this method.

So my view in this case looks like this:

    public class EmployeeView
{
[
Required("First Name is required.")]
public string FirstName { get; set; }
[
Required("Last Name is required.")]
public string LastName { get; set; }
public string Bio { get; set; }
public string EmailAddress { get; set; }
public bool ReceiveEmails { get; set; }

public Employee MapToEmployee()
{
var employee = new Employee();
employee.Name.FirstName = FirstName;
employee.Name.LastName = LastName;
employee.EmailAddress = EmailAddress;
employee.Biography = Bio;
return employee;
}

public static EmployeeView MapEmployeeToView(Employee employee)
{
var view = new EmployeeView();
view.FirstName = employee.Name.FirstName;
view.LastName = employee.Name.LastName;
view.EmailAddress = employee.EmailAddress;
view.Bio = employee.Biography;
return view;
}
}

The Required attributes are also contained in the WebFormContrib dll. It uses similar syntax to the MVC 2 validators. The BaseUserControl<T> looks like this:

    public class BaseUserControl<TModel> : BaseUserControl where TModel : new()
{
private readonly BaseWebForm<TModel> _baseWebForm;
public BaseUserControl()
{
_baseWebForm =
new BaseWebForm<TModel>();
}

protected IList<string> ErrorMessages
{
get { return _baseWebForm.ErrorMessages; }
}

protected bool DisableAll
{
get { return _baseWebForm.DisableAll; }
set { _baseWebForm.DisableAll = value; }
}

protected TModel ViewModel
{
get
{
try { _baseWebForm.Request = Request; }
catch { }
return _baseWebForm.ViewModel;
}
set { _baseWebForm.ViewModel = value; }
}

protected bool ModelIsValid(TModel view)
{
return _baseWebForm.ModelIsValid(view);
}

protected string Html<TControl>(Expression<Func<TModel, object>> func) where TControl : Control, new()
{
return _baseWebForm.Html<TControl>(func);
}
}

This inherits from a BaseUserControl, which inherits from UserControl and has another method associated that I’ll show later. Basically, this provides all the functionality of BaseWebForm<TModel>, which I will show last. The BaseWebForm<TModel> is the meat of the whole project. The try{} catch{} around the _baseWebForm.Request is only there so my unit tests won’t fail when trying to get the HttpRequest. So the BaseUserControl looks like this:

    public class BaseUserControl : UserControl
{
protected TControl C<TControl>(string id) where TControl : Control
{
return (TControl)FindControl(id);
}
}

Pretty basic stuff here…looks for the control and then casts to the specified type. BasePage<T> and BasePage look exactly the same as these two, except the BasePage inherits from Page instead of UserControl.

Now…BaseWebForm<T> I’m going to breakdown. It inherits from Control and T must allow new().

        internal TModel ViewModel
{
get
{
if (_view != null)
return _view;

_view =
new TModel();

foreach (var property in typeof (TModel).GetProperties())
try
{
if (Request.Form[property.Name] != null)
property.SetValue(_view, Request.Form[property.Name]);
}
catch (NullReferenceException) {}

return _view;
}
set
{
_view =
value;
}
}

First things first…the ViewModel…I loop through the properties of the view model object and pull out the key from Request.Form and then set the value of the property on the _view object. The try {} catch{} here is also for unit testing purposes.

The ModelIsValid looks like this:

       internal bool ModelIsValid(TModel view)
{
ErrorMessages =
new List<string>();
foreach (var property in typeof(TModel).GetProperties())
{
var attributes = property.GetCustomAttributes(typeof(RequiredAttribute), false);
if (attributes.Length > 0)
{
var value = property.GetValue(view, null);
if (value.ToSafeString() == string.Empty)
ErrorMessages.Add(((
RequiredAttribute)attributes[0]).Message);
}
}

if (ErrorMessages.Count == 0)
return true;

return false;
}

This will be the first thing I refactor. The thing I hate most is that the actual validation of the RequiredAttribute happens here instead of in the attribute. However, it works for now. If anyone has any suggestions, please add a comment.

Finally, the Html<TControl> looks like this:

    internal string Html<TControl>(Expression<Func<TModel, object>> func) where TControl : Control, new()
{
var id = func.ToId();
var control = new TControl { ID = id };
control.SetValue(func.Compile().Invoke(ViewModel));

using (var textwriter = new StringWriter())
using (var htmlwriter = new HtmlTextWriter(textwriter))
{
if (DisableAll)
control.Disable();
control.RenderControl(htmlwriter);
return textwriter.ToString();
}
}

This one required TControl to be of type Control and allow new(). I get the Id or PropertyName from func using an extension method and then I create the TControl object. Afterward, I set the value of it from ViewModel then I render it and return the string.

Here are the tests I have:

    [TestFixture]
public class BaseControlTests
{
[
Test]
public void Generic_C_should_return_any_object_by_id_contained_in_user_control_controls()
{
var testcontrol = new TestUserControl();
var textbox = testcontrol.GetTestUsingC<TextBox>("testid");

Assert.That(textbox, Is.TypeOf(typeof (TextBox)));
Assert.That(textbox.ID, Is.EqualTo("testid"));
}
}

public class TestUserControl : BaseUserControl
{
public TestUserControl()
{
Controls.Add(
new TextBox{ID="testid"});
}

public T GetTestUsingC<T>(string id) where T : Control
{
return C<T>(id);
}
}
    [TestFixture]
public class BaseControlTTests
{
[
Test]
public void Html_should_render_html_textbox_with_an_id_of_FirstName()
{
var testcontrol = new TestWebForm();
var textbox = testcontrol.ExposedHtml<TextBox>(f => f.FirstName);

Assert.That(textbox, Is.EqualTo("<input name=\"FirstName\" type=\"text\" id=\"FirstName\" />"));
}

[
Test]
public void Html_should_render_html_literal()
{
var testcontrol = new TestWebForm();
var literal = testcontrol.ExposedHtml<Literal>(x => x.LastName);
Assert.That(literal, Is.EqualTo(""));
}

[
Test]
public void Html_should_render_html_textarea_with_an_id_of_bio()
{
var testcontrol = new TestWebForm();
var textarea = testcontrol.ExposedHtml<TextArea>(x => x.Bio);
Assert.That(textarea, Is.EqualTo("<textarea name=\"Bio\" rows=\"10\" cols=\"20\" id=\"Bio\"></textarea>"));
}

[
Test]
public void ModelIsValid_should_return_false()
{
var testcontrol = new TestWebForm();

Assert.That(testcontrol.ExposedModelIsValid(), Is.False);
}

[
Test]
public void ModelIsValid_should_return_true()
{
var testcontrol = new TestWebForm();

testcontrol.ExposedViewModel.FirstName =
"test";
Assert.That(testcontrol.ExposedModelIsValid(), Is.True);
}

[
Test]
public void ModelIsValid_should_return_false_and_error_message_should_contain_one_record()
{
var testcontrol = new TestWebForm();

Assert.That(testcontrol.ExposedModelIsValid(), Is.False);
Assert.That(testcontrol.ExposedErrorMessages.Count, Is.EqualTo(1));
Assert.That(testcontrol.ExposedErrorMessages[0], Is.EqualTo("First Name is Required."));
}

[
Test]
public void Html_should_return_disabled_objects_if_disableall_is_true()
{
var testcontrol = new TestWebForm();
testcontrol.ExposedDisable =
true;

var textbox = testcontrol.ExposedHtml<TextBox>(f => f.FirstName);
Assert.That(textbox, Is.EqualTo("<input name=\"FirstName\" type=\"text\" readonly=\"readonly\" id=\"FirstName\" disabled=\"disabled\" />"));
}
}

public class TestWebForm : BasePage<TestViewModel>
{
public string ExposedHtml<TControl>(Expression<Func<TestViewModel, object>> func) where TControl : Control, new()
{
return Html<TControl>(func);
}

public bool ExposedModelIsValid()
{
return ModelIsValid(ViewModel);
}

public IList<string> ExposedErrorMessages
{
get { return ErrorMessages; }
}

public TestViewModel ExposedViewModel
{
get { return ViewModel; }
}

public bool ExposedDisable
{
get { return DisableAll;}
set { DisableAll = value; }
}
}

public class TestViewModel
{
[
Required("First Name is Required.")]
public string FirstName { get; set;}
public string LastName { get; set;}
public string EmailAddress { get; set;}
public string Bio { get; set; }
}

Well, that’s it for now. Please let me know what you think. You can download the code here. You can browse it here. You can download the dll here.

Please let me know if you have any suggestions or comments. Have a great day! Thanks for reading!

Happy Thanksgiving!


Shout it

kick it on DotNetKicks.com

Related Posts Plugin for WordPress, Blogger...