How to publish a specific event from an implemented interface - masstransit

Full code (github)...
I'm moving from MediatR to MassTransit to publish my domain events to a queue.
I'm using an interface IDomainEvent in different domain events that implement such interface (in this case PersonCreated and PersonPositionCreated). Then I have an entity 'Person' with a list of IDomainEvent in which I register all the domain events occurred. I Also have a consumer for each specific event.
After persist my entity, I want to iterate all the events of the entity and publish them to the queue.
// Event interface.
public class IDomainEvent
{
}
// Events.
public class PersonCreated : IDomainEvent
{
public int Id { get; set; }
}
public class PersonPositionCreated : IDomainEvent
{
public string Position { get; set; }
}
// Entity.
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Position { get; set; }
public List<IDomainEvent> Events { get; set; };
}
// Consumers.
public class PersonCreatedConsumer : IConsumer<PersonCreated>
{
public Task Consume(ConsumeContext<PersonCreated> context)
{
Debug.Print(context.Message.Id.ToString());
return Task.CompletedTask;
}
}
public class PersonPositionCreatedConsumer : IConsumer<PersonPositionCreated>
{
public Task Consume(ConsumeContext<PersonPositionCreated> context)
{
Debug.Print(context.Message.Position);
return Task.CompletedTask;
}
}
// My command.
//...
// Creates Person.
Person person = new Person(){ Id = 1, Name = "Alice", Position = "Developer" };
// Registers the events to the list.
person.Events.Add(new PersonCreated() { Id = person.Id });
person.Events.Add(new PersonPositionCreated() { Position = person.Position });
foreach (IDomainEvent personEvent in person.Events)
{
// This way, it publish an IDomainEvent and I don't want to use a IConsumer<IDoaminEvent> because I need specific consumers.
// How can I tell the bus that I sending the specific event and not the IDomainEvent?
//(I know that inside the iteration I'm dealing with IDomainEvent but it have access to the class that implement the interface).
// NOTE: That way works with MediatR specific handlers.
| |
\ /
\ /
\/
_bus.Publish(personEvent);
}
// Of course this two lines works!
//_bus.Publish<PersonCreated>(new PersonCreated() { Id = 1 });
//_bus.Publish<PersonPositionCreated>(new PersonPositionCreated() { Position = "Developer" });
//...
How can I tell the bus that I am sending the specific event and not the IDomainEvent?
(I know that inside the iteration I'm dealing with IDomainEvent, but it has access to the class that implement the interface).

You should call:
_bus.Publish((object)personEvent);
By casting it to an object, MassTransit will call GetType() and then publish to the exchange (and ultimately consumer) for the object type (aka, implemented message type).

Related

Automatonymous - Payload not found when calling RaiseEvent with Send Activity

I've been spinning my wheels trying to get the MassTransitStateMachine working and I seem to not understand exactly how this is supposed to work.
The error I'm receiving (full code below) is PayloadNotFoundException when I attempt to call stateMachine.RaiseEvent(instance, stateMachine.DeployApplicationRequest, request) combined with the .Send() Activity in the state machine. I've been trying to trace this through but have gotten nowhere.
Here's the relevant code and explanation of intent:
I receive a request to deploy an application via a webAPI post, and convert the request to a DeployApplicationRequest.
public record DeployApplicationRequest
{
// State machine properties
public Guid CorrelationId { get; init; }
public ChatApplication ChatApplication { get; init; }
public string ChannelId { get; init; }
public string UserId { get; init; }
// Command
public DeployApplication DeployApplication { get; init; }
}
public enum ChatApplication
{
Slack,
Teams
}
This request encapsulates two things: The state that the API needs to maintain so it knows how to route the results back to the requester (state machine properties) and the Command to be sent to the service bus.
The command, DeployApplication, looks like this:
public record DeployApplication
{
public Guid CorrelationId { get; init;}
public string InitiatedBy { get; init; }
public DateTime CreatedDate { get; init; }
public string Environment { get; init; }
public string PullRequestId { get; init; }
}
I have created a state instance to preserve the details of the request (such as whether it came in via Slack or Teams). I do not want to publish this information to the bus:
public class DeployApplicationState : SagaStateMachineInstance
{
public Guid CorrelationId { get; set; }
public string CurrentState { get; set; }
public ChatApplication ChatApplication { get; set; }
public string ChannelId { get; set; }
public string UserId { get; set; }
}
And I have created a StateMachine to handle this:
public class DeployApplicationStateMachine : MassTransitStateMachine<DeployApplicationState>
{
private readonly ILogger<DeployApplicationStateMachine> logger;
public DeployApplicationStateMachine(ILogger<DeployApplicationStateMachine> logger)
{
this.logger = logger;
InstanceState(x => x.CurrentState);
Event(() => DeployApplicationRequest, x => x.CorrelateById(context => context.Message.CorrelationId));
Initially(
When(DeployApplicationRequest)
.Then(x => {
x.Instance.CorrelationId = x.Data.CorrelationId;
x.Instance.ChannelId = x.Data.ChannelId;
x.Instance.ChatApplication = x.Data.ChatApplication;
x.Instance.UserId = x.Data.UserId;
})
.Send(context => context.Init<DeployApplication>(context.Data.DeployApplication))
.TransitionTo(Submitted));
}
public Event<DeployApplicationRequest> DeployApplicationRequest { get; private set; }
public State Submitted { get; private set; }
}
To trigger the initial event (since the request is not coming in via a Consumer but rather through a controller), I have injected the state machine into the MassTransit client, and I'm calling the RaiseEvent method:
public class MassTransitDeployClient : IDeployClient
{
private readonly DeployApplicationStateMachine stateMachine;
public MassTransitDeployClient(DeployApplicationStateMachine stateMachine)
{
this.stateMachine = stateMachine;
}
public async Task Send(DeployApplicationRequest request)
{
var instance = new DeployApplicationState
{
CorrelationId = request.CorrelationId,
ChannelId = request.ChannelId,
ChatApplication = request.ChatApplication,
UserId = request.UserId
};
await stateMachine.RaiseEvent(instance, stateMachine.DeployApplicationRequest, request);
// This works for sending to the bus, but I lose the state information
//await sendEndpointProvider.Send(request.DeployApplication);
}
}
And the container configuration is as follows:
services.AddMassTransit(x =>
{
x.AddSagaStateMachine<DeployApplicationStateMachine, DeployApplicationState>()
.InMemoryRepository();
x.UsingInMemory((context, cfg) =>
{
cfg.ConfigureEndpoints(context);
});
});
EndpointConvention.Map<DeployApplication>(new Uri($"queue:{typeof(DeployApplication).FullName}"));
services.AddMassTransitHostedService();
Raising the event works just fine, and the state machine transfers to Submitted successfully if I do not include .Send(...) in the state machine. The second I introduce that Activity I get the PayloadNotFoundException. I've tried about 15 different ways of doing this over the weekend with no success, and I'm hoping someone may be able to help me see the error of my ways.
Thanks for reading! Fantastic library, by the way. I'll be looking for ways to contribute to this going forward, this is one of the most useful libraries I've come across (and Chris your Youtube videos are excellent).
Saga state machines are not meant to be invoked directly from controllers. You should send (or publish) a message that will then be dispatched to the saga via the message broker.
IF you want to do it that way, you can use MassTransit Mediator instead, but you'll still be sending a message via Mediator to the saga, which will then be handled by MassTransit.
TL;DR - you don't use RaiseEvent with saga state machines.

How should be initialized CorrelationId at MassTransit

I'd like to track my messages using built-in interface CorrelatedBy<TKey>, but i didn't quite understand: should i initialize it myself, for example, in constructor of my message (command)?
public class RegisterCallback : IRegisterCallback
{
public RegisterCallback()
{
CorrelationId = Guid.NewGuid();
}
public Guid RequestId { get; set; }
public Guid CorrelationId { get; }
}
You should initialize it by either passing it into the constructor, or otherwise generating it as part of the constructor.
public RegisterCallback(Guid correlationId) {...}
Or you can generate it using NewId to get an ordered identifier.
public RegisterCallback()
{
CorrelationId = NewId.NextGuid();
}
Also, your interface should include CorrelatedBy<Guid> if you want to use the built-in support.
public interface IRegisterCallback :
CorrelatedBy<Guid> {...}

MVC3 - Unity/Unit of Work Pattern and Webservice implementation

I am a newbie to with unity and unit of work pattern and I am trying to write a code, which connects to my webservice and does all the work.
Everything goes well until I use the Database but I get lost when I try to use the webservice.
I have wasted my 2 precious days, searching every single possible article related to it and applying it to my code, but no luck till date.
I know, by writing connection string to web.config and calling it in dbcontext class controller will connect to the required database, but I am not connecting to any database, so what changes I need to do in web/app.config. Also, even if I write my connection logic in dbcontext constructor, it still searches and fills the dbcontext with sql server details. I presume thats happening because I am using DBSet.
Guys, you are requested to have a look at my code, I have done and show me some hope that I can do it. Let me know, if you want any other info related to the code that you want to see.
thanks
DBCONTEXT
public class CVSContext : DbContext
{
public DbSet<CVSViewModel> CVS { get; set; }
public DbSet<Contact> Contacts { get; set; }
public DbSet<Account> Accounts { get; set; }
public CVSContext()
{
//CRM Start
var clientCredentials = new System.ServiceModel.Description.ClientCredentials();
clientCredentials.UserName.UserName = "";
clientCredentials.UserName.Password = "";
var serviceProxy = new Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy(new Uri("http://Organization.svc"), null, clientCredentials, null);
serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
HttpContext.Current.Session.Add("ServiceProxy", serviceProxy);
//CRM End
}
}
GENERIC REPOSITORY
public class GenericRepository<TEntity> where TEntity : class
{
internal CVSContext context;
internal DbSet<TEntity> dbSet;
public GenericRepository(CVSContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
}
UNIT OF WORK
public interface IUnitOfWork : IDisposable
{
int SaveChanges();
}
public interface IDALContext : IUnitOfWork
{
ICVSRepository CVS { get; set; }
IContactRepository Contacts { get; set; }
//IAccountRepository Accounts { get; set; }
}
public class DALContext : IDALContext
{
private CVSContext dbContext;
private ICVSRepository cvs;
private IContactRepository contacts;
// private IAccountRepository accounts;
public DALContext()
{
dbContext = new CVSContext();
}
public ICVSRepository CVS
{
get
{
if (cvs == null)
cvs = new CVSRepository(dbContext);
return cvs;
}
set
{
if (cvs == value)
cvs = value;
}
}
public IContactRepository Contacts
{
get
{
if (contacts == null)
contacts = new ContactRepository(dbContext);
return contacts;
}
set
{
if (contacts == value)
contacts = value;
}
}
public int SaveChanges()
{
return this.SaveChanges();
}
public void Dispose()
{
if(contacts != null)
contacts.Dispose();
//if(accounts != null)
// accounts.Dispose();
if(dbContext != null)
dbContext.Dispose();
GC.SuppressFinalize(this);
}
}
SERVICE
public interface ICVSService
{
Contact CreateContact(Guid contactName, string productName, int price);
List<CVSViewModel> GetCVS();
List<Contact> GetContacts();
List<Account> GetAccounts();
}
public class CVSService : ICVSService, IDisposable
{
private IDALContext context;
public CVSService(IDALContext dal)
{
context = dal;
}
public List<CVSViewModel> GetCVS()
{
return context.CVS.All().ToList();
}
public List<Contact> GetContacts()
{
return context.Contacts.All().ToList();
}
public List<Account> GetAccounts()
{
return context.Accounts.All().ToList();
}
public Contact CreateContact(Guid contactName, string accountName, int price)
{
var contact = new Contact() { ContactId = contactName };
var account = new Account() { ContactName = accountName, Rent = price, Contact = contact };
//context.Contacts.Create(contact);
context.SaveChanges();
return contact;
}
public void Dispose()
{
if (context != null)
context.Dispose();
}
}
CONTROLLER
public ActionResult Index()
{
ViewData.Model = service.GetContacts();
return View();
}
It's all about proper abstractions. The common abstraction that is used between some data source (could be a db or ws) is the Repository pattern, or at a higher level the Unit of Work pattern. In fact Entity Framework DbContext is an implementation of the Unit of Work pattern, but it is tailored for databases. You can't use to communicate with a web service.
In that case you will have to write your own IRepository<T> abstraction and have a database specific implementation that uses a DbContext under the covers and a web service specific implementation that wraps a web service client proxy under the covers.
However, when your application gets more complex, you often find yourself wanting to have some sort of transaction like behavior. This is what the Unit of Work pattern if for: it presents a business transaction. Using the unit of work pattern to wrap multiple WS calls however, will get painful very soon. It's a lot of work to get right and in that case you will be much better of using a message based architecture.
With a message based architecture you define a single atomic operation (a business transaction or use case) as a specific message, for instance:
public class MoveCustomerCommand
{
public int CustomerId { get; set; }
public Address NewAddress { get; set; }
}
This is just an object (DTO) with a set of properties, but without behavior. Nice about this is that you can pass these kinds of objects over the wire using WCF or any other technology or process them locally without the need for the consumer to know.
Take a look at this article that describes it in detail. This article builds on top of that model and describes how you can write highly maintainable WCF services using this model.

IValidatableObject passes validation but StringLength is Invalid

I have a test class with a couple tests that check to see if the entity IsValid. I moved to using IValidatableObject from having my own custom validation but I'm stuck with the correct validation technique.
This is my Test class:
[TestFixture]
public class StudentTests {
private static Student GetContactWithContactInfo()
{
return new Student(new TestableContactRepository())
{
Phone = "7275551111"
};
}
private static Student GetContactWithoutContactInfo()
{
return new Student(new TestableContactRepository());
}
[Test]
public void Student_Saving_StudentHasInfo_IsValid ()
{
// Arrange
Student student = GetContactWithContactInfo();
// Act
student.Save();
// Assert
Assert.IsTrue(student.IsValid);
}
[Test]
public void Student_Saving_StudentDoesNotHaveInfo_IsNotValid ()
{
// Arrange
Student student = GetContactWithoutContactInfo();
// Act
student.Save();
// Assert
Assert.IsFalse(student.IsValid);
}
}
This is my entity:
public class Student : IValidatableObject
{
private readonly IContactRepository contactRepository;
public Student(IContactRepository _contactRepository)
{
contactRepository = _contactRepository;
Contacts = new List<Student>();
}
[Required]
public int Id { get; private set; }
[StringLength(10, MinimumLength = 10)]
public string Phone { get; set; }
public List<Student> Contacts { get; private set; }
public bool IsValid { get; private set; }
public void Save()
{
if (IsValidForPersistance())
{
IsValid = true;
Id = contactRepository.Save();
}
}
private bool IsValidForPersistance()
{
return Validator.TryValidateObject(this, new ValidationContext(this), null, true);
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (string.IsNullOrEmpty(Phone) && Contacts.All(c => string.IsNullOrEmpty(c.Phone)))
yield return new ValidationResult("The student or at least one contact must have a phone number entered", new[] { "Phone Number" });
}
}
As you can see the tests test for IsValid by calling the IsValidForPersistance. Validate will eventually have more validation .
The above tests all pass using this method but this test below also passes but should not.
[Test]
public void Student_Saving_HasContactInfoWithInvalidLength_IsNotValid()
{
// Arrange
Contact student = GetContactWithoutContactInfo();
student.Phone = "string";
// Act
student.Save();
// Assert
Assert.IsFalse(student.IsValid);
}
Here I'm setting my own Phone value of an invalid length string. I expect validation to fail because of the StringLength annotation set at min and max 10 characters.
Why is this passing?
Update
There was a problem with the custom validation, updated the code with the change. Along with the suggestion from nemesv about not having a private modifier on the Phone property it now works. I've updated all the code to working.
Validator.TryValidateObject only checks the RequiredAttributes (and also other things like type level attributes and IValidatableObject implementation) by default.
If you need to validate all the attributes like StringLength etc. you need to set the validateAllProperties parameter of the method to true
private bool IsValidForPersistance() {
return Validator.TryValidateObject(this,
new ValidationContext(this),
null,
true /* validateAllProperties */);
}

ASP.NET MVC Patterns

I am fairly new to MVC, but after playing with it (MVC 3/Razor), I am hooked.
I have a few questions:
1) What is the best, or most widely used pattern to develop MVC apps in? Repository, DDD, UOW?
2) I am using the Entity Framework 4, so could some please explain to me or point me to a good source that will explain the Repository Pattern w/EF4? Doesn't EF4 take place as the business layer and the data access layer? Does the Repository Pattern even provide a benefit?
3) Also, one last question, could someone explain the whole relationship between the Controller, the Model and the View? I get the basics, but maybe a little more in depth of the correct way to use it. View Models - Say I have a view that displays customer info, and one that edits it, should I have a view model and an edit model, or can the be passed around?
4) Examples??
Thanks for the help up front,
$("Sam")
** EDIT **
Am I on the right track here:
Public Class HomeController
Inherits System.Web.Mvc.Controller
Function Index(ByVal id As Integer) As ActionResult
Return View(New HomeModel)
End Function
<HttpPost()> _
Function Index(ByVal Model As HomeModel) As ActionResult
Return View(Model)
End Function
End Class
Public Class HomeModel
Private _Repository As IRepository(Of Customer)
Public Property Customer As Customer
Public Sub New()
End Sub
Public Sub New(ByVal ID As Integer)
_Repository = New CustomerRepository
Customer = _Repository.GetByID(ID)
End Sub
End Class
Public Interface IRepository(Of T)
Function GetByID(ByVal ID As Integer) As T
Sub Add(ByVal Entity As T)
Sub Delete(ByVal Entity As T)
End Interface
Public Class CustomerRepository
Implements IRepository(Of Customer)
Public Sub Add(ByVal Entity As Customer) Implements IRepository(Of Customer).Add
End Sub
Public Sub Delete(ByVal Entity As Customer) Implements IRepository(Of Customer).Delete
End Sub
Public Function GetByID(ByVal ID As Integer) As Customer Implements IRepository(Of Customer).GetByID
Return New Customer With {.ID = ID, .FirstName = "Sam", .LastName = "Striano"}
End Function
End Class
Public Class Customer
Public Property ID As Integer
Public Property FirstName As String
Public Property LastName As String
End Class
I use generic repositories that get instantiated in a service class (using Dependency Injection with Ninject).
The service class essentially performs two functions:
It provides all the methods that the controller will consume.
It has a property called ViewModel, that essentially maps the data that the views need into a MyViewModel class.
The Controller consumes the service class. With this "pattern", your controllers look like:
namespace ES.eLearningFE.Areas.Courses.Controllers
{
public partial class CourseController : Controller
{
ICourseDisplayService service;
public CourseController(ICourseDisplayService service)
{
this.service = service;
}
public virtual ActionResult Display(int CourseId, int StepOrder, string PupilName, string TutorName)
{
service.CourseId = CourseId;
service.StepOrder = StepOrder;
service.PupilName = PupilName;
service.TutorName = TutorName;
if (Request.IsAjaxRequest())
{
return PartialView(service.ViewModel);
}
else
{
return View(service.ViewModel);
}
}
}
}
The ViewModel class only hold display data and no methods (except the odd really simple method to retrieve data from another property that is, for example a List<> object).
Works really well. An example of a service class:
namespace ES.eLearning.Domain.Services.Courses
{
public class SqlCourseDisplayService : ICourseDisplayService
{
DataContext db;
public SqlCourseDisplayService(DbDataContextFactory contextFactory)
{
db = contextFactory.Make();
CoursesRepository = new SqlRepository<Course>(db);
StepsRepository = new SqlRepository<CourseStep>(db);
StepLinksRepository = new SqlRepository<StepLink>(db);
UserCoursesRepository = new SqlRepository<UserCourse>(db);
CourseTutorsRepository = new SqlRepository<CourseTutor>(db);
UsersRepository = new SqlRepository<User>(db);
}
#region ICourseDisplayService Members
public ViewModels.CourseDisplayVM ViewModel
{
get
{
return new ViewModels.CourseDisplayVM
{
CourseId = this.CourseId,
CourseName = this.Course.Name,
Steps = this.Steps,
ActiveStepIndex = this.ActiveStepIndex,
CurrentStepIndex = this.CurrentStepIndex,
Pupil = new UserDto { UserId = this.PupilId, UserName = this.PupilName },
Tutors = this.GetTutors(this.CourseId),
Tutor = tutorName == null ? null : new UserDto { UserName = this.TutorName, UserId = this.TutorId}
};
}
}
#region Entities
int courseId;
public int CourseId
{
get
{
if (courseId == 0) throw new ApplicationException("Invalid Course Id!");
return courseId;
}
set
{
if (value == 0) throw new ApplicationException("Invalid Course Id!");
try
{
Course = (from c in CoursesRepository.Query where c.CourseId == value select c).First();
Steps = Course.CourseSteps.ToList();
courseId = value;
}
catch {throw new ApplicationException("No Course found for Course Id: " + value);}
}
}
public Data.Course Course { get; private set; }
public int StepOrder { get; set; }
public List<Data.CourseStep> Steps { get; private set; }
public int ActiveStepIndex
{
get
{
if (PupilName == null)
{
throw new ApplicationException("Pupil not set!");
}
if (CourseId == 0)
{
throw new ApplicationException("Course not set!");
}
try
{
var x = (from uc in UserCoursesRepository.Query where (uc.IdCourse == CourseId) && (uc.UserName == PupilName) select uc).First();
return x.ActiveStepIndex;
}
catch { throw new ApplicationException("Could not get Active Step!"); }
}
}
#endregion
#region Users
string tutorName;
public string TutorName
{
get
{
if (tutorName == null) throw new ApplicationException("Invalid call to get Tutor Name [Null Tutor Name]!");
return tutorName;
}
set
{
tutorName = value;
TutorId = (Guid)Membership.GetUser(tutorName).ProviderUserKey;
}
}
public Guid TutorId { get; set; }
string pupilName;
public string PupilName
{
get { return pupilName; }
set
{
pupilName = value;
PupilId = (Guid)Membership.GetUser(pupilName).ProviderUserKey;
}
}
public Guid PupilId { get; set; }
#endregion
#region Utility Properties
public int CurrentStepIndex { get; set; }
public int StepCount
{
get
{
return Steps == null ? 0 : Steps.Count();
}
}
#endregion
#region Private Utilities
private List<UserDto> GetTutors(int CourseId)
{
return (from ct in CourseTutorsRepository.Query join u in UsersRepository.Query
on ct.TutorName equals u.UserName
where (ct.CourseId == courseId)
select new UserDto { UserName = ct.TutorName, UserId = u.UserId }).ToList();
}
#endregion
#region Repositories
private IRepository<Course> CoursesRepository
{
get;
set;
}
private IRepository<CourseStep> StepsRepository
{
get;
set;
}
private IRepository<StepLink> StepLinksRepository
{
get;
set;
}
private IRepository<UserCourse> UserCoursesRepository
{
get;
set;
}
private IRepository<CourseTutor> CourseTutorsRepository
{
get;
set;
}
private IRepository<User> UsersRepository
{
get;
set;
}
#endregion
#endregion
}
}
May not be everyone's choice, but hey, it works for me... AND (more importantly) my clients and their users.
Edit
As requested in the comment below, the Repository that I use:
namespace ES.eLearning.Domain
{
public class SqlRepository<T> : IRepository<T> where T : class
{
DataContext db;
public SqlRepository(DataContext db)
{
this.db = db;
}
#region IRepository<T> Members
public IQueryable<T> Query
{
get { return db.GetTable<T>(); }
}
public List<T> FetchAll()
{
return Query.ToList();
}
public void Add(T entity)
{
db.GetTable<T>().InsertOnSubmit(entity);
}
public void Delete(T entity)
{
db.GetTable<T>().DeleteOnSubmit(entity);
}
public void Attach(T entity)
{
db.GetTable<T>().Attach(entity);
}
public void Save()
{
db.SubmitChanges();
}
#endregion
}
}
And the IRepository Interface:
namespace Wingspan.Web.Mvc
{
public interface IRepository<TEntity> where TEntity : class
{
List<TEntity> FetchAll();
IQueryable<TEntity> Query {get;}
void Add(TEntity entity);
void Delete(TEntity entity);
void Attach(TEntity entity);
void Save();
}
}
This should help you getting started. There are a lot of tutorials and videos available; for example:
Understanding Models, Views and Controllers
The ASP.NET MVC 2.0 basics and excellent introduction by Scott Hanselman. Personally one of my favorite speakers.
And also at www.asp.net; there are a few tutorials/examples to help you getting started. For example the Music Store sample
Unfortunately, I'm not so familiar with EF4/Repository pattern. But here's a blogpost about this pattern.
1) I would say that the repository pattern is the most widely used, then there is inversion of controll too.
2) I can't really point out the benefits with using a repository for entity framework other than that the controller should not know about how to acces data other then asking a repository. This makes it easy to switch it out sometime.
You can also eager load the data to make sure that the view don't call the database in every iteration of a foreach, for example a collection of users to display data from a child entity. You can probly do this anyway, but I feel that the repository is the right place to do it.
3) I can't tell you about the concept in a more in depth way, but I can tell some about viewmodels. In my opinion you should only use viewmodels if there is anything more then one entity you want to send to the view, for example a list of countries. You can alo use a viewmodel to "flatten" out very complex objects.
I would defiantly say the repository pattern is used a lot. This pattern can be used with Dependency Injection. Using Dependency Injection makes Unit Testing a breeze because you can snap different repositories to an abstract repoistory. Check out http://ninject.org/ for a simple to use Dependecy injector for .NET.
View Models should hold display data and transfer that data from the controller to the view. If you want to edit and display customer info, take a look at this

Resources