<|start_filename|>src/EventSourcingCqrsSample.EventHandlers/BaseEventHandler.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using EventSourcingCqrsSample.Events;
using EventSourcingCqrsSample.Models.Requests;

namespace EventSourcingCqrsSample.EventHandlers
{
    /// <summary>
    /// This represents the base event processor entity. This must be inherited.
    /// </summary>
    /// <typeparam name="T">Type of event.</typeparam>
    public abstract class BaseEventHandler<T> : IEventHandler where T : BaseEvent
    {
        private bool _disposed;

        /// <summary>
        /// Loads the list of events.
        /// </summary>
        /// <param name="streamId">The stream id.</param>
        /// <returns>Returns the list of events.</returns>
        public async Task<IEnumerable<BaseEvent>> LoadAsync(Guid streamId)
        {
            var events = await this.OnLoadAsync(streamId);
            return events;
        }

        /// <summary>
        /// Loads the latest event.
        /// </summary>
        /// <param name="streamId">The stream id.</param>
        /// <returns>Returns the latest event.</returns>
        public async Task<BaseEvent> LoadLatestAsync(Guid streamId)
        {
            if (streamId == Guid.Empty)
            {
                return null;
            }

            var events = await this.LoadAsync(streamId);
            return events.FirstOrDefault();
        }

        /// <summary>
        /// Checks whether the given event can be processed or not.
        /// </summary>
        /// <param name="ev">Event instance.</param>
        /// <returns>Returns <c>True</c>, if the given event can be processed; otherwise returns <c>False</c>.</returns>
        public virtual bool CanProcess(BaseEvent ev)
        {
            var @event = ev as T;
            return @event != null;
        }

        /// <summary>
        /// Processes the event asynchronously.
        /// </summary>
        /// <param name="ev">Event instance.</param>
        /// <returns>Returns <c>True</c>, if the given event has been processed; otherwise returns <c>False</c>.</returns>
        public async Task<bool> ProcessAsync(BaseEvent ev)
        {
            ev.DateRecorded = DateTime.UtcNow;
            return await this.OnProcessingAsync(ev);
        }

        /// <summary>
        /// Checks whether the given request can be built or not.
        /// </summary>
        /// <typeparam name="TReq">Type of request.</typeparam>
        /// <param name="request">Request instance.</param>
        /// <returns>Returns <c>True</c>, if the given request can be built; otherwise returns <c>False</c>.</returns>
        public virtual bool CanBuild<TReq>(BaseRequest request) where TReq : BaseRequest
        {
            return false;
        }

        /// <summary>
        /// Builds the request using the latest event stored asynchronously.
        /// </summary>
        /// <param name="request">The request instance.</param>
        /// <returns>Returns the <see cref="Task"/>.</returns>
        public virtual async Task BuildRequestAsync(BaseRequest request)
        {
            await Task.FromResult(false);
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public virtual void Dispose()
        {
            if (this._disposed)
            {
                return;
            }

            this._disposed = true;
        }

        /// <summary>
        /// Called while loading events from the repository asynchronously.
        /// </summary>
        /// <param name="streamId">The stream id.</param>
        /// <returns>Returns the list of events.</returns>
        protected abstract Task<IEnumerable<BaseEvent>> OnLoadAsync(Guid streamId);

        /// <summary>
        /// Called while processing the event asynchronously.
        /// </summary>
        /// <param name="ev">Event instance.</param>
        /// <returns>Returns <c>True</c>, if the given event has been processed; otherwise returns <c>False</c>.</returns>
        protected abstract Task<bool> OnProcessingAsync(BaseEvent ev);
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Services/EventStreamService.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using EventSourcingCqrsSample.EventProcessors;
using EventSourcingCqrsSample.Events;
using EventSourcingCqrsSample.Models.Requests;
using EventSourcingCqrsSample.Models.Responses;
using EventSourcingCqrsSample.Models.Responses.Data;
using EventSourcingCqrsSample.RequestBuilders;
using EventSourcingCqrsSample.RequestHandlers;

namespace EventSourcingCqrsSample.Services
{
    /// <summary>
    /// This represents the service entity for event stream.
    /// </summary>
    public class EventStreamService : IEventStreamService
    {
        private readonly IEventProcessor _processor;
        private readonly IRequestBuilder _builder;
        private readonly IEnumerable<IRequestHandler> _handlers;

        private bool _disposed;

        /// <summary>
        /// Initializes a new instance of the <see cref="EventStreamService" /> class.
        /// </summary>
        /// <param name="processor">The event processor instance.</param>
        /// <param name="builder">The request builder instance.</param>
        /// <param name="handlers">The list of request handlers.</param>
        public EventStreamService(IEventProcessor processor, IRequestBuilder builder, params IRequestHandler[] handlers)
        {
            if (processor == null)
            {
                throw new ArgumentNullException(nameof(processor));
            }

            this._processor = processor;

            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            this._builder = builder;

            if (handlers == null)
            {
                throw new ArgumentNullException(nameof(handlers));
            }

            this._handlers = handlers;
        }

        /// <summary>
        /// Creates a new event stream asynchronously.
        /// </summary>
        /// <param name="request">The <see cref="EventStreamCreateRequest" /> instance.</param>
        /// <returns>Returns the <see cref="EventStreamCreateResponse" /> instance.</returns>
        public async Task<EventStreamCreateResponse> CreateEventStreamAsync(EventStreamCreateRequest request)
        {
            var handler = this._handlers.SingleOrDefault(p => p.CanHandle(request));
            if (handler == null)
            {
                return await Task.FromResult(default(EventStreamCreateResponse));
            }

            var ev = handler.CreateEvent(request) as EventStreamCreatedEvent;
            PopulateBaseProperties(ev);

            EventStreamCreateResponse response;
            try
            {
                await this._processor.ProcessEventsAsync(new[] { ev });
                response = new EventStreamCreateResponse()
                               {
                                   Data = new EventStreamResponseData()
                                              {
                                                  StreamId = request.StreamId
                                              }
                               };
            }
            catch (Exception ex)
            {
                response = new EventStreamCreateResponse()
                               {
                                   Error = new ResponseError()
                                           {
                                               Message = ex.Message,
                                               StackTrace = ex.StackTrace,
                                           }
                               };
            }

            return await Task.FromResult(response);
        }

        /// <summary>
        /// Changes salutation asynchronously.
        /// </summary>
        /// <param name="request">The <see cref="SalutationChangeRequest" /> instance.</param>
        /// <returns>Returns the <see cref="SalutationChangeResponse" /> instance.</returns>
        public async Task<SalutationChangeResponse> ChangeSalutationAsync(SalutationChangeRequest request)
        {
            var handler = this._handlers.SingleOrDefault(p => p.CanHandle(request));
            if (handler == null)
            {
                return await Task.FromResult(default(SalutationChangeResponse));
            }

            var ev = handler.CreateEvent(request) as SalutationChangedEvent;
            PopulateBaseProperties(ev);

            SalutationChangeResponse response;
            try
            {
                await this._processor.ProcessEventsAsync(new[] { ev });
                response = new SalutationChangeResponse()
                               {
                                   Data = new SalutationResponseData()
                                              {
                                                  Value = request.Value
                                              }
                               };
            }
            catch (Exception ex)
            {
                response = new SalutationChangeResponse()
                               {
                                   Error = new ResponseError()
                                               {
                                                   Message = ex.Message,
                                                   StackTrace = ex.StackTrace,
                                               }
                               };
            }

            return await Task.FromResult(response);
        }

        /// <summary>
        /// Changes username asynchronously.
        /// </summary>
        /// <param name="request">The <see cref="UsernameChangeRequest" /> instance.</param>
        /// <returns>Returns the <see cref="UsernameChangeResponse" /> instance.</returns>
        public async Task<UsernameChangeResponse> ChangeUsernameAsync(UsernameChangeRequest request)
        {
            var handler = this._handlers.SingleOrDefault(p => p.CanHandle(request));
            if (handler == null)
            {
                return await Task.FromResult(default(UsernameChangeResponse));
            }

            var ev = handler.CreateEvent(request) as UsernameChangedEvent;
            PopulateBaseProperties(ev);

            UsernameChangeResponse response;
            try
            {
                await this._processor.ProcessEventsAsync(new[] { ev });
                response = new UsernameChangeResponse()
                               {
                                   Data = new UsernameResponseData()
                                              {
                                                  Value = request.Value
                                              }
                               };
            }
            catch (Exception ex)
            {
                response = new UsernameChangeResponse()
                               {
                                   Error = new ResponseError()
                                               {
                                                   Message = ex.Message,
                                                   StackTrace = ex.StackTrace,
                                               }
                               };
            }

            return await Task.FromResult(response);
        }

        /// <summary>
        /// Changes email asynchronously.
        /// </summary>
        /// <param name="request">The <see cref="EmailChangeRequest" /> instance.</param>
        /// <returns>Returns the <see cref="EmailChangeResponse" /> instance.</returns>
        public async Task<EmailChangeResponse> ChangeEmailAsync(EmailChangeRequest request)
        {
            var handler = this._handlers.SingleOrDefault(p => p.CanHandle(request));
            if (handler == null)
            {
                return await Task.FromResult(default(EmailChangeResponse));
            }

            var ev = handler.CreateEvent(request) as EmailChangedEvent;
            PopulateBaseProperties(ev);

            EmailChangeResponse response;
            try
            {
                await this._processor.ProcessEventsAsync(new[] { ev });
                response = new EmailChangeResponse()
                               {
                                   Data = new EmailResponseData()
                                              {
                                                  Value = request.Value
                                              }
                               };
            }
            catch (Exception ex)
            {
                response = new EmailChangeResponse()
                               {
                                   Error = new ResponseError()
                                               {
                                                   Message = ex.Message,
                                                   StackTrace = ex.StackTrace,
                                               }
                               };
            }

            return await Task.FromResult(response);
        }

        /// <summary>
        /// Creates user asynchronously.
        /// </summary>
        /// <param name="request">The <see cref="UserCreateRequest" /> instance.</param>
        /// <returns>Returns the <see cref="UserCreateResponse" /> instance.</returns>
        public async Task<UserCreateResponse> CreateUserAsync(UserCreateRequest request)
        {
            await this._builder.BuildAsync(request);

            var handler = this._handlers.SingleOrDefault(p => p.CanHandle(request));
            if (handler == null)
            {
                return await Task.FromResult(default(UserCreateResponse));
            }

            var ev = handler.CreateEvent(request) as UserCreatedEvent;
            PopulateBaseProperties(ev);

            UserCreateResponse response;
            try
            {
                await this._processor.ProcessEventsAsync(new[] { ev });
                response = new UserCreateResponse()
                              {
                                  Data = new UserResponseData()
                                             {
                                                 Title = ev.Title,
                                                 Username = ev.Username,
                                                 Email = ev.Email,
                                             }
                              };
            }
            catch (Exception ex)
            {
                response = new UserCreateResponse()
                               {
                                   Error = new ResponseError()
                                               {
                                                   Message = ex.Message,
                                                   StackTrace = ex.StackTrace,
                                               }
                               };
            }

            return await Task.FromResult(response);
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public virtual void Dispose()
        {
            if (this._disposed)
            {
                return;
            }

            this._disposed = true;
        }

        private static void PopulateBaseProperties<T>(T ev) where T : BaseEvent
        {
            ev.EventId = Guid.NewGuid();
            ev.Sequence = DateTime.UtcNow.Ticks;
            ev.DateOccurred = DateTime.UtcNow;
            ev.Projector = Projector.System;
        }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.EventProcessors/EventProcessor.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using Aliencube.EntityContextLibrary.Interfaces;

using EventSourcingCqrsSample.EventHandlers;
using EventSourcingCqrsSample.Events;
using EventSourcingCqrsSample.Repositories;

namespace EventSourcingCqrsSample.EventProcessors
{
    /// <summary>
    /// This represents the processor entity for events.
    /// </summary>
    public class EventProcessor : IEventProcessor
    {
        private readonly IUnitOfWorkManager _uowm;
        private readonly IEnumerable<IEventHandler> _handlers;

        private bool _disposed;

        /// <summary>
        /// Initializes a new instance of the <see cref="EventProcessor" /> class.
        /// </summary>
        /// <param name="uowm"><see cref="IUnitOfWorkManager" /> instance.</param>
        /// <param name="handlers">List of event handlers.</param>
        public EventProcessor(IUnitOfWorkManager uowm, params IEventHandler[] handlers)
        {
            if (uowm == null)
            {
                throw new ArgumentNullException(nameof(uowm));
            }

            this._uowm = uowm;

            if (handlers == null)
            {
                throw new ArgumentNullException(nameof(handlers));
            }

            this._handlers = handlers;
        }

        /// <summary>
        /// Processes the list of events asynchronously.
        /// </summary>
        /// <param name="evs">List of events.</param>
        /// <returns>Returns <c>True</c>, if all events have been consumed; otherwise returns <c>False.</c></returns>
        public async Task<bool> ProcessEventsAsync(IEnumerable<BaseEvent> evs)
        {
            var results = new List<bool>();
            using (var uow = this._uowm.CreateInstance<SampleDbContext>())
            {
                uow.BeginTransaction();

                try
                {
                    foreach (var ev in evs)
                    {
                        var handlers = this.GetHandlers(ev);
                        foreach (var handler in handlers)
                        {
                            var result = await handler.ProcessAsync(ev);
                            results.Add(result);
                        }
                    }

                    uow.Commit();
                }
                catch
                {
                    uow.Rollback();
                    results.Add(false);
                    throw;
                }
            }

            return await Task.FromResult(results.TrueForAll(p => p));
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public virtual void Dispose()
        {
            if (this._disposed)
            {
                return;
            }

            this._disposed = true;
        }

        private IEnumerable<IEventHandler> GetHandlers(BaseEvent ev)
        {
            var handlers = this._handlers.Where(p => p.CanProcess(ev));
            return handlers;
        }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Models/Responses/Data/ResponseError.cs<|end_filename|>
namespace EventSourcingCqrsSample.Models.Responses.Data
{
    /// <summary>
    /// This represents the response error entity.
    /// </summary>
    public class ResponseError
    {
        /// <summary>
        /// Gets or sets the error message.
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// Gets or sets the stack trace.
        /// </summary>
        public string StackTrace { get; set; }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Models/Requests/EmailChangeRequest.cs<|end_filename|>
﻿namespace EventSourcingCqrsSample.Models.Requests
{
    /// <summary>
    /// This represents the request entity for the email changed event.
    /// </summary>
    public class EmailChangeRequest : InputChangeRequest
    {
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Models/Responses/Data/UserResponseData.cs<|end_filename|>
﻿namespace EventSourcingCqrsSample.Models.Responses.Data
{
    /// <summary>
    /// This represents the response data entity for user.
    /// </summary>
    public class UserResponseData : BaseResponseData
    {
        /// <summary>
        /// Gets or sets the title.
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        public string Username { get; set; }

        /// <summary>
        /// Gets or sets the email.
        /// </summary>
        public string Email { get; set; }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Models/Responses/Data/EventStreamResponseData.cs<|end_filename|>
﻿using System;

namespace EventSourcingCqrsSample.Models.Responses.Data
{
    /// <summary>
    /// This represents the response data entity for event stream.
    /// </summary>
    public class EventStreamResponseData : BaseResponseData
    {
        /// <summary>
        /// Gets or sets the stream Id.
        /// </summary>
        public Guid StreamId { get; set; }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Models/Responses/EmailChangeResponse.cs<|end_filename|>
﻿using EventSourcingCqrsSample.Models.Responses.Data;

namespace EventSourcingCqrsSample.Models.Responses
{
    /// <summary>
    /// This represents the response entity for the email changed event.
    /// </summary>
    public class EmailChangeResponse : BaseResponse<EmailResponseData>
    {
    }
}

<|start_filename|>src/EventSourcingCqrsSample.RequestHandlers/Map/UserCreateRequestToUserCreatedEventMapper.cs<|end_filename|>
using AutoMapper;

using EventSourcingCqrsSample.Events;
using EventSourcingCqrsSample.Models.Requests;

namespace EventSourcingCqrsSample.RequestHandlers.Map
{
    /// <summary>
    /// This represents the mapper entity for <see cref="UserCreateRequest" /> to <see cref="UserCreatedEvent" />.
    /// </summary>
    public class UserCreateRequestToUserCreatedEventMapper :
        BaseRequestToEventMapper<UserCreateRequest, UserCreatedEvent>
    {
        /// <summary>
        /// Initialises the mapping definition.
        /// </summary>
        protected override void Initialise()
        {
            if (this.Initialised)
            {
                return;
            }

            Mapper.CreateMap<UserCreateRequest, UserCreatedEvent>()
                  .ForMember(ev => ev.EventStream, o => o.MapFrom(req => req.StreamId))
                  .ForMember(ev => ev.Username, o => o.MapFrom(req => req.Name));

            this.Initialised = true;
        }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Repositories/Migrations/00_Initialise.cs<|end_filename|>
namespace EventSourcingCqrsSample.Repositories.Migrations
{
    using System;
    using System.Data.Entity.Migrations;
    
    public partial class _00_Initialise : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.EventStream",
                c => new
                    {
                        EventId = c.Guid(nullable: false),
                        StreamId = c.Guid(nullable: false),
                        Sequence = c.Long(),
                        EventName = c.String(nullable: false, maxLength: 256),
                        EventType = c.String(nullable: false, maxLength: 256),
                        EventBody = c.String(nullable: false),
                        DateOccurred = c.DateTime(nullable: false),
                        DateRecorded = c.DateTime(nullable: false),
                        DateProjected = c.DateTime(nullable: false),
                        ProjectedBy = c.Guid(nullable: false),
                    })
                .PrimaryKey(t => t.EventId);
            
            CreateTable(
                "dbo.User",
                c => new
                    {
                        UserId = c.Int(nullable: false, identity: true),
                        Title = c.String(nullable: false, maxLength: 8),
                        Name = c.String(nullable: false, maxLength: 256),
                        Email = c.String(nullable: false, maxLength: 256),
                    })
                .PrimaryKey(t => t.UserId);
            
        }
        
        public override void Down()
        {
            DropTable("dbo.User");
            DropTable("dbo.EventStream");
        }
    }
}


<|start_filename|>src/EventSourcingCqrsSample.Repositories/SampleDbContext.cs<|end_filename|>
namespace EventSourcingCqrsSample.Repositories
{
    using System;
    using System.Data.Entity;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;

    public partial class SampleDbContext : DbContext
    {
        public SampleDbContext()
            : base("name=SampleDbContext")
        {
        }

        public virtual IDbSet<EventStream> EventStreams { get; set; }
        public virtual IDbSet<User> Users { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
        }
    }
}


<|start_filename|>src/EventSourcingCqrsSample.WebApp/App_Start/MvcConfig.cs<|end_filename|>
﻿using System;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

using Autofac;
using Autofac.Integration.Mvc;

using Owin;

namespace EventSourcingCqrsSample.WebApp
{
    /// <summary>
    /// This represents the config entity for MVC.
    /// </summary>
    public static class MvcConfig
    {
        /// <summary>
        /// Configures the MVC.
        /// </summary>
        /// <param name="builder">
        /// The <see cref="IAppBuilder" /> instance.
        /// </param>
        /// <param name="container">
        /// The <see cref="IContainer" /> instance.
        /// </param>
        public static void Configure(IAppBuilder builder, IContainer container)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (container == null)
            {
                throw new ArgumentNullException(nameof(container));
            }

            RegisterDependencyResolver(container);
            RegisterAreas();
            RegisterRoutes(RouteTable.Routes);
            RegisterFilters(GlobalFilters.Filters);
            RegisterBundles(BundleTable.Bundles);
        }

        private static void RegisterDependencyResolver(IContainer container)
        {
            var resolver = new AutofacDependencyResolver(container);
            DependencyResolver.SetResolver(resolver);
        }

        private static void RegisterAreas()
        {
            AreaRegistration.RegisterAllAreas();
        }

        private static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapMvcAttributeRoutes();
        }

        private static void RegisterFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        private static void RegisterBundles(BundleCollection collection)
        {
            collection.RegisterBundles();
        }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Services/IEventStreamService.cs<|end_filename|>
﻿using System;
using System.Threading.Tasks;

using EventSourcingCqrsSample.Models.Requests;
using EventSourcingCqrsSample.Models.Responses;

namespace EventSourcingCqrsSample.Services
{
    /// <summary>
    /// This provides interfaces to the <see cref="EventStreamService" /> class.
    /// </summary>
    public interface IEventStreamService : IDisposable
    {
        /// <summary>
        /// Creates a new event stream asynchronously.
        /// </summary>
        /// <param name="request">The <see cref="EventStreamCreateRequest" /> instance.</param>
        /// <returns>Returns the <see cref="EventStreamCreateResponse" /> instance.</returns>
        Task<EventStreamCreateResponse> CreateEventStreamAsync(EventStreamCreateRequest request);

        /// <summary>
        /// Changes salutation asynchronously.
        /// </summary>
        /// <param name="request">The <see cref="SalutationChangeRequest" /> instance.</param>
        /// <returns>Returns the <see cref="SalutationChangeResponse" /> instance.</returns>
        Task<SalutationChangeResponse> ChangeSalutationAsync(SalutationChangeRequest request);

        /// <summary>
        /// Changes username asynchronously.
        /// </summary>
        /// <param name="request">The <see cref="UsernameChangeRequest" /> instance.</param>
        /// <returns>Returns the <see cref="UsernameChangeResponse" /> instance.</returns>
        Task<UsernameChangeResponse> ChangeUsernameAsync(UsernameChangeRequest request);

        /// <summary>
        /// Changes email asynchronously.
        /// </summary>
        /// <param name="request">The <see cref="EmailChangeRequest" /> instance.</param>
        /// <returns>Returns the <see cref="EmailChangeResponse" /> instance.</returns>
        Task<EmailChangeResponse> ChangeEmailAsync(EmailChangeRequest request);

        /// <summary>
        /// Creates user asynchronously.
        /// </summary>
        /// <param name="request">The <see cref="UserCreateRequest" /> instance.</param>
        /// <returns>Returns the <see cref="UserCreateResponse" /> instance.</returns>
        Task<UserCreateResponse> CreateUserAsync(UserCreateRequest request);
    }
}

<|start_filename|>src/EventSourcingCqrsSample.RequestHandlers/Map/IRequestToEventMapper.cs<|end_filename|>
﻿using System;

using EventSourcingCqrsSample.Events;
using EventSourcingCqrsSample.Models.Requests;

namespace EventSourcingCqrsSample.RequestHandlers.Map
{
    /// <summary>
    /// This provides interfaces to mappers inheriting the <see cref="BaseRequestToEventMapper{TRequest, TEvent}" /> class.
    /// </summary>
    /// <typeparam name="TRequest">Type of request.</typeparam>
    /// <typeparam name="TEvent">Type of event.</typeparam>
    public interface IRequestToEventMapper<in TRequest, out TEvent> : IDisposable
        where TRequest : BaseRequest where TEvent : BaseEvent
    {
        /// <summary>
        /// Checks whether the request instance can be mapped to the event class.
        /// </summary>
        /// <param name="request">Request instance</param>
        /// <returns>Returns <c>True</c>; if the given request can be mapped to the event class; otherwise returns <c>False</c>.</returns>
        bool CanMap(BaseRequest request);

        /// <summary>
        /// Maps the given request to the event class.
        /// </summary>
        /// <param name="request">Request to map.</param>
        /// <returns>Returns the <see cref="TEvent" /> mapped.</returns>
        TEvent Map(TRequest request);
    }
}

<|start_filename|>src/EventSourcingCqrsSample.EventHandlers/Map/BaseEventToEventStreamMapper.cs<|end_filename|>
using AutoMapper;

using EventSourcingCqrsSample.Events;
using EventSourcingCqrsSample.Repositories;

namespace EventSourcingCqrsSample.EventHandlers.Map
{
    /// <summary>
    /// This represents the mapper entity for event inheriting <see cref="BaseEvent" /> to <see cref="EventStream" />. This must be inherited.
    /// </summary>
    /// <typeparam name="T">Type of event.</typeparam>
    public abstract class BaseEventToEventStreamMapper<T> : IEventToEventStreamMapper<T> where T : BaseEvent
    {
        private bool _disposed;

        /// <summary>
        /// Gets or sets a value indicating whether the mapper definition has been initialised or not.
        /// </summary>
        protected bool Initialised { get; set; }

        /// <summary>
        /// Checks whether the event instance can be mapped to <see cref="EventStream" /> class.
        /// </summary>
        /// <param name="ev">Event instance</param>
        /// <returns>Returns <c>True</c>; if the given event can be mapped to <see cref="EventStream" />; otherwise returns <c>False</c>.</returns>
        public virtual bool CanMap(BaseEvent ev)
        {
            var @event = ev as T;
            return @event != null;
        }

        /// <summary>
        /// Maps the given event to the <see cref="EventStream" /> class.
        /// </summary>
        /// <param name="ev">Event to map.</param>
        /// <returns>Returns the <see cref="EventStream" /> mapped.</returns>
        public virtual EventStream Map(T ev)
        {
            if (!this.CanMap(ev))
            {
                return null;
            }

            this.Initialise();

            var mapped = Mapper.Map<EventStream>(ev);
            return mapped;
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public virtual void Dispose()
        {
            if (this._disposed)
            {
                return;
            }

            this._disposed = true;
        }

        /// <summary>
        /// Initialises the mapping definition.
        /// </summary>
        protected abstract void Initialise();
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Models/Requests/UserCreateRequest.cs<|end_filename|>
﻿namespace EventSourcingCqrsSample.Models.Requests
{
    /// <summary>
    /// This represents the request entity for the user created event.
    /// </summary>
    public class UserCreateRequest : BaseRequest
    {
        /// <summary>
        /// Gets or sets the title.
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets the email.
        /// </summary>
        public string Email { get; set; }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Events/InputValueChangedEvent.cs<|end_filename|>
﻿namespace EventSourcingCqrsSample.Events
{
    /// <summary>
    /// This represents the event entity for all inputs when their values have been changed. This must be inherited.
    /// </summary>
    public abstract class InputValueChangedEvent : BaseEvent
    {
        /// <summary>
        /// Gets or sets the element Id.
        /// </summary>
        public string ElementId { get; set; }

        /// <summary>
        /// Gets or sets the element name.
        /// </summary>
        public string ElementName { get; set; }

        /// <summary>
        /// Gets or sets the element value.
        /// </summary>
        public string ElementValue { get; set; }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Repositories/User.cs<|end_filename|>
namespace EventSourcingCqrsSample.Repositories
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    [Table("User")]
    public partial class User
    {
        public int UserId { get; set; }

        [Required]
        [StringLength(8)]
        public string Title { get; set; }

        [Required]
        [StringLength(256)]
        public string Name { get; set; }

        [Required]
        [StringLength(256)]
        public string Email { get; set; }
    }
}


<|start_filename|>src/EventSourcingCqrsSample.WebApp/App_Start/DependencyConfig.cs<|end_filename|>
﻿using System.Reflection;
using System.Web;

using Aliencube.EntityContextLibrary;
using Aliencube.EntityContextLibrary.Interfaces;

using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;

using EventSourcingCqrsSample.EventHandlers;
using EventSourcingCqrsSample.EventHandlers.Map;
using EventSourcingCqrsSample.EventProcessors;
using EventSourcingCqrsSample.Repositories;
using EventSourcingCqrsSample.RequestBuilders;
using EventSourcingCqrsSample.RequestHandlers;
using EventSourcingCqrsSample.RequestHandlers.Map;
using EventSourcingCqrsSample.Services;
using EventSourcingCqrsSample.WebApp.Controllers;

namespace EventSourcingCqrsSample.WebApp
{
    /// <summary>
    /// This represents the configuration entity for dependency injection.
    /// </summary>
    public static class DependencyConfig
    {
        private const string SampleDbContext = "SampleDbContext";

        /// <summary>
        /// Configures <see cref="Autofac" /> dependency injection.
        /// </summary>
        /// <returns>Returns <see cref="IContainer" /> instance.</returns>
        public static IContainer Configure()
        {
            var builder = new ContainerBuilder();

            RegisterDbContext(builder);
            RegisterRepositories(builder);
            RegisterServices(builder);
            RegisterEventHandlerMappers(builder);
            RegisterEventHandlers(builder);
            RegisterRequestBuilders(builder);
            RegisterRequestHandlerMappers(builder);
            RegisterRequestHandlers(builder);
            RegisterEventProcessors(builder);
            RegisterWebAbstractions(builder);
            RegisterMvcControllers(builder);
            RegisterApiControllers(builder);

            var container = builder.Build();
            return container;
        }

        private static void RegisterDbContext(ContainerBuilder builder)
        {
            // DB context.
            builder.RegisterType<DbContextFactory<SampleDbContext>>()
                   .Named<IDbContextFactory>(SampleDbContext)
                   .As<IDbContextFactory>()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();

            // unit of work managers.
            builder.Register(p => new UnitOfWorkManager(p.ResolveNamed<IDbContextFactory>(SampleDbContext)))
                   .As<IUnitOfWorkManager>()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();
        }

        private static void RegisterRepositories(ContainerBuilder builder)
        {
            builder.RegisterType<BaseRepository<EventStream>>()
                   .AsImplementedInterfaces()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();

            builder.RegisterType<BaseRepository<User>>()
                   .AsImplementedInterfaces()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();
        }

        private static void RegisterServices(ContainerBuilder builder)
        {
            builder.RegisterType<EventStreamService>()
                   .As<IEventStreamService>()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();
        }

        private static void RegisterEventHandlerMappers(ContainerBuilder builder)
        {
            builder.RegisterType<EmailChangedEventToEventStreamMapper>()
                   .AsImplementedInterfaces()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();

            builder.RegisterType<EventStreamCreatedEventToEventStreamMapper>()
                   .AsImplementedInterfaces()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();

            builder.RegisterType<SalutationChangedEventToEventStreamMapper>()
                   .AsImplementedInterfaces()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();

            builder.RegisterType<UsernameChangedEventToEventStreamMapper>()
                   .AsImplementedInterfaces()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();

            builder.RegisterType<UserCreatedEventToEventStreamMapper>()
                   .AsImplementedInterfaces()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();
        }

        private static void RegisterEventHandlers(ContainerBuilder builder)
        {
            builder.RegisterType<EmailChangedEventHandler>()
                   .As<IEventHandler>()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();

            builder.RegisterType<EventStreamCreatedEventHandler>()
                   .As<IEventHandler>()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();

            builder.RegisterType<SalutationChangedEventHandler>()
                   .As<IEventHandler>()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();

            builder.RegisterType<UsernameChangedEventHandler>()
                   .As<IEventHandler>()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();

            builder.RegisterType<UserCreatedEventHandler>()
                   .As<IEventHandler>()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();
        }

        private static void RegisterRequestBuilders(ContainerBuilder builder)
        {
            builder.RegisterType<UserCreateRequestBuilder>()
                   .As<IRequestBuilder>()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();
        }

        private static void RegisterRequestHandlerMappers(ContainerBuilder builder)
        {
            builder.RegisterType<EmailChangeRequestToEmailChangedEventMapper>()
                   .AsImplementedInterfaces()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();

            builder.RegisterType<EventStreamCreateRequestToEventStreamCreatedEventMapper>()
                   .AsImplementedInterfaces()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();

            builder.RegisterType<SalutationChangeRequestToSalutationChangedEventMapper>()
                   .AsImplementedInterfaces()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();

            builder.RegisterType<UserCreateRequestToUserCreatedEventMapper>()
                   .AsImplementedInterfaces()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();

            builder.RegisterType<UsernameChangeRequestToUsernameChangedEventMapper>()
                   .AsImplementedInterfaces()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();
        }

        private static void RegisterRequestHandlers(ContainerBuilder builder)
        {
            builder.RegisterType<EmailChangeRequestHandler>()
                   .As<IRequestHandler>()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();

            builder.RegisterType<EventStreamCreateRequestHandler>()
                   .As<IRequestHandler>()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();

            builder.RegisterType<SalutationChangeRequestHandler>()
                   .As<IRequestHandler>()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();

            builder.RegisterType<UserCreateRequestHandler>()
                   .As<IRequestHandler>()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();

            builder.RegisterType<UsernameChangeRequestHandler>()
                   .As<IRequestHandler>()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();
        }

        private static void RegisterEventProcessors(ContainerBuilder builder)
        {
            builder.RegisterType<EventProcessor>()
                   .As<IEventProcessor>()
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();
        }

        private static void RegisterWebAbstractions(ContainerBuilder builder)
        {
            builder.RegisterModule<AutofacWebTypesModule>();
        }

        private static void RegisterMvcControllers(ContainerBuilder builder)
        {
            builder.RegisterControllers(typeof(Startup).Assembly)
                   .OnActivating(e =>
                                 {
                                     var httpContext = e.Context.Resolve<HttpContextBase>();
                                 
                                     ((HomeController)e.Instance).SetHttpContext(httpContext);
                                 })
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();
        }

        private static void RegisterApiControllers(ContainerBuilder builder)
        {
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly())
                   .PropertiesAutowired()
                   .InstancePerLifetimeScope();
        }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Models/Requests/BaseRequest.cs<|end_filename|>
﻿using System;

namespace EventSourcingCqrsSample.Models.Requests
{
    /// <summary>
    /// This represents the base request entity. This must be inherited.
    /// </summary>
    public abstract class BaseRequest
    {
        /// <summary>
        /// Gets or sets the stream Id.
        /// </summary>
        public Guid StreamId { get; set; }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Models/Responses/SalutationChangeResponse.cs<|end_filename|>
﻿using EventSourcingCqrsSample.Models.Responses.Data;

namespace EventSourcingCqrsSample.Models.Responses
{
    /// <summary>
    /// This represents the response entity for the salutation changed event.
    /// </summary>
    public class SalutationChangeResponse : BaseResponse<SalutationResponseData>
    {
    }
}

<|start_filename|>src/EventSourcingCqrsSample.RequestHandlers/IRequestHandler.cs<|end_filename|>
﻿using System;

using EventSourcingCqrsSample.Events;
using EventSourcingCqrsSample.Models.Requests;

namespace EventSourcingCqrsSample.RequestHandlers
{
    /// <summary>
    /// This provides interfaces to the classes inheriting the <see cref="BaseRequestHandler{TRequest, TEvent}" /> class.
    /// </summary>
    public interface IRequestHandler : IDisposable
    {
        /// <summary>
        /// Checks whether the given request can be handled or not.
        /// </summary>
        /// <param name="request">Request instance.</param>
        /// <returns>Returns <c>True</c>, if the given request can be processed; otherwise returns <c>False</c>.</returns>
        bool CanHandle(BaseRequest request);

        /// <summary>
        /// Create the event from the request.
        /// </summary>
        /// <param name="request">Request instance.</param>
        /// <returns>Returns the event created.</returns>
        BaseEvent CreateEvent(BaseRequest request);
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Models/Responses/Data/UsernameResponseData.cs<|end_filename|>
﻿namespace EventSourcingCqrsSample.Models.Responses.Data
{
    /// <summary>
    /// This represents the response data entity for username.
    /// </summary>
    public class UsernameResponseData : BaseResponseData
    {
        /// <summary>
        /// Gets or sets the salutation value.
        /// </summary>
        public string Value { get; set; }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Models/ViewModels/Salutations/Salutation.cs<|end_filename|>
﻿namespace EventSourcingCqrsSample.Models.ViewModels.Salutations
{
    /// <summary>
    /// This represents the entity for salutation.
    /// </summary>
    public class Salutation
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Salutation" /> class.
        /// </summary>
        public Salutation()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Salutation" /> class.
        /// </summary>
        /// <param name="text">Salutation text.</param>
        /// <param name="value">Salutation value.</param>
        public Salutation(string text, string value)
        {
            this.Text = text;
            this.Value = value;
        }

        /// <summary>
        /// Gets or sets the salutation text.
        /// </summary>
        public string Text { get; set; }

        /// <summary>
        /// Gets or sets the salutation value.
        /// </summary>
        public string Value { get; set; }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.EventHandlers/Map/SalutationChangedEventToEventStreamMapper.cs<|end_filename|>
﻿using AutoMapper;

using EventSourcingCqrsSample.Events;
using EventSourcingCqrsSample.Repositories;

using Newtonsoft.Json;

namespace EventSourcingCqrsSample.EventHandlers.Map
{
    /// <summary>
    /// This represents the mapper entity for <see cref="SalutationChangedEvent" /> to <see cref="EventStream" />.
    /// </summary>
    public class SalutationChangedEventToEventStreamMapper : BaseEventToEventStreamMapper<SalutationChangedEvent>
    {
        /// <summary>
        /// Initialises the mapping definition.
        /// </summary>
        protected override void Initialise()
        {
            if (this.Initialised)
            {
                return;
            }

            Mapper.CreateMap<SalutationChangedEvent, EventStream>()
                  .ForMember(es => es.StreamId, o => o.MapFrom(ev => ev.EventStream))
                  .ForMember(es => es.EventName, o => o.MapFrom(ev => ev.Name))
                  .ForMember(es => es.EventType, o => o.MapFrom(ev => ev.GetType().FullName))
                  .ForMember(es => es.EventBody, o => o.MapFrom(ev => JsonConvert.SerializeObject(ev)))
                  .ForMember(es => es.DateProjected, o => o.MapFrom(ev => ev.Projector.DateProjected))
                  .ForMember(es => es.ProjectedBy, o => o.MapFrom(ev => ev.Projector.ProjectorId));

            this.Initialised = true;
        }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Events/BaseEvent.cs<|end_filename|>
﻿using System;

namespace EventSourcingCqrsSample.Events
{
    /// <summary>
    /// This represents the base event entity. This must be inherited.
    /// </summary>
    public abstract class BaseEvent
    {
        /// <summary>
        /// Gets or sets the event Id.
        /// </summary>
        public Guid EventId { get; set; }

        /// <summary>
        /// Gets the name of the event.
        /// </summary>
        public abstract string Name { get; }

        /// <summary>
        /// Gets or sets the event stream.
        /// </summary>
        public Guid EventStream { get; set; }

        /// <summary>
        /// Gets or sets the sequence of the event.
        /// </summary>
        public long Sequence { get; set; }

        /// <summary>
        /// Gets or sets the date in UTC when the event has occurred.
        /// </summary>
        public DateTime DateOccurred { get; set; }

        /// <summary>
        /// Gets or sets the <see cref="Projector" />.
        /// </summary>
        public Projector Projector { get; set; }

        /// <summary>
        /// Gets or sets the date in UTC when the event has been recorded.
        /// </summary>
        public DateTime DateRecorded { get; set; }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Models/Responses/UserCreateResponse.cs<|end_filename|>
using EventSourcingCqrsSample.Models.Responses.Data;

namespace EventSourcingCqrsSample.Models.Responses
{
    /// <summary>
    /// This represents the response entity for the user created event.
    /// </summary>
    public class UserCreateResponse : BaseResponse<UserResponseData>
    {
    }
}

<|start_filename|>src/EventSourcingCqrsSample.RequestHandlers/EmailChangeRequestHandler.cs<|end_filename|>
﻿using System;

using EventSourcingCqrsSample.Events;
using EventSourcingCqrsSample.Models.Requests;
using EventSourcingCqrsSample.RequestHandlers.Map;

namespace EventSourcingCqrsSample.RequestHandlers
{
    /// <summary>
    /// This represents the request handler entity for email change.
    /// </summary>
    public class EmailChangeRequestHandler : BaseRequestHandler<EmailChangeRequest, EmailChangedEvent>
    {
        private readonly IRequestToEventMapper<EmailChangeRequest, EmailChangedEvent> _mapper;

        /// <summary>
        /// Initializes a new instance of the <see cref="EmailChangeRequestHandler" /> class.
        /// </summary>
        /// <param name="mapper">The event mapper instance.</param>
        public EmailChangeRequestHandler(IRequestToEventMapper<EmailChangeRequest, EmailChangedEvent> mapper)
        {
            if (mapper == null)
            {
                throw new ArgumentNullException(nameof(mapper));
            }

            this._mapper = mapper;
        }

        /// <summary>
        /// Called while creating the event from the request.
        /// </summary>
        /// <param name="request">Request instance.</param>
        /// <returns>Returns the event created.</returns>
        protected override EmailChangedEvent OnCreatingEvent(BaseRequest request)
        {
            var @event = this._mapper.Map(request as EmailChangeRequest);
            return @event;
        }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Models/Requests/EventStreamCreateRequest.cs<|end_filename|>
﻿namespace EventSourcingCqrsSample.Models.Requests
{
    /// <summary>
    /// This represents the request entity for event stream created event.
    /// </summary>
    public class EventStreamCreateRequest : BaseRequest
    {
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Events/EmailChangedEvent.cs<|end_filename|>
﻿namespace EventSourcingCqrsSample.Events
{
    /// <summary>
    /// This represents the event entity when email change occurs.
    /// </summary>
    public class EmailChangedEvent : InputValueChangedEvent
    {
        /// <summary>
        /// Gets the name of the event.
        /// </summary>
        public override string Name => this.GetType().Name;
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Models/Responses/UsernameChangeResponse.cs<|end_filename|>
﻿using EventSourcingCqrsSample.Models.Responses.Data;

namespace EventSourcingCqrsSample.Models.Responses
{
    /// <summary>
    /// This represents the response entity for the username changed event.
    /// </summary>
    public class UsernameChangeResponse : BaseResponse<UsernameResponseData>
    {
    }
}

<|start_filename|>src/EventSourcingCqrsSample.WebApp/Controllers/SalutationController.cs<|end_filename|>
﻿using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Http;

using EventSourcingCqrsSample.Models.ViewModels.Salutations;

namespace EventSourcingCqrsSample.WebApp.Controllers
{
    /// <summary>
    /// This represents the API controller entity for salutation.
    /// </summary>
    [RoutePrefix("api/salutations")]
    public class SalutationController : ApiController
    {
        /// <summary>
        /// Gets the list of <see cref="Salutation" />s.
        /// </summary>
        /// <returns>Returns the list of <see cref="Salutation" />s.</returns>
        [Route("")]
        public virtual async Task<SalutationCollection> Get()
        {
            var salutations = new List<Salutation>()
                                      {
                                          new Salutation("Mr", "Mr"),
                                          new Salutation("Mrs", "Mrs"),
                                          new Salutation("Ms", "Ms"),
                                          new Salutation("Mx", "Mx"),
                                      };

            var collection = new SalutationCollection(salutations);
            return await Task.FromResult(collection);
        }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.WebApp/App_Start/BundleConfig.cs<|end_filename|>
﻿using System.Web.Optimization;

namespace EventSourcingCqrsSample.WebApp
{
    /// <summary>
    /// This represents the config entity for bundles.
    /// </summary>
    public static class BundleConfig
    {
        /// <summary>
        /// Registers bundled JavaScripts and CSS files.
        /// </summary>
        /// <param name="bundles">The <see cref="BundleCollection" /> instance.</param>
        /// <remarks>For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862</remarks>
        public static void RegisterBundles(this BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                        "~/Scripts/bootstrap.js"));

            bundles.Add(new ScriptBundle("~/bundles/angular").Include(
                        "~/Scripts/angular.min.js",
                        "~/Scripts/angular-animate.min.js",
                        "~/Scripts/angular-route.min.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                        "~/Content/bootstrap.css",
                        "~/Content/site.css"));
        }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Events/UserCreatedEvent.cs<|end_filename|>
﻿namespace EventSourcingCqrsSample.Events
{
    /// <summary>
    /// This represents the event entity when user is created.
    /// </summary>
    public class UserCreatedEvent : BaseEvent
    {
        /// <summary>
        /// Gets the name of the event.
        /// </summary>
        public override string Name => this.GetType().Name;

        /// <summary>
        /// Gets or sets the title.
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// Gets or sets the username.
        /// </summary>
        public string Username { get; set; }

        /// <summary>
        /// Gets or sets the email.
        /// </summary>
        public string Email { get; set; }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Models/Responses/Data/BaseResponseData.cs<|end_filename|>
﻿namespace EventSourcingCqrsSample.Models.Responses.Data
{
    /// <summary>
    /// This represents the base response data entity. This must be inherited.
    /// </summary>
    public abstract class BaseResponseData
    {
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Models/ViewModels/Home/HomeIndexViewModel.cs<|end_filename|>
﻿namespace EventSourcingCqrsSample.Models.ViewModels.Home
{
    /// <summary>
    /// This represents the view model entity for /home/index
    /// </summary>
    public class HomeIndexViewModel
    {
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Models/Responses/EventStreamCreateResponse.cs<|end_filename|>
﻿using EventSourcingCqrsSample.Models.Responses.Data;

namespace EventSourcingCqrsSample.Models.Responses
{
    /// <summary>
    /// This represents the response entity for event stream created event.
    /// </summary>
    public class EventStreamCreateResponse : BaseResponse<EventStreamResponseData>
    {
    }
}

<|start_filename|>src/EventSourcingCqrsSample.RequestHandlers/SalutationChangeRequestHandler.cs<|end_filename|>
﻿using System;

using EventSourcingCqrsSample.Events;
using EventSourcingCqrsSample.Models.Requests;
using EventSourcingCqrsSample.RequestHandlers.Map;

namespace EventSourcingCqrsSample.RequestHandlers
{
    /// <summary>
    /// This represents the request handler entity for salutation change.
    /// </summary>
    public class SalutationChangeRequestHandler : BaseRequestHandler<SalutationChangeRequest, SalutationChangedEvent>
    {
        private readonly IRequestToEventMapper<SalutationChangeRequest, SalutationChangedEvent> _mapper;

        /// <summary>
        /// Initializes a new instance of the <see cref="SalutationChangeRequestHandler" /> class.
        /// </summary>
        /// <param name="mapper">The event mapper instance.</param>
        public SalutationChangeRequestHandler(IRequestToEventMapper<SalutationChangeRequest, SalutationChangedEvent> mapper)
        {
            if (mapper == null)
            {
                throw new ArgumentNullException(nameof(mapper));
            }

            this._mapper = mapper;
        }

        /// <summary>
        /// Called while creating the event from the request.
        /// </summary>
        /// <param name="request">Request instance.</param>
        /// <returns>Returns the event created.</returns>
        protected override SalutationChangedEvent OnCreatingEvent(BaseRequest request)
        {
            var @event = this._mapper.Map(request as SalutationChangeRequest);
            return @event;
        }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Models/ViewModels/Salutations/SalutationCollection.cs<|end_filename|>
﻿using System.Collections.Generic;
using System.Linq;

using Newtonsoft.Json;

namespace EventSourcingCqrsSample.Models.ViewModels.Salutations
{
    /// <summary>
    /// This represents the collection entity for salutations.
    /// </summary>
    public class SalutationCollection
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="SalutationCollection" /> class.
        /// </summary>
        public SalutationCollection()
        {
            this.Salutations = new List<Salutation>();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SalutationCollection" /> class.
        /// </summary>
        /// <param name="salutations">The list of <see cref="Salutation" /> objects.</param>
        public SalutationCollection(IEnumerable<Salutation> salutations)
        {
            this.Salutations = salutations.ToList();
        }

        /// <summary>
        /// Gets or sets the list of salutations.
        /// </summary>
        [JsonProperty(PropertyName = "data")]
        public List<Salutation> Salutations { get; set; }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.EventProcessors/IEventProcessor.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;

using EventSourcingCqrsSample.Events;

namespace EventSourcingCqrsSample.EventProcessors
{
    /// <summary>
    /// This provides interfaces to the <see cref="EventProcessor" /> class.
    /// </summary>
    public interface IEventProcessor : IDisposable
    {
        /// <summary>
        /// Processes the list of events asynchronously.
        /// </summary>
        /// <param name="evs">List of events.</param>
        /// <returns>Returns <c>True</c>, if all events have been consumed; otherwise returns <c>False.</c></returns>
        Task<bool> ProcessEventsAsync(IEnumerable<BaseEvent> evs);
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Models/Requests/SalutationChangeRequest.cs<|end_filename|>
﻿namespace EventSourcingCqrsSample.Models.Requests
{
    /// <summary>
    /// This represents the request entity for the salutation changed event.
    /// </summary>
    public class SalutationChangeRequest : InputChangeRequest
    {
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Models/Requests/UsernameChangeRequest.cs<|end_filename|>
﻿namespace EventSourcingCqrsSample.Models.Requests
{
    /// <summary>
    /// This represents the request entity for the username changed event.
    /// </summary>
    public class UsernameChangeRequest : InputChangeRequest
    {
    }
}

<|start_filename|>src/EventSourcingCqrsSample.RequestHandlers/Map/BaseRequestToEventMapper.cs<|end_filename|>
using AutoMapper;

using EventSourcingCqrsSample.Events;
using EventSourcingCqrsSample.Models.Requests;

namespace EventSourcingCqrsSample.RequestHandlers.Map
{
    /// <summary>
    /// This represents the mapper entity for requests to events. This must be inherited.
    /// </summary>
    /// <typeparam name="TRequest">Type of request.</typeparam>
    /// <typeparam name="TEvent">Type of event.</typeparam>
    public abstract class BaseRequestToEventMapper<TRequest, TEvent> : IRequestToEventMapper<TRequest, TEvent>
        where TRequest : BaseRequest where TEvent : BaseEvent
    {
        private bool _disposed;

        /// <summary>
        /// Gets or sets a value indicating whether the mapper definition has been initialised or not.
        /// </summary>
        protected bool Initialised { get; set; }

        /// <summary>
        /// Checks whether the request instance can be mapped to the event class.
        /// </summary>
        /// <param name="request">Request instance</param>
        /// <returns>Returns <c>True</c>; if the given request can be mapped to the event class; otherwise returns <c>False</c>.</returns>
        public virtual bool CanMap(BaseRequest request)
        {
            var casted = request as TRequest;
            return casted != null;
        }

        /// <summary>
        /// Maps the given request to the event class.
        /// </summary>
        /// <param name="request">Request to map.</param>
        /// <returns>Returns the <see cref="TEvent" /> mapped.</returns>
        public virtual TEvent Map(TRequest request)
        {
            if (!this.CanMap(request))
            {
                return null;
            }

            this.Initialise();

            var mapped = Mapper.Map<TEvent>(request);
            return mapped;
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public virtual void Dispose()
        {
            if (this._disposed)
            {
                return;
            }

            this._disposed = true;
        }

        /// <summary>
        /// Initialises the mapping definition.
        /// </summary>
        protected abstract void Initialise();
    }
}

<|start_filename|>src/EventSourcingCqrsSample.EventHandlers/Map/IEventToEventStreamMapper.cs<|end_filename|>
﻿using System;

using EventSourcingCqrsSample.Events;
using EventSourcingCqrsSample.Repositories;

namespace EventSourcingCqrsSample.EventHandlers.Map
{
    /// <summary>
    /// This provides interfaces to mappers inheriting the <see cref="BaseEventToEventStreamMapper{T}" /> class.
    /// </summary>
    /// <typeparam name="T">Type of event.</typeparam>
    public interface IEventToEventStreamMapper<in T> : IDisposable where T : BaseEvent
    {
        /// <summary>
        /// Checks whether the event instance can be mapped to <see cref="EventStream" /> class.
        /// </summary>
        /// <param name="ev">Event instance</param>
        /// <returns>Returns <c>True</c>; if the given event can be mapped to <see cref="EventStream" />; otherwise returns <c>False</c>.</returns>
        bool CanMap(BaseEvent ev);

        /// <summary>
        /// Maps the given event to the <see cref="EventStream" /> class.
        /// </summary>
        /// <param name="ev">Event to map.</param>
        /// <returns>Returns the <see cref="EventStream" /> mapped.</returns>
        EventStream Map(T ev);
    }
}

<|start_filename|>src/EventSourcingCqrsSample.RequestBuilders/UserCreateRequestBuilder.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using EventSourcingCqrsSample.EventHandlers;
using EventSourcingCqrsSample.Models.Requests;

namespace EventSourcingCqrsSample.RequestBuilders
{
    /// <summary>
    /// This represents the builder entity for user create request.
    /// </summary>
    public class UserCreateRequestBuilder : IRequestBuilder
    {
        private readonly IEnumerable<IEventHandler> _handlers;

        private bool _disposed;

        /// <summary>
        /// Initializes a new instance of the <see cref="UserCreateRequestBuilder" /> class.
        /// </summary>
        /// <param name="handlers">The list of event handler instances.</param>
        public UserCreateRequestBuilder(params IEventHandler[] handlers)
        {
            if (handlers == null)
            {
                throw new ArgumentNullException(nameof(handlers));
            }

            this._handlers = handlers;
        }

        /// <summary>
        /// Builds requests asynchronously.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>Returns <see cref="Task" />.</returns>
        public async Task BuildAsync(BaseRequest request)
        {
            var handlers = this._handlers.Where(p => p.CanBuild<UserCreateRequest>(request));
            foreach (var handler in handlers)
            {
                await handler.BuildRequestAsync(request);
            }
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public virtual void Dispose()
        {
            if (this._disposed)
            {
                return;
            }

            this._disposed = true;
        }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Events/EventStreamCreatedEvent.cs<|end_filename|>
﻿namespace EventSourcingCqrsSample.Events
{
    /// <summary>
    /// This represents the event entity when event stream is created.
    /// </summary>
    public class EventStreamCreatedEvent : BaseEvent
    {
        /// <summary>
        /// Gets the name of the event.
        /// </summary>
        public override string Name => this.GetType().Name;
    }
}

<|start_filename|>src/EventSourcingCqrsSample.WebApp/Views/Home/Index.cshtml<|end_filename|>
﻿@{
    ViewBag.Title = "Event Sourcing and CQRS Sample";
}

<h1>@ViewBag.Title</h1>

<div class="row">
    <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
        <h2>Input</h2>

        <div user-registration></div>
    </div>
    <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
        <h2>Replayed View</h2>

        <div user-replayed></div>
    </div>
    <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
        <h2>Materialised Storage View</h2>

        <div user-materialised></div>
    </div>
</div>

@section scripts
{
    @Scripts.Render("~/bundles/angular")

    <!-- Main entry for Angular -->
    <script src="~/App/App.js"></script>

    <!-- Register models -->
    <script src="~/App/models/emailModel.js"></script>
    <script src="~/App/models/errorModel.js"></script>
    <script src="~/App/models/eventStreamModel.js"></script>
    <script src="~/App/models/materialViewModel.js"></script>
    <script src="~/App/models/replayViewModel.js"></script>
    <script src="~/App/models/salutationModel.js"></script>
    <script src="~/App/models/usernameModel.js"></script>
    <script src="~/App/models/userRegistrationModel.js"></script>

    <!-- Register factories -->
    <script src="~/App/factories/emailFactory.js"></script>
    <script src="~/App/factories/eventStreamFactory.js"></script>
    <script src="~/App/factories/materialViewFactory.js"></script>
    <script src="~/App/factories/replayViewFactory.js"></script>
    <script src="~/App/factories/salutationsFactory.js"></script>
    <script src="~/App/factories/usernameFactory.js"></script>

    <!-- Register components/directives -->
    <script src="~/App/components/userEmail/userEmail.js"></script>
    <script src="~/App/components/userMaterialised/userMaterialised.js"></script>
    <script src="~/App/components/userName/userName.js"></script>
    <script src="~/App/components/userRegistration/userRegistration.js"></script>
    <script src="~/App/components/userReplayed/userReplayed.js"></script>
    <script src="~/App/components/userSalutation/userSalutation.js"></script>

    <!-- Bind Angular to the page -->
    <script>
        angular.element(document).ready(function() {
            angular.bootstrap(document, ["app"]);
        });
    </script>
}


<|start_filename|>src/EventSourcingCqrsSample.WebApp/Startup.cs<|end_filename|>
﻿using System;

using Owin;

namespace EventSourcingCqrsSample.WebApp
{
    /// <summary>
    /// This represents the entity for OWIN pipeline startup.
    /// </summary>
    public class Startup
    {
        /// <summary>
        /// Configures the OWIN pipeline.
        /// </summary>
        /// <param name="appBuilder">
        /// The <see cref="IAppBuilder" /> instance.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// Throws when <c>appBuilder</c> is null.
        /// </exception>
        public void Configuration(IAppBuilder appBuilder)
        {
            if (appBuilder == null)
            {
                throw new ArgumentNullException(nameof(appBuilder));
            }

            var container = DependencyConfig.Configure();

            MvcConfig.Configure(appBuilder, container);
            WebApiConfig.Configure(appBuilder, container);
        }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.WebApp/Controllers/HomeController.cs<|end_filename|>
﻿using System;
using System.Web;
using System.Web.Mvc;

using EventSourcingCqrsSample.Models.ViewModels.Home;
using EventSourcingCqrsSample.Services;

namespace EventSourcingCqrsSample.WebApp.Controllers
{
    /// <summary>
    /// This represents the controller entity for /home
    /// </summary>
    [RoutePrefix("")]
    public class HomeController : Controller
    {
        private readonly IEventStreamService _service;

        /// <summary>
        /// Initializes a new instance of the <see cref="HomeController" /> class.
        /// </summary>
        /// <param name="service">The <see cref="EventStreamService" /> instance.</param>
        public HomeController(IEventStreamService service)
        {
            if (service == null)
            {
                throw new ArgumentNullException(nameof(service));
            }

            this._service = service;

            this.HttpContext = base.HttpContext;
        }

        /// <summary>
        /// Gets the <see cref="HttpContextBase" /> instance.
        /// </summary>
        public new HttpContextBase HttpContext { get; private set; }

        /// <summary>
        /// Sets the <see cref="HttpContextBase" /> instance.
        /// </summary>
        /// <param name="httpContext">
        /// The <see cref="HttpContextBase" /> instance.
        /// </param>
        public void SetHttpContext(HttpContextBase httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }

            this.HttpContext = httpContext;
        }

        /// <summary>
        /// Runs when /home/index is requested.
        /// </summary>
        /// <returns>Returns the <see cref="HomeIndexViewModel" /> instance.</returns>
        [Route("")]
        public virtual ActionResult Index()
        {
            var vm = new HomeIndexViewModel();
            return this.View(vm);
        }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.RequestHandlers/Map/EventStreamCreateRequestToEventStreamCreatedEventMapper.cs<|end_filename|>
﻿using AutoMapper;

using EventSourcingCqrsSample.Events;
using EventSourcingCqrsSample.Models.Requests;

namespace EventSourcingCqrsSample.RequestHandlers.Map
{
    /// <summary>
    /// This represents the mapper entity for <see cref="EventStreamCreateRequest" /> to <see cref="EventStreamCreatedEvent" />.
    /// </summary>
    public class EventStreamCreateRequestToEventStreamCreatedEventMapper :
        BaseRequestToEventMapper<EventStreamCreateRequest, EventStreamCreatedEvent>
    {
        /// <summary>
        /// Initialises the mapping definition.
        /// </summary>
        protected override void Initialise()
        {
            if (this.Initialised)
            {
                return;
            }

            Mapper.CreateMap<EventStreamCreateRequest, EventStreamCreatedEvent>()
                  .ForMember(ev => ev.EventStream, o => o.MapFrom(req => req.StreamId));

            this.Initialised = true;
        }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.RequestBuilders/IRequestBuilder.cs<|end_filename|>
﻿using System;
using System.Threading.Tasks;

using EventSourcingCqrsSample.Models.Requests;

namespace EventSourcingCqrsSample.RequestBuilders
{
    /// <summary>
    /// This provides interfaces to request builders.
    /// </summary>
    public interface IRequestBuilder : IDisposable
    {
        /// <summary>
        /// Builds requests asynchronously.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>Returns <see cref="Task" />.</returns>
        Task BuildAsync(BaseRequest request);
    }
}

<|start_filename|>src/EventSourcingCqrsSample.WebApp/Controllers/InputValueChangedEventController.cs<|end_filename|>
﻿using System;
using System.Threading.Tasks;
using System.Web.Http;

using EventSourcingCqrsSample.Models.Requests;
using EventSourcingCqrsSample.Models.Responses;
using EventSourcingCqrsSample.Services;

namespace EventSourcingCqrsSample.WebApp.Controllers
{
    /// <summary>
    /// This represents the API controller entity for input value changed events.
    /// </summary>
    [RoutePrefix("api/events")]
    public class InputValueChangedEventController : ApiController
    {
        private readonly IEventStreamService _service;

        /// <summary>
        /// Initializes a new instance of the <see cref="InputValueChangedEventController" /> class.
        /// </summary>
        /// <param name="service">The <see cref="EventStreamService "/> instance.
        /// </param>
        public InputValueChangedEventController(IEventStreamService service)
        {
            if (service == null)
            {
                throw new ArgumentNullException(nameof(service));
            }

            this._service = service;
        }

        /// <summary>
        /// Gets the event stream.
        /// </summary>
        /// <returns>Returns the <see cref="EventStreamCreateResponse" /> instance.
        /// </returns>
        [Route("stream")]
        public virtual async Task<EventStreamCreateResponse> GetEventStream()
        {
            var request = new EventStreamCreateRequest() { StreamId = Guid.NewGuid() };
            var response = await this._service.CreateEventStreamAsync(request);
            return response;
        }

        /// <summary>
        /// Sets the salutation value.
        /// </summary>
        /// <param name="request">The <see cref="SalutationChangeRequest" /> instance.</param>
        /// <returns>Returns the <see cref="SalutationChangeResponse" /> instance.</returns>
        [HttpPost]
        [Route("salutation-changed")]
        public virtual async Task<SalutationChangeResponse> SetSalutation([FromBody] SalutationChangeRequest request)
        {
            var response = await this._service.ChangeSalutationAsync(request);
            return response;
        }

        /// <summary>
        /// Sets the username value.
        /// </summary>
        /// <param name="request">The <see cref="UsernameChangeRequest" /> instance.</param>
        /// <returns>Returns the <see cref="UsernameChangeResponse" /> instance.</returns>
        [HttpPost]
        [Route("username-changed")]
        public virtual async Task<UsernameChangeResponse> SetUsername([FromBody] UsernameChangeRequest request)
        {
            var response = await this._service.ChangeUsernameAsync(request);
            return response;
        }

        /// <summary>
        /// Sets the email value.
        /// </summary>
        /// <param name="request">The <see cref="EmailChangeRequest" /> instance.</param>
        /// <returns>Returns the <see cref="EmailChangeResponse" /> instance.</returns>
        [HttpPost]
        [Route("email-changed")]
        public virtual async Task<EmailChangeResponse> SetEmail([FromBody] EmailChangeRequest request)
        {
            var response = await this._service.ChangeEmailAsync(request);
            return response;
        }

        /// <summary>
        /// Sets the user.
        /// </summary>
        /// <param name="request">The <see cref="UserCreateRequest" /> instance.</param>
        /// <returns>Returns the <see cref="UserCreateResponse" /> instance.</returns>
        [HttpPost]
        [Route("registration")]
        public virtual async Task<UserCreateResponse> SetUser([FromBody] UserCreateRequest request)
        {
            var response = await this._service.CreateUserAsync(request);
            return response;
        }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.RequestHandlers/Map/EmailChangeRequestToEmailChangedEventMapper.cs<|end_filename|>
﻿using AutoMapper;

using EventSourcingCqrsSample.Events;
using EventSourcingCqrsSample.Models.Requests;

namespace EventSourcingCqrsSample.RequestHandlers.Map
{
    /// <summary>
    /// This represents the mapper entity for <see cref="EmailChangeRequest" /> to <see cref="EmailChangedEvent" />.
    /// </summary>
    public class EmailChangeRequestToEmailChangedEventMapper :
        BaseRequestToEventMapper<EmailChangeRequest, EmailChangedEvent>
    {
        /// <summary>
        /// Initialises the mapping definition.
        /// </summary>
        protected override void Initialise()
        {
            if (this.Initialised)
            {
                return;
            }

            Mapper.CreateMap<EmailChangeRequest, EmailChangedEvent>()
                  .ForMember(ev => ev.EventStream, o => o.MapFrom(req => req.StreamId))
                  .ForMember(ev => ev.ElementId, o => o.MapFrom(req => req.Id))
                  .ForMember(ev => ev.ElementName, o => o.MapFrom(req => req.Name))
                  .ForMember(ev => ev.ElementValue, o => o.MapFrom(req => req.Value));

            this.Initialised = true;
        }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.EventHandlers/UserCreatedEventHandler.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;

using Aliencube.EntityContextLibrary.Interfaces;

using EventSourcingCqrsSample.EventHandlers.Map;
using EventSourcingCqrsSample.Events;
using EventSourcingCqrsSample.Repositories;

using Newtonsoft.Json;

namespace EventSourcingCqrsSample.EventHandlers
{
    /// <summary>
    /// This represents the processor entity for the <see cref="UserCreatedEvent" /> class.
    /// </summary>
    public class UserCreatedEventHandler : BaseEventHandler<UserCreatedEvent>
    {
        private readonly IEventToEventStreamMapper<UserCreatedEvent> _mapper;
        private readonly IBaseRepository<EventStream> _eventRepository;
        private readonly IBaseRepository<User> _userRepository;
        private readonly string _eventType;

        /// <summary>
        /// Initializes a new instance of the <see cref="UserCreatedEventHandler" /> class.
        /// </summary>
        /// <param name="mapper">event stream mapper instance.</param>
        /// <param name="eventRepository">event stream repository instance.</param>
        /// <param name="userRepository">user repository instance.</param>
        public UserCreatedEventHandler(
            IEventToEventStreamMapper<UserCreatedEvent> mapper,
            IBaseRepository<EventStream> eventRepository,
            IBaseRepository<User> userRepository)
        {
            if (mapper == null)
            {
                throw new ArgumentNullException(nameof(mapper));
            }

            this._mapper = mapper;

            if (eventRepository == null)
            {
                throw new ArgumentNullException(nameof(eventRepository));
            }

            this._eventRepository = eventRepository;

            if (userRepository == null)
            {
                throw new ArgumentNullException(nameof(userRepository));
            }

            this._userRepository = userRepository;

            this._eventType = typeof(UserCreatedEvent).FullName;
        }

        /// <summary>
        /// Called while loading events from the repository asynchronously.
        /// </summary>
        /// <param name="streamId">The stream id.</param>
        /// <returns>Returns the list of events.</returns>
        protected override async Task<IEnumerable<BaseEvent>> OnLoadAsync(Guid streamId)
        {
            var streams = await this._eventRepository
                                    .Get()
                                    .Where(p => p.EventType.Equals(this._eventType, StringComparison.InvariantCultureIgnoreCase))
                                    .OrderByDescending(p => p.Sequence)
                                    .ToListAsync();

            var events = streams.Select(p => JsonConvert.DeserializeObject<UserCreatedEvent>(p.EventBody));
            return events;
        }

        /// <summary>
        /// Called while processing the event asynchronously.
        /// </summary>
        /// <param name="ev">Event instance.</param>
        /// <returns>Returns <c>True</c>, if the given event has been processed; otherwise returns <c>False</c>.</returns>
        protected override async Task<bool> OnProcessingAsync(BaseEvent ev)
        {
            var @event = (ev as UserCreatedEvent);
            var stream = this._mapper.Map(@event);
            this._eventRepository.Add(stream);

            var user = new User
                           {
                               Title = @event.Title,
                               Name = @event.Username,
                               Email = @event.Email
                           };
            this._userRepository.AddOrUpdate(user);

            return await Task.FromResult(true);
        }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Events/Projector.cs<|end_filename|>
using System;

namespace EventSourcingCqrsSample.Events
{
    /// <summary>
    /// This represents the entity for the projector who raised an event.
    /// </summary>
    public class Projector
    {
        private static readonly Guid SystemId = Guid.Parse("E2749C64-8955-4A70-92D7-9FBDF1E0E0C1");

        /// <summary>
        /// Initializes a new instance of the <see cref="Projector" /> class.
        /// </summary>
        /// <param name="dateProjected">Date when the event has been projected.</param>
        public Projector(DateTime? dateProjected = null)
        {
            this.DateProjected = dateProjected.GetValueOrDefault(DateTime.UtcNow);
        }

        /// <summary>
        /// Gets the <see cref="Projector" /> instance as "SYSTEM".
        /// </summary>
        public static Projector System => new Projector() { ProjectorId = SystemId };

        /// <summary>
        /// Gets or sets the unique Id who raised the event.
        /// </summary>
        public Guid ProjectorId { get; set; }

        /// <summary>
        /// Gets or sets the date when the event has been projected.
        /// </summary>
        public DateTime DateProjected { get; set; }
    }
}

<|start_filename|>src/EventSourcingCqrsSample.Repositories/Migrations/00_Initialise.Designer.cs<|end_filename|>
// <auto-generated />
namespace EventSourcingCqrsSample.Repositories.Migrations
{
    using System.CodeDom.Compiler;
    using System.Data.Entity.Migrations;
    using System.Data.Entity.Migrations.Infrastructure;
    using System.Resources;
    
    [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
    public sealed partial class _00_Initialise : IMigrationMetadata
    {
        private readonly ResourceManager Resources = new ResourceManager(typeof(_00_Initialise));
        
        string IMigrationMetadata.Id
        {
            get { return "201511101300354_00_Initialise"; }
        }
        
        string IMigrationMetadata.Source
        {
            get { return null; }
        }
        
        string IMigrationMetadata.Target
        {
            get { return Resources.GetString("Target"); }
        }
    }
}


<|start_filename|>src/EventSourcingCqrsSample.EventHandlers/UsernameChangedEventHandler.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;

using Aliencube.EntityContextLibrary.Interfaces;

using EventSourcingCqrsSample.EventHandlers.Map;
using EventSourcingCqrsSample.Events;
using EventSourcingCqrsSample.Models.Requests;
using EventSourcingCqrsSample.Repositories;

using Newtonsoft.Json;

namespace EventSourcingCqrsSample.EventHandlers
{
    /// <summary>
    /// This represents the processor entity for the <see cref="UsernameChangedEvent" /> class.
    /// </summary>
    public class UsernameChangedEventHandler : BaseEventHandler<UsernameChangedEvent>
    {
        private readonly IEventToEventStreamMapper<UsernameChangedEvent> _mapper;
        private readonly IBaseRepository<EventStream> _repository;
        private readonly string _eventType;

        /// <summary>
        /// Initializes a new instance of the <see cref="UsernameChangedEventHandler" /> class.
        /// </summary>
        /// <param name="mapper">event stream mapper instance.</param>
        /// <param name="repository">event stream repository instance.</param>
        public UsernameChangedEventHandler(IEventToEventStreamMapper<UsernameChangedEvent> mapper, IBaseRepository<EventStream> repository)
        {
            if (mapper == null)
            {
                throw new ArgumentNullException(nameof(mapper));
            }

            this._mapper = mapper;

            if (repository == null)
            {
                throw new ArgumentNullException(nameof(repository));
            }

            this._repository = repository;

            this._eventType = typeof(UsernameChangedEvent).FullName;
        }

        /// <summary>
        /// Checks whether the given request can be built or not.
        /// </summary>
        /// <typeparam name="TReq">Type of request.</typeparam>
        /// <param name="request">Request instance.</param>
        /// <returns>Returns <c>True</c>, if the given request can be built; otherwise returns <c>False</c>.</returns>
        public override bool CanBuild<TReq>(BaseRequest request)
        {
            var req = request as TReq;
            return req != null;
        }

        /// <summary>
        /// Builds the request using the latest event stored asynchronously.
        /// </summary>
        /// <param name="request">The request instance.</param>
        /// <returns>Returns the <see cref="Task"/>.</returns>
        public override async Task BuildRequestAsync(BaseRequest request)
        {
            var ev = (await this.LoadLatestAsync(request.StreamId)) as UsernameChangedEvent;
            (request as UserCreateRequest).Name = ev.ElementValue;
        }

        /// <summary>
        /// Called while loading events from the repository asynchronously.
        /// </summary>
        /// <param name="streamId">The stream id.</param>
        /// <returns>Returns the list of events.</returns>
        protected override async Task<IEnumerable<BaseEvent>> OnLoadAsync(Guid streamId)
        {
            var streams = await this._repository
                                    .Get()
                                    .Where(p => p.EventType.Equals(this._eventType, StringComparison.InvariantCultureIgnoreCase))
                                    .OrderByDescending(p => p.Sequence)
                                    .ToListAsync();

            var events = streams.Select(p => JsonConvert.DeserializeObject<UsernameChangedEvent>(p.EventBody));
            return events;
        }

        /// <summary>
        /// Called while processing the event asynchronously.
        /// </summary>
        /// <param name="ev">Event instance.</param>
        /// <returns>Returns <c>True</c>, if the given event has been processed; otherwise returns <c>False</c>.</returns>
        protected override async Task<bool> OnProcessingAsync(BaseEvent ev)
        {
            var stream = this._mapper.Map(ev as UsernameChangedEvent);

            this._repository.Add(stream);
            return await Task.FromResult(true);
        }
    }
}