Tuesday, December 07, 2010

WebFormContrib – Sample Part 3




This sample on the WebFormContrib mini-framework is on how to do a form post. If you’d like a particular sample on how to do something or if I’m missing something, please leave a comment.

Here’s how…

  1. Create a New Web Site of Use an Existing
  2. Download and reference the WebFormContrib.DLL
  3. Delete the CodeFile=”Default.aspx.cs” Inherits=”_Default” in the <%@ Page area
  4. Delete the actual Default.aspx.cs file attached to the Default.aspx page
  5. Create a new Class in the App_Code folder ( I’m calling mine DefaultPage )
  6. Inherit the DefaultPage from BasePage<SampleEmployeeView>
  7. Create a new Class file called SampleEmployeeView and make it look like this:
public class SampleEmployeeView
{
[
Required("Id is Required.")]
public int Id { get; set; }
[
Required("First Name is Required.")]
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }

//Could use AutoMapper
public static SampleEmployeeView MapEmployeeToView(Employee employee)
{
var view = new SampleEmployeeView();
view.FirstName = employee.Name.FirstName;
view.LastName = employee.Name.LastName;
view.EmailAddress = employee.EmailAddress;
view.Id = employee.Id;
return view;
}

//Could use AutoMapper
public Employee MapToEmployee()
{
var emp = new Employee();
emp.Name.FirstName = FirstName;
emp.Name.LastName = LastName;
emp.EmailAddress = EmailAddress;
emp.Id = Id;
return emp;
}
}

Employee Class & Person Class look like this:

public class Employee
{
public Employee()
{
Name =
new PersonName();
}
public int Id { get; set; }
public PersonName Name { get; set; }
public string EmailAddress { get; set; }
}

public class PersonName
{
public PersonName(){}
public PersonName(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
public string FirstName { get; set; }
public string LastName { get; set; }
}

  1. In the DefaultPage Class create in Step 6, add the following code:

public class DefaultPage : BasePage<SampleEmployeeView>
{
private IRepository rep;
protected void Page_Load(object sender, EventArgs e)
{
rep =
DI.CreateSampleRepository();
if(Page.IsPostBack)
return;

getEmployee();
}

private void getEmployee()
{
//Pass in ID here to load employee into view.
ViewModel = SampleEmployeeView.MapEmployeeToView(rep.GetEmployeeBy(ViewModel.Id));
}

protected void SaveEmployee(object sender, EventArgs e)
{
if (!ModelIsValid(ViewModel))
return;

rep.Save(ViewModel.MapToEmployee());
C<
HtmlGenericControl>("successmsg").Visible = true;
}
}

Notice the ModelIsValid(ViewModel), which checks the validators set on the ViewModel. I considered using Castle Validators, but I preferred to not have any 3rd party references. I sometimes get annoyed when an open-source project has a lot of dependencies on other projects. Anyhow…


  1. Now we need to setup a dummy repository and service locator like this:

public class DI
{
public static IRepository CreateSampleRepository()
{
return new SampleRepository();
}
}

public class SampleRepository : IRepository
{
public Employee GetEmployeeBy(int employeeId)
{
//Get Employee from DB here.
return new Employee {EmailAddress = "test@test.com", Id = 123, Name = new PersonName("John", "Doe")};
}

public void Save(Employee employee)
{
//Save Employee here.
}
}

public interface IRepository
{
Employee GetEmployeeBy(int employeeId);
void Save(Employee employee);
}

  1. And finally the HTML portion of the site…the “cool” part:

<%@ Page Language="C#" AutoEventWireup="true"  Inherits="DefaultPage" %>
<%
@ Import Namespace="WebFormContrib.Helpers" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<
html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title></title>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
div id="successmsg" runat="server" enableviewstate="false" visible="false">Saved Successfully.</div>
<%=ErrorMessages.ToList("Important Message") %>
<p><%=Html<TextBox>(f=>f.FirstName).Label("First Name:<br/>") %></p>
<
p><%=Html<TextBox>(f=>f.LastName).Label("Last Name:<br/>") %></p>
<
p><%=Html<TextBox>(f=>f.EmailAddress).Label("Email Address:<br/>") %></p>
<
p><%=Html<HiddenField>(f=>f.Id) %></p>
<
p><asp:Button ID="bSave" runat="server" Text="Save" OnClick="SaveEmployee" /></p>
</
div>
</
form>
</
body>
</
html>

Finished view should look like this:

image

Download the sample project here.

Please comment if you have any questions or suggestions. Thanks for reading!

Shout it

kick it on DotNetKicks.com

Saturday, December 04, 2010

WebFormContrib – Sample Part 2




This sample on the WebFormContrib mini-framework is a mixture of a form post and viewing an item. If you’d like a particular sample on how to do something or if I’m missing something, please leave a comment.

Down to the code…

  1. Create a New Web Site of Use an Existing
  2. Download and reference the WebFormContrib.DLL
  3. Delete the CodeFile=”Default.aspx.cs” Inherits=”_Default” in the <%@ Page area
  4. Delete the actual Default.aspx.cs file attached to the Default.aspx page
  5. Create a new Class in the App_Code folder ( I’m calling mine DefaultPage )
  6. Inherit the DefaultPage from BasePage<SampleDataView>
  7. Create a new Class file called SampleDataView and make it look like this:
public class SampleDataView
{
public SampleDataView()
{
Employees =
new List<Employee>();
SelectedEmployee =
new Employee();
}
public IList<Employee> Employees { get; set; }
public Employee SelectedEmployee { get; set; }
public string SelectedEmployeeEmailAddress { get; set; }
}

My Employee class looks like this:

public class Employee
{
public Employee(){}
public Employee(string firstName, string lastName, string email)
{
FirstName = firstName;
LastName = lastName;
Email = email;
}

public string DisplayName {get { return FirstName + " " + LastName;}}
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}

  1. In the DefaultPage Class create in Step 6, add the following code:

public class DefaultPage : BasePage<SampleDataView>
{
private IRepository rep;
protected void Page_Load(object sender, EventArgs e)
{
rep =
DI.CreateSampleRepository();
initializePage();
}

private void initializePage()
{
ViewModel.Employees = rep.GetAllEmployeesResult;
}

protected void getEmployee(object sender, EventArgs e)
{
ViewModel.SelectedEmployee = rep.GetEmployeeBy(ViewModel.SelectedEmployeeEmailAddress);
}
}
  1. Create the IRepository Interface and a new DI Class that look like these:
public interface IRepository
{
IList<Employee> GetAllEmployeesResult { get; }
Employee GetEmployeeBy(string emailAddress);
}
public class DI
{
public static IRepository CreateSampleRepository()
{
return new SampleRepository();
}
}
  1. Let’s implement the IRepository real quick with a Class called SampleRepository. Looks like this:
public class SampleRepository : IRepository
{
public IList<Employee> GetAllEmployeesResult
{
get
{
var list = new List<Employee>();
list.Add(
new Employee("John", "Smith", "john@test.com"));
list.Add(
new Employee("Cindy", "Sue", "sue@test.com"));
list.Add(
new Employee("Speed", "Racer", "speed@test.com"));
list.Add(
new Employee("Joan", "Arc", "joan@test.com"));
return list;
}
}
public Employee GetEmployeeBy(string emailAddress)
{
return GetAllEmployeesResult.SingleOrDefault(x => x.Email == emailAddress);
}
}
  1. Now we get to see the fun part, the HTML code :)
<%@ Page Language="C#" AutoEventWireup="true" Inherits="DefaultPage" %>
<%
@ Import Namespace="WebFormContrib.Helpers" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<
html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title></title>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<%=Html<DropDownList>(f=>f.SelectedEmployeeEmailAddress)
.Options(ViewModel.Employees, f=>f.DisplayName, f=>f.Email)
.Selected(ViewModel.SelectedEmployeeEmailAddress)
%>
<asp:Button ID="bLoadEmployee" runat="server" Text="Display Employee" OnClick="getEmployee" />

<
p>Selected Employee:<br />
Email <
strong><%=ViewModel.SelectedEmployee.DisplayName %></strong> at <%=ViewModel.SelectedEmployee.Email %></p>
</
div>
</
form>
</
body>
</
html>

You will notice the new DropDownList with Options and Selected extension methods. The Options extension has 2 other overloads that accepts the IEnumerable<string> or IEnumerable<ListItem> so you don’t have to specify the datafield and valuefield. The Selected extension gets the value of what needs to be selected after the postback or during an initial load.

When you run the app, you should see this:

image

After clicking Display Employee:

image

Download the sample project here.

Please comment if you have any questions or suggestions. Thanks for reading!


Shout it

kick it on DotNetKicks.com

Thursday, December 02, 2010

WebFormContrib – Sample Part 1




After using the WebFormContrib mini-framework the past couple weeks, I’ve grown to really like it. I thought I’d share some of the ways I’m using it in hopes that you might benefit from it too.

This first sample is on how to show data on a page and not have to worry about any of the form elements. We will also not use any asp.net controls like gridviews, literals, or labels. So, here we go using Visual Studio 2008…

  1. Create a New Web Site or Use an Existing
  2. Download and reference the WebFormContrib DLL
  3. Delete the CodeFile="Default.aspx.cs" Inherits="_Default" in the <%@ Page area
  4. Delete the actual ….aspx.cs
  5. Create a new Class file in the App_Code folder ( I called mine DefaultPage)
  6. Inherit the DefaultPage from BasePage<SampleDataView>
  7. Create a new Class file called SampleDataView and make it look like this:
public class SampleDataView
{
public SampleDataView()
{
Employees =
new List<Employee>();
}
public string DepartmentName { get; set; }
public IList<Employee> Employees { get; set; }
public int TotalEmployees { get { return Employees.Count; } }
}

The above class is just made up of some practical things that your view might contain. My Employee class just looks like this:

public class Employee
{
public Employee(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}

public string FirstName { get; set; }
public string LastName { get; set; }
}

  1. Back in the DefaultPage Class that we created in Step 6, add the following code:

public class DefaultPage : BasePage<SampleDataView>
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
return;

initializePage();
}

private void initializePage()
{
//this is where you'd call your repository and possibly automapper to map from your domain model to your view model
ViewModel.DepartmentName = "Sample Department";
ViewModel.Employees.Add(
new Employee("John", "Smith"));
ViewModel.Employees.Add(
new Employee("Cindy", "Sue"));
ViewModel.Employees.Add(
new Employee("Speed", "Racer"));
ViewModel.Employees.Add(
new Employee("Joan", "Arc"));
}
}

  1. Now we can setup our view in the Default.aspx page like this:

<%@ Page Language="C#" AutoEventWireup="true" Inherits="DefaultPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<
html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title>WebFormContrib Sample Part 1</title>
</
head>
<
body>
<
form id="form1" runat="server">
<h3><%=ViewModel.DepartmentName %></h3>
<
p>Total Employees: <%=ViewModel.TotalEmployees %></p>
<
ul>
<% foreach (var employee in ViewModel.Employees) {%>
<li><%=employee.FirstName %> <%=employee.LastName %></li>
<% }%>
</ul>
</form>
</
body>
</
html>

As you can see, it looks pretty much exactly like MVC and it allows you to keep complete control of your HTML. When you run your app, you should see this:

image

Download the sample project here.

Please comment if you have any questions or suggestions. Thanks for reading!


Shout it

kick it on DotNetKicks.com

Related Posts Plugin for WordPress, Blogger...