Showing posts with label AutoMapper. Show all posts
Showing posts with label AutoMapper. Show all posts

Friday, April 15, 2011

ASP.NET MVC 3 Sample Project Launched




Okay, after popular demand of I think 0 people, I’ve published my old demo MVC 1 project as an MVC 3 project. If you haven’t read any of the posts on the last demo project, check out this post. This project completely separates UI & C# code, so you only have 2 projects (Core & UI…not counting the Unit Tests project).

Basically, all I did was create a new MVC 3 project using Razor with Microsoft’s default template and deleted everything except the following:

  • Views folder
  • Root Default.aspx
  • global.asax (I did delete the global.asax.cs)
  • both web.configs

I referenced my Core, setup my views that match my Core project, and inherited from my global.cs in the global.asax. That was it!

You can download it via zip here: http://code.google.com/p/derans/downloads/list (the file is called DemoPhotographySite_v3.zip)

I feel like this project will act as a great stepping stone to understanding the Code Camp server, which is much more complex.

The sample project was built with the following tools:

If you downloaded the old one, you’ll notice that I removed the following 3rd parties:

The primary reason I removed these three parties is because MVC 3 and Razor are good enough so you don’t need the 3rd party tools.

The best practices I mentioned above come straight from experience and the following people/resources:

You can see the exact same Core code in use at sweetandhappy.com. If you see any improvements that can be made or you’d just like to comment, please do so!

Also, please note that I basically am even re-posting the exact same blog post I did over a year ago with my original MVC demo project. I hope you don’t mind, but it’s late and I have to work tomorrow :)

Thanks for reading!

Shout it

kick it on DotNetKicks.com

Thursday, January 28, 2010

Linq to Sql Generic Repository with AutoMapper




We, my teammates and I, have been playing with creating a generic repository for Linq to Sql using AutoMapper. We haven’t used it in production or anything, but I figured I’d blog about it and see if anyone has any comments about it. It’s fun just to toy around sometimes.

A couple of posts ago, I blogged about Func<> and that’s going to play an important part in what I’m about to show you. So basically we started off coding what we would do without generics and then converted that into a generic method. The ending interface looks like this:

public interface ILinq2SqlRepository<TDataContext, TDomainModel, TLinqModel>
where TDataContext : DataContext
{
IList<TDomainModel> GetAll(Func<TDataContext, IQueryable<TLinqModel>> func);
TDomainModel GetById(
Func<TDataContext, TLinqModel> func);
void Save(TDomainModel model, Func<TDataContext, TLinqModel> func);
}

So there is the GetAll and the GetById methods. I’m also working on the Save, but it’s a little more tricky because I believe there’s a bug in Linq to Sql Attach(entity, original) when the primary key is a Guid, but that’s just me :) My Save method right now keeps returning a cannot insert duplicate key error and I’ve Googled it, but to no avail. I’m also not sure how to handle the using(DataContext)…just know it’s a work in progress! Anyhow…


The implementation looks like this:

public class Linq2SqlRepository<TDataContext, TDomainModel, TLinqModel> 
:
ILinq2SqlRepository<TDataContext, TDomainModel, TLinqModel>
where TDataContext: DataContext
{
private readonly TDataContext DataContext;

public Linq2SqlRepository(TDataContext dataContext)
{
DataContext = dataContext;
}

public IList<TDomainModel> GetAll(Func<TDataContext, IQueryable<TLinqModel>> func)
{
var list = Mapper.Map<TLinqModel[], TDomainModel[]>(func.Invoke(DataContext).ToArray());
return list.ToList();
}

public TDomainModel GetById(Func<TDataContext, TLinqModel> func)
{
return Mapper.Map<TLinqModel, TDomainModel>(func.Invoke(DataContext));
}

public void Save(TDomainModel model, Func<TDataContext, TLinqModel> func)
{
using (DataContext)
{
var original = func.Invoke(DataContext);
var entity = Mapper.Map<TDomainModel, TLinqModel>(model);
DataContext.GetTable(
typeof(TLinqModel)).Attach(entity, original);
DataContext.SubmitChanges();
}
}
}

Well here’s the base implementation and it looks a lot easier if you have a good understanding of .Net generics. You can see the common AutoMapper Mapper.Map<> method in there, which is what we’re using to do the left to right mapping and basically we’re just passing in simple Linq commands. So we still have to do our AutoMapper configuration, but my hope is that maybe this post will strike up a good idea in someone else’s head…hopefully!


I thought it’d work best to implement this into a repository by just setting it as a private field like this:

public class SampleRepository : IRepository<DomainPerson>
{
private readonly ILinq2SqlRepository<SampleDataContext, DomainPerson, DataPerson> _repository;
public SampleRepository(string connstring)
{
_repository =
new Linq2SqlRepository<SampleDataContext, DomainPerson, DataPerson>(
new SampleDataContext(connstring));
}

public IList<DomainPerson> GetAll()
{
return _repository.GetAll(x => x.DataPeople);
}

public DomainPerson GetById(Guid id)
{
return _repository.GetById(x => x.DataPeople.SingleOrDefault(y => y.Id == personId));
}

public void Save(DomainPerson person)
{
_repository.Save(person, x => x.DataPeople.SingleOrDefault(y => y.Id == person.Id));
}
}

I went the inheritance route and didn’t really care for it, mainly because it was much uglier in the implementation. So you’ll notice this inherits from a generic IRepository, which could’ve been IDomainPersonRepository that inherits from the generic or was just a plain ole repository. Anyhow, it looks like this:

    public interface IRepository<T>
{
IList<T> GetAll();
T GetById(
Guid id);
void Save(T model);
}

I wanted to show prettier things in the public side of the API like GetById with just Guid instead of pass me an ugly lambda :) (Even though I love the lambdas, a lot of devs don’t care for them) So the users of this API would just reference the IRepository<T>, but I’d actually probably end up renaming to a friendlier name like this:

    public interface IDomainPersonRepository : IRepository<DomainPerson> {}

Then I’d go ahead and inherit my SampleRepository from IDomainPersonRepository…I should really plan these posts out more than I do before typing them so the post is better structured. As I get more practice in, I’ll try to do that for you!


So that’s my thinking on some type of generic repository for Linq to Sql with AutoMapper. Please keep in mind that this was a fly by thing we came up with this afternoon and I thought it was pretty cool. It could definitely use more testing & refactoring!


Let me know if you have any thoughts, questions, or comments.


Thanks for reading!


Shout it

kick it on DotNetKicks.com

Wednesday, January 27, 2010

Security Questions with ASP.NET MVC & fluentHtml




Have you ever needed to create a screen to ask a user to select security questions? Well, I recently had to create this screen and I thought I’d share the experience.

I guess I’ll start with the view model.

public class CreateSecurityQuestionsView
{
public IList<SelectListItem> QuestionList
{
get { return DI.SecurityQuestionService().GenerateSecurityQuestions(); }
}

[
ValidateNonEmpty("Username was not found")]
public string Username { get; set; }




[
ValidateNonEmpty("")]
[
ValidateNotSameAs("SecondQuestionId", "Question 1 = Question 2")]
[
ValidateNotSameAs("ThirdQuestionId", "Question 1 = Question 3")]
public string FirstQuestionId { get; set; }

[
ValidateNonEmpty("Answer 1 is Required")]
public string FirstAnswer { get; set; }

[
ValidateNonEmpty("")]
[
ValidateNotSameAs("FirstQuestionId", "Question 2 = Question 1")]
[
ValidateNotSameAs("ThirdQuestionId", "Question 2 = Question 3")]
public string SecondQuestionId { get; set; }

[
ValidateNonEmpty("Answer 2 is Required")]
public string SecondAnswer { get; set; }

[
ValidateNonEmpty("")]
[
ValidateNotSameAs("FirstQuestionId", "Question 3 = Question 1")]
[
ValidateNotSameAs("SecondQuestionId", "Question 3 = Question 2")]
public string ThirdQuestionId { get; set; }

[
ValidateNonEmpty("Answer 3 is Required")]
public string ThirdAnswer { get; set; }
}

So my view has a QuestionList, which gets all the questions for the end-user to select. I’ll populate the dropdownlists with this property in a bit. I used the goodsecurityquestions.com website to gather my questions and I’m using 15 in the selection. The other properties are pretty standard and the validation attributes are Castle Validators. I’m not a fan of the way the ValidateNotSameAs worked out for me, but it does the job.


Okay, let’s take a look at the HTML.

<%=Html.DivValidationSummary("All three questions are required and should be unique")%>
<form action="/Account/CreateSecurityQuestions/" method="post" id="step5form">
<
fieldset>
<
legend>Create Security Questions</legend>
<
p><%=this.Select(f => f.FirstQuestionId)
.Options(Model.QuestionList)
.Label(
"Security Question 1: ")
.Selected(Model.FirstQuestionId)
%></p>

<
p><%=this.TextBox(f => f.FirstAnswer).Label("Answer 1: ")%></p>

<
p><%=this.Select(f => f.SecondQuestionId)
.Options(Model.QuestionList)
.Label(
"Security Question 2: ")
.Selected(Model.SecondQuestionId)
%></p>

<
p><%=this.TextBox(f => f.SecondAnswer).Label("Answer 2: ")%></p>

<
p><%=this.Select(f => f.ThirdQuestionId)
.Options(Model.QuestionList)
.Label(
"Security Question 3: ")
.Selected(Model.ThirdQuestionId)
%></p>

<
p><%=this.TextBox(f=>f.ThirdAnswer).Label("Answer 3: ") %></p>
<%=this.Hidden(f=>f.Username) %>
<%
=Html.AntiForgeryToken() %>
<div style="text-align: right"><%=Html.SubmitButton("Finish", "sb", "S") %></div>
</
fieldset>
</
form>

So you can see here, I’m using fluentHtml and  you can see the view model from above spread all through the markup. You should notice the Model.QuestionList three different times in the above markup in the Options() for the Select(). In order to use fluentHtml, you’ll need to inherit from the MvcContrib.FluentHtml.ModelViewPage<TModel>. I plan on doing a post on fluentHtml soon, which will go through the configuration and usage…etc.


The controller is really basic and looks like this:

[AcceptVerbs(HttpVerbs.Post), ValidateModel(typeof(CreateSecurityQuestionsView)), ValidateAntiForgeryToken]
public ActionResult CreateSecurityQuestions(CreateSecurityQuestionsView securityQuestionsView)
{
if (!ModelState.IsValid)
return View("Step5", securityQuestionsView);

_registrationService.CreateSecurityQuestions(
Mapper.Map<CreateSecurityQuestionsView, AccountInformation>(securityQuestionsView));

return RedirectToAction("Summary");
}

Alrighty, so the CreateSecurityQuestions action is post only, it uses the ValidateModel filter that I got from CodeCampServer (I think), and it uses the ValidateAntiForgeryToken. You can read more about the ValidateAntiForgeryToken on Phil Haack’s post. Obviously the action accepts the CreateSecurityQuestionsView and then it checks to verify the ModelState is valid, if not, it returns the view. Then I’m using AutoMapper to map the view model to my AccountInformation object and then I redirect to the summary action. The _registrationService is passed into the controller via the constructor.


I did consider doing a loop on the security questions and answers, but I thought the most I’d ever have is 5 in the view and as long as it’s not a set number in my domain I’m alright with it. Basically, what I’m saying is don’t put securityQuestion1, 2, 3 etc in your domain model, allow it to grow to how many ever security questions your end-user wants to answer. The reason we’re using three is because we require our registered users to answer three and then they can add more later once they’ve completed the registration process.


I think that about covers everything. Please comment if you’d like more details on anything.


Thanks for reading!


Shout it

kick it on DotNetKicks.com

Wednesday, January 20, 2010

Diving a Little Deeper into AutoMapper Part 2




Okay, so what I’m going to do in this post is actually do the opposite of what I did in the last post. This method is actually a better practice because you would go from domain model to view model. I’ll be using the same domain & view model from Part 1.

So, let’s dive in…here is my DomainToViewProfile:

public class DomainToViewProfile : Profile
{
public const string NameOfProfile = "DomainToViewProfile";
protected override string ProfileName
{
get { return NameOfProfile; }
}

protected override void Configure()
{
CreateMaps();
}

private void CreateMaps()
{
CreateMap<Person, PersonView>()
.ForMember(dest => dest.Gender, opts => opts.MapFrom(src =>
src.Demographics.Gender))
.ForMember(dest => dest.BirthDate, opts => opts.MapFrom(src =>
src.Demographics.BirthDate))
.ForMember(dest => dest.Ethnicity, opts => opts.MapFrom(src =>
src.Demographics.Ethnicity))
.ForMember(dest => dest.HomePhoneNumber, opts => opts.MapFrom(src =>
src.ContactInfo.HomePhoneNumber))
.ForMember(dest => dest.MailingAddressCity, opts => opts.MapFrom(src =>
src.ContactInfo.MailingAddress.City))
.ForMember(dest => dest.MailingAddressPostalCode, opts => opts.MapFrom(src =>
src.ContactInfo.MailingAddress.PostalCode))
.ForMember(dest => dest.MailingAddressState, opts => opts.MapFrom(src =>
src.ContactInfo.MailingAddress.State))
.ForMember(dest => dest.MailingAddressStreetLine, opts => opts.MapFrom(src =>
src.ContactInfo.MailingAddress.StreetLine));
}
}

Okay, so obviously this one is MUCH more basic than going the other route. You’ll notice that I didn’t have to map the ContactInfoEmailAddress because AutoMapper is smart enough to map it based on the naming convention.


AutoMapper also knows to map things like GetWhatever() to flattened views like the GetAge() on the Demographics class is not mapped above, but it is mapped! Very cool!


Another interesting thing is that I didn’t have to map PersonName or Gender AND I don’t have a converter for either of them…so what does AutoMapper do? It calls the ToString()…pretty smart AutoMapper!


On to the tests! I setup the fixturesetup and all that like I did in Part 1, so I won’t re-paste it here.


So first thing I tested was the demographics mapping and it looks like this:

        [Test]
public void personview_demographics_should_equal_person_demographics()
{
var person = new Person();
person.Demographics.Gender =
Gender.Male;
person.Demographics.BirthDate =
new DateTime(1990, 1, 1);
person.Demographics.Ethnicity =
"Klingon";
var personview = Mapper.Map<Person, PersonView>(person);

Assert.AreEqual(personview.Gender, "Male");
Assert.AreEqual(personview.BirthDate, person.Demographics.BirthDate);
Assert.AreEqual(personview.Ethnicity, person.Demographics.Ethnicity);
Assert.AreEqual(personview.DemographicsAge, 20);
}

Then person name like this:

        [Test]
public void personview_name_should_equal_person_name()
{
var person = new Person();
person.PersonName =
new PersonName {FirstName = "John", MiddleName = "Test", LastName = "Smith"};

var personview = Mapper.Map<Person, PersonView>(person);

Assert.AreEqual(person.PersonName.ToString(), personview.PersonName);
}

And finally address like this:

[Test]
public void personview_address_should_equal_person_address()
{
var person = new Person();
person.ContactInfo.MailingAddress.StreetLine =
"1234 Test St.";
person.ContactInfo.MailingAddress.City =
"Testville";
person.ContactInfo.MailingAddress.State =
"TX";
person.ContactInfo.MailingAddress.PostalCode =
"12345-1234";
person.ContactInfo.EmailAddress =
"test@test.com";
person.ContactInfo.HomePhoneNumber =
"123-456-7890";

var personview = Mapper.Map<Person, PersonView>(person);

Assert.AreEqual(personview.ContactInfoEmailAddress, person.ContactInfo.EmailAddress);
Assert.AreEqual(personview.HomePhoneNumber, person.ContactInfo.HomePhoneNumber);
Assert.AreEqual(personview.MailingAddressStreetLine, person.ContactInfo.MailingAddress.StreetLine);
Assert.AreEqual(personview.MailingAddressCity, person.ContactInfo.MailingAddress.City);
Assert.AreEqual(personview.MailingAddressState, person.ContactInfo.MailingAddress.State);
Assert.AreEqual(personview.MailingAddressPostalCode, person.ContactInfo.MailingAddress.PostalCode);
}

It’s funny because typically I think on Part 2 of a two part lesson the second part would be more difficult…apparently that’s not how I operate :)


So there you have it…AutoMapper from domain model to view model. Good stuff!


Thanks for reading!


Shout it

kick it on DotNetKicks.com

Diving a Little Deeper into AutoMapper Part 1

Disclaimer When reading this post, please keep in mind that there are much better ways to handle what you're about to read and the sole purpose of this post is to give you examples of how to map to different types of objects with AutoMapper and it is not a best practice or implementation post





Everytime I use AutoMapper, I think this is such an awesome tool! I think it’s hilarious to go back and read my first post in April where it states, “Now automapper is one thing I'm not sure I'll benefit from yet.” and I go on to say, “I'm pretty confident that I will eventually slap myself in the face for posting this just because I'm sure it is an awesome tool that I will one day see as VERY cool, but right now...I don't”. Well, I’m slapping myself :)

So let’s dive into some awesomeness that is AutoMapper. If you haven’t read the AutoMapper – ASP.NET MVC post or downloaded Jimmy’s sample code or have any understanding of AutoMapper, you might want to read one of those items first because they will help you understand how to setup AutoMapper.

Okay, so I have this basic Domain Model:

image

I want to map it to this View Model:

image

Notice the view model is flattened out completely and ignores a few properties. Alright, let’s get to the code!

Here is my ViewToDomainProfile:

    public class ViewToDomainProfile : Profile
{
public const string NameOfProfile = "ViewToDomainProfile";
protected override string ProfileName
{
get { return NameOfProfile; }
}

protected override void Configure()
{
CreateMaps();
}

private void CreateMaps()
{
CreateMap<
string, Gender>().ConvertUsing<GenderConverter>();

CreateMap<
PersonView, Demographics>()
.ForMember(dest => dest.NationalId, opts => opts.Ignore());

CreateMap<
PersonView, ContactInfo>()
.ForMember(dest => dest.MailingAddress, opts => opts.ResolveUsing<
AddressResolver>())
.ForMember(dest => dest.EmailAddress, opts =>
opts.MapFrom(src => src.ContactInfoEmailAddress));

CreateMap<
PersonView, Person>()
.ForMember(dest => dest.ContactInfo, opts =>
opts.MapFrom(
Mapper.Map<PersonView, ContactInfo>))
.ForMember(dest=>dest.Demographics, opts=>opts.MapFrom(
Mapper.Map<PersonView, Demographics>))
.ForMember(dest => dest.PersonName, opts => opts.ResolveUsing<
PersonNameResolver>());
}
}

There are a few new techniques in here that I’ve never gone over.


First this:

CreateMap<string, Gender>().ConvertUsing<GenderConverter>();

What this says is that anytime you try to go from a string to a Gender Enum, use this class to convert it. The GenderConverter class looks like this:

    internal class GenderConverter : ITypeConverter<string, Gender>
{
public Gender Convert(string source)
{
var ignorecase = true;
return (Gender)Enum.Parse(typeof(Gender), source, ignorecase);
}
}

I tend to only make things public when it becomes necessary, which is why this one is internal. In most the samples I’ve found, the converter classes are public. I put the ignorecase variable above so you’d know what the last bool meant in the Enum.Parse. So this is pretty cool and pretty powerful. Anytime you try to map string and Gender, this is called. You’ll also notice that I don’t have Gender mapped anywhere in any of the CreateMap<> definitions.


Okay, let’s keep going.


Second this:

            CreateMap<PersonView, Demographics>()
.ForMember(dest => dest.NationalId, opts => opts.Ignore());

This code is simply ignoring my NationalId property of Demographics. If I didn’t ignore the property, the mapping would still occur, but when you’re setting up your unit test, the Mapper.AssertConfigurationIsValid(ViewToDomainProfile.NameOfProfile); would fail. So AutoMapper likes you to tell it everything so it knows if you meant to ignore something or not. Everything else I didn’t have to map because the names match. Thank you reflection & AutoMapper!


Third this:

 CreateMap<PersonView, ContactInfo>()
.ForMember(dest => dest.MailingAddress, opts => opts.ResolveUsing<
AddressResolver>())
.ForMember(dest => dest.EmailAddress, opts => opts.MapFrom(src => src.ContactInfoEmailAddress));

So this one does something funky in that it has an AddressResolver, which means basically that MailingAddress has properties and AutoMapper can only map the top-level properties. So Jimmy gives us some cool ways to handle these things. Here’s what the AddressResolver looks like:

    internal class AddressResolver:ValueResolver<PersonView, Address>
{
protected override Address ResolveCore(PersonView source)
{
return new Address
{
City = source.MailingAddressCity,
PostalCode = source.MailingAddressPostalCode,
State = source.MailingAddressState,
StreetLine = source.MailingAddressStreetLine
};
}
}

Basically it instantiates a new Address class and sets the properties. Done and Next!


Fourth this:

 CreateMap<PersonView, Person>()
.ForMember(dest => dest.ContactInfo, opts => opts.MapFrom(
Mapper.Map<PersonView, ContactInfo>))
.ForMember(dest=>dest.Demographics, opts=>opts.MapFrom(
Mapper.Map<PersonView, Demographics>))
.ForMember(dest => dest.PersonName, opts => opts.ResolveUsing<
PersonNameResolver>());

Alrighty…so this one does a few things..two of the same things and then one thing the same as “third this”. So I’m actually waiting on a response from the AutoMapper-users group on whether or not this is a good practice. It passes all the tests and I think it looks clean and made sense to me. So, hopefully I’ll get their approval. I know Jimmy responds often, so hopefully I’ll hear somthing tomorrow. I’ll update the post if it’s not a good thing :)


So the above code simply calls the other two CreateMap definitions for ContactInfo & Demographics. It also resolves the PersonName like we did with Address above. This post is already pretty long, so I won’t put that code in here…mainly cause I want to post my unit tests.


Here are the tests:


First call the AutoMapperConfigurator in the setup like this:

  [TestFixture]
public class ViewToDomainProfileTests
{
[
TestFixtureSetUp]
public void SetupDemoTests()
{
AutoMapperConfigurator.Configure();
}

The first unit test I do is the AsserConfigurationIsValid that Jimmy gives us. It looks like this:

        [Test]
public void automapper_should_be_configured_correctly()
{
Mapper.AssertConfigurationIsValid(ViewToDomainProfile.NameOfProfile);
}

Okay, then I tested the demographics area on my person & personview. Please ignore my test names…they’re not very good.

        [Test]
public void demographics_should_equal_personview_demographics()
{
var personview = new PersonView();
personview.Gender =
"Male";
personview.BirthDate =
new DateTime(1990, 1, 1);
personview.Ethnicity =
"Klingon";
var person = Mapper.Map<PersonView, Person>(personview);

Assert.AreEqual(person.Demographics.Gender, Gender.Male);
Assert.AreEqual(person.Demographics.BirthDate, personview.BirthDate);
Assert.AreEqual(person.Demographics.Ethnicity, personview.Ethnicity);
}

Then I wanted to make sure my PersonNameResolver was working, so I did this:

        [Test]
public void person_name_should_equal_personview_name()
{
var personview = new PersonView();
personview.PersonName =
"John Test Smith";

var person = Mapper.Map<PersonView, Person>(personview);

Assert.AreEqual(person.PersonName.FirstName, "John");
Assert.AreEqual(person.PersonName.MiddleName, "Test");
Assert.AreEqual(person.PersonName.LastName, "Smith");
}

Finally I wanted to make sure my ContactInfo mapping was working, so I wrote this test:

 [Test]
public void person_address_should_equal_personview_address()
{
var personview = new PersonView();
personview.MailingAddressStreetLine =
"1234 Test St.";
personview.MailingAddressCity =
"Testville";
personview.MailingAddressState =
"TX";
personview.MailingAddressPostalCode =
"12345-1234";
personview.ContactInfoEmailAddress =
"test@test.com";
personview.HomePhoneNumber =
"123-456-7890";

var person = Mapper.Map<PersonView, Person>(personview);

Assert.AreEqual(person.ContactInfo.MailingAddress.StreetLine, personview.MailingAddressStreetLine);
Assert.AreEqual(person.ContactInfo.MailingAddress.City, personview.MailingAddressCity);
Assert.AreEqual(person.ContactInfo.MailingAddress.State, personview.MailingAddressState);
Assert.AreEqual(person.ContactInfo.MailingAddress.PostalCode, personview.MailingAddressPostalCode);
Assert.AreEqual(person.ContactInfo.EmailAddress, personview.ContactInfoEmailAddress);
Assert.AreEqual(person.ContactInfo.HomePhoneNumber, personview.HomePhoneNumber);
}

All done! Stay tuned for part 2 where I basically reverse this and go DomainToView and I talk about why some of the names in my ViewModel are weird…like ContactInfoEmailAddress.



Thanks for reading!

UPDATED: 1/20/2009 7:20PM
Please note that going from domain model to view model and back to domain model is NOT a recommended practice. I did hear back from the AutoMapper user group and they wanted to make sure to point that out. Also, all the AutoMapper code is valid, so I will leave it all as is for reference of how to map certain items. I think it’s a good example of mapping random things, which was the original purpose. I do not have any of this code in a production environment, it is simply a demo on how to use AutoMapper to map your objects.

Shout it

kick it on DotNetKicks.com

Tuesday, January 12, 2010

ASP.NET MVC Sample Project Launched




Okay, after popular demand of I think 3 people, I’ve published the code for the wife’s website. If you haven’t read any of the posts on my wife’s project, check out this post. This project completely separates UI & C# code, so you only have 2 projects (Core & UI).

Basically, all I did was create a new MVC project with Microsoft’s default template and deleted everything except the following:

  • Views folder
  • Root Default.aspx
  • global.asax (I did delete the global.asax.cs)
  • both web.configs

I referenced my Core, setup my views that match my Core project, and inherited from my global.cs in the global.asax. That was it!

You can check it out via svn here: https://derans.googlecode.com/svn/trunk/

or

download it via zip here: http://code.google.com/p/derans/downloads/list

I feel like this project will act as a great stepping stone to understanding the Code Camp server, which is much more complex.

My unit tests are definitely the weakest part of the project, so there won’t be a need to run any coverage tests or anything like that because this project will not do well :)

The sample project was built with the following tools:

The best practices I mentioned above come straight from experience and the following people/resources:

You can see the exact same Core code in use at sweetandhappy.com. If you see any improvements that can be made or you’d just like to comment, please do so!

Thanks for reading!


Shout it

kick it on DotNetKicks.com

Thursday, January 07, 2010

ASP.NET MVC Bootstrapper




Thanks to a comment by thangchung in my last post about the global.asax, I’m going to write up a post using a bootstrapper in my global.cs. So what does that mean? Well basically it’s a technique to boot up your mvc app. Let’s get started!

Step 1: Create your task interface. Mine looks like this:

public interface IStartUpTask
{
void Configure();
}

Pretty simple right? Let’s keep on…


Step 2: Configure StructureMap, otherwise you’re going to have a mess. In my Scan() from my DependencyRegistry, I added x.AddAllTypesOf<IStartUpTask>(); and the completed Scan looks like this:

  Scan(x =>
{
x.TheCallingAssembly();
x.AddAllTypesOf<
IStartUpTask>();
x.WithDefaultConventions();
});

Step 3: Create the Bootstrapper class. Mine looks like this:

    public class Bootstrapper
{
static Bootstrapper()
{
DependencyResolution.
DependencyRegistrar.EnsureDependenciesRegistered();
}

public static void StartUp()
{
var startUpTasks = ObjectFactory.GetAllInstances<IStartUpTask>();

foreach (var task in startUpTasks)
task.Configure();
}
}

The DependencyRegistrar mentioned above, I basically stole from the sample code in the ASP.NET MVC in Action book. I made a few modifications, but not much.


Step 4: Configure your configuration files for all the junk you need to start up.



  • Routes - I took my RouteConfigurator and made it implement IStartUpTask and renamed RegisterRoutes to Configure.
  • MvcContrib InputBuilder – Just made a new class that looks like this:
public class MvcContribConfigurer : IStartUpTask
{
public void Configure()
{
MvcContrib.UI.InputBuilder.
InputBuilder.BootStrap();
}
}


  • Automapper - I already had a configure, so I just tacked on the : IStartUpTask like this:
    public class AutoMapperConfigurator : IStartUpTask
{
public void Configure()
{
Mapper.Initialize(x => x.AddProfile<MyProfile>());
}
}


  • ControllerFactory – I created a new class for it and it looks like this:
 public class ControllerConfigurer : IStartUpTask
{
public void Configure()
{
ControllerBuilder.Current.SetControllerFactory(new ControllerFactory());
}
}

That’s it! So essentially the Global.cs went from this:

protected void Application_Start()
{
MvcContrib.UI.InputBuilder.InputBuilder.BootStrap();
DependencyRegistrar.EnsureDependenciesRegistered();
new RouteConfigurator().RegisterRoutes();
AutoMapperConfigurator.Configure();
ControllerBuilder.Current.SetControllerFactory(new ControllerFactory());
}

to this:

        protected void Application_Start()
{
Bootstrapper.StartUp();
}

Pretty cool stuff! Thanks thangchung for bringing it up!


As always, please comment and thanks for reading!




Shout it

kick it on DotNetKicks.com

Tuesday, December 22, 2009

AutoMapper – ASP.NET MVC




First things first, let’s setup our Profile and call our configure from the global.asax. After reading blogs and sample code, I believe this is the best practice while using AutoMapper. I try to only post best practices, but sometimes I slip up or have a brain fart. So let’s rig this thing up.

Step 1: Create an AutoMapperConfigurator

    public class AutoMapperConfigurator
{
public static void Configure()
{
Mapper.Initialize(x => x.AddProfile<MyProfile>());
}
}

Note: I put my AutoMapperConfigurator under Helpers –> Configuration


Step 2: Create the MyProfile class (as mentioned above), which inherits from AutoMapper.Profile

    public class MyProfile : Profile
{
public const string VIEW_MODEL = "MyProfileNameHere";
protected override string ProfileName
{
get { return VIEW_MODEL; }
}

protected override void Configure()
{
CreateMaps();
}

private static void CreateMaps()
{
//Create Maps here…we'll get to this in a second
}
}

Step 3: Plug into global.asax

        protected void Application_Start()
{
AutoMapperConfigurator.Configure();
}

Okay, we’re all setup, let’s make some maps. I will be mapping the two objects(FeedbackForm & INotificationMessage), which are listed below. The FeedbackForm is part of my view model on my MVC project & INotificationMessage is part of my domain model.


Here is the FeedbackForm:

    public class FeedbackForm
{
public string SenderName { get; set; }
public string SenderEmail { get; set; }
public string Subject { get; set; }
public string MessageBody { get; set; }
}

And my INotificationMessage:

    public interface INotificationMessage
{
string Subject { get; set; }
string MessageBody { get; set; }
}

Step 4: Map the objects

        private void CreateMaps()
{
//Mapper.CreateMap<FeedbackForm, INotificationMessage>() //BEFORE JIMMY’S COMMENT BELOW

CreateMap<FeedbackForm, INotificationMessage>(); //AFTER JIMMY’S COMMENT
}

UPDATED 12/22/09 8:00PM
According to Jimmy, I should use just CreateMap<> above instead of Mapper.CreateMap and since he’s the creator of AutoMapper, I guess I’ll trust him :) Thanks Jimmy!


That’s it! Done! If my property names didn’t match up exactly, there would be more work to do, but since they do, we’re done! For a GREAT tutorial on AutoMapper, see Jimmy Bogard on dnrTV.


Now let’s use it in our controller!


Step 5: Create Mapper Interface

    public interface IFeedbackMapper
{
T Map<T>(
FeedbackForm model);
}

Step 6: Implement Mapper Interface

    public class FeedbackMapper : IFeedbackMapper
{
public T Map<T>(FeedbackForm model)
{
return Mapper.Map<FeedbackForm, T>(model);
}
}
The reason we’re doing this and not just using Mapper.Map in the FeedbackController is that we’re trying to keep all the using statements to be our namespaces and that’s it. Everything else should be wrapped by our code so we’re not depending on 3rd party or Microsoft implementations.


Step 7: Inject the IFeedbackMapper into the FeedbackController constructor

        private readonly IFeedbackMapper _feedbackMapper;
public FeedbackController(IFeedbackMapper feedbackMapper)
{
_feedbackMapper = feedbackMapper;
}

Note: You can inject the feedbackMapper using your favorite IoC tool. See my StructureMap posts for more info or the StructureMap site.


Step 8: Use the _feedbackMapper

        [AcceptVerbs(HttpVerbs.Post), ValidateModel(typeof(FeedbackForm)), ValidateAntiForgeryToken]
public ViewResult Index(FeedbackForm form)
{
if (!ModelState.IsValid)
return View("index", form);

var message = _feedbackMapper.Map<NotificationMessage>(form);
//send message via notification service or something and return Success View
}

Step 9: Add more stuff to the mapper and map away!


Please let me know your thoughts! Thanks for reading!

kick it on DotNetKicks.com

Related Posts Plugin for WordPress, Blogger...