How to Command Query Responsibility Segregation (CQRS) with ASP.NET MVC? - asp.net-mvc

I have been reading about Command Query Responsibility Segregation (CQRS). I sort of wonder how would this work with ASP.NET MVC? I get the idea of CQRS conceptually it sounds nice and sure does introduce some complexities (event and messaging pattern) compared to the "normal/common" approach . Also the idea of CQRS sort of against the use of ORM in some ways. I am trying to think how I could use this pattern in the coming projects so if anyone has experience in combining CQRS with ASP.NET MVC and NHibernate please give some concrete examples to help me better understand CQRS and use with ASP.NET MVC. Thanks!
Updated:
I've been going through Mark's sample code. It's a must read if you are learning CQRS.
http://github.com/MarkNijhof/Fohjin
http://cre8ivethought.com/blog/2009/11/12/cqrs--la-greg-young/
http://cre8ivethought.com/blog/2009/11/28/cqrs-trying-to-make-it-re-usable/

Please take a look at my DDDsample.Net project on CodePlex. The GUI is implemented using ASP.NET MVC while the business logic using DDD practices in 4 different variants:
classic (no CQRS)
CQRS with two NHIbernate relational data stores
CQRS with LINQ to SQL on reporting side
CQRS with Event Sourcing on command side

Cqrs makes the web project much easier. On the get site, all the queries will look like
"select * from table where id = #id"). For those simple queries, you won't need an orm like NHiberante. You don't have to use a sql database, and when you will, you can serialize your object to the database table, or use a naming convention. You can still query the read database by NHibernate, but you won't get any advantage from it, because all your queries will be the same.
public class Controller
{
public ActionResult Get(Guid id)
{
var viewModel = reportingDatabase.Get(id);
return View(viewmodel);
}
}
On the command side, the controllers will look like this:
public class Controller
{
public ActionResult Post(SomeForm form)
{
// do validation
var command = new SomeCommand(form.Property1, form.Property2);
bus.Send(command);
return redirecto(something else);
}
}
The controller just send a message, and it doesn't know where the message goes to and what the result of the message is. The mvc part of this is very simple to program. Cqrs will make writing the web-part of the application very boring, but you can make it more fun by adding some code that helps the user make decisions (optionally returning json used by ajax).

And take a look at my attempt at http://agrcqrs.codeplex.com, which is ASP.NET MVC + NHibernate

Here is a complete example I wrote for my CQRS lib Scritchy:
Example.Domain: Domain implementation
Example.Specs : Domain behavior specs using MSpec
Example.Web : Example MVC web app (demo at http://scritchyExample.apphb.com )
Example.SignalR : Example html/Javascript/SignalR web app (using the same domain code)
Creating your CQRS app using the Scritchy nuget package is pretty straightforward and gets you up and running in a few minutes

In the following post you may find interesting resources: How to adapt CQRS to projects
The one that I found particularly interesting is the CQRS Journey, from Microsoft. It may look disappointing for its dependency with Windows Azure, but wait... It has a very nice implementation of an Event Store and Enterprise Service Bus in SQL Server. You will find a lot of comments in the Demo App source code that warns you against using the SQL implementation in production... but with a few tweaks you can adapt it to your project. I did it, and it works very, very well.
The code is clean (it is from the guys from Microsoft Patterns and practices). You will find a good example of how to use dependency injection (with Unity), an simple but effective Enterprise Service Bus (with SQL Server and ADO.NET, with parallel threads), a read model with Entity Framework and a lot more. I learned from it how to do CQRS and Event Sourcing... Remember: Its all about Events

This is a bit of a late response, yet it might be helpful for someone who is looking how to implement CQRS architectural pattern in ASP.NET Core and surprisingly didn't find any proper middleware for that matter.
During my discovery process, I decided to share my findings and ended up writing a series of articles on how to do CQRS via HTTP.
CQRS: Intro
CQRS: Commanding via HTTP
CQRS: Querying via HTTP
Apart from the theoretical aspect, during the writing process, I managed to build two ready-to-use, independent middleware that are built to help you adopt CQRS in your ASP NET Core project. HTTP Commanding and HTTP Querying.
Hope it helps, if you have any questions, don't hesitate and shoot me a message.

Related

usefulness of microsoft data access application

I am planning to start learning asp.net mvc. And also I want to learn Microsoft's Data Access application block. But I dont want to waste time in MDAC block if theres a better option to go for, or if MVC provides any good feature than MDAC. As I have heard MVC architecture automatically generates code.
So, please guide me regarding this. Thanks in advance.
It's not part of MVC per se, but I'd recommend using LINQ to SQL or LINQ to Entities (Entity Framework) over the Data Access application block if you're interested in a pure MS object relational mapping. You could also look at nHibernate or a variety of other ORMs to accomplish this. Any of these would suffice as the basis for the M(odel) in an MVC application.
Try the Nerddinner example application, there is also the data access included. The tutorials are extensive: http://www.asp.net/mvc/learn/
Don't work with MDAC block if you are not forced to! Try NHibernate, Entity-Framework or LINQ instead.

What tools are available to auto-generate ASP.NET MVC REST services from domain objects?

I am developing an application for which I want to expose the basic CRUD operations on most of the database entities through REST web services. A colleague has demonstrated some impressive code generation using Grails.
I would like to be able to generate my REST services as well, but using ASP.NET MVC instead of Grails. I planning on using Fluent-NHibernate for the ORM. The underlying database is PostgreSQL.
Are there any tools available that would assist me in generating the REST services in ASP.NET MVC from the domain objects?
You should check out T4 templates.
It sounds like a really good project for S#arp Architecture. That is a nice framework built to help make putting together CRUD operations with ASP.NET MVC and NHibernate. It does also make use of T4 as was suggested for use by Jason but they have done the legwork for you really and wrapped everything up in a nice package.
Have you looked at Ado.Net Data Services (aka Astoria)? It does pretty much what you are looking for.
Take a look at the REST Services for asp.net MVC library.
To get an API that supports html, JSON and XML "out of the box", just decorate your controller with [WebApiEnabled], like this:
using System.Web.Mvc.Resources;
namespace ivu.Controllers
{
[WebApiEnabled]
public class LocationsController : Controller
{
public ActionResult Index()
{
return View(db.ReadLocations().ToList());
}
}
}
You may also want to keep an eye on ABSE (http://www.abse.info). ABSE is a code-generation and model-driven software development methodology that is completely agnostic in terms of platform and language, so you wouldn't have any trouble creating your own generators for ASP.NET MVC.
Unfortunately, ABSE is still work in progress and a reference IDE (AtomWeaver) is still in the making... but still worth a look in your case.
Or take a look at my series of articles at http://www.shouldersofgiants.co.uk/Blog where I create a framework that adds REST support to ASP.Net MVC

ASP.NET MVC Forum Application

I need to write a forum application for a friend's web site. I want to write it in C# 3.0 against the ASP.NET MVC framework, with SQL Server database.
So, I've two questions:
Should I use Linq to SQL or the Entity Framework as a database abstraction?
Should I use the ASP.NET Membership API or add Users table and implement it myself?
Thanks.
There are lots of examples around internet which is using ling with ASP.NET MVC. But may be you can add your list NHibernate. If you do not want to add i suggest Entity Framework. Using ORM's is a plus.
I always chose write my own membership management layer. If you are a person like (write your own code and be happy when you are making changes in future.) write your own membership layer. If you are looking for a quick solution ASP.NET Membership API is a good choice.
Entity Framework definitely -- see below.
ASP.net Membership API -- easy to maintain.
Reason:
Entity Framework vs LINQ to SQL
1) How about both? Just create an abstraction and you could just use either. My recommendation is to use the repository pattern.
2) The membership provider has its strengths and weaknesses. For some projects, it was far too complex for my needs. However, it is great if you need to get something running in a short amount of time.
I won't answer the first question since i'm a fan of nhibernate
for the second question adding a users table and implement membership yourself i don't think you will be able to do it at least the right way (lot of people tried to make their own membership api but they messed up !)
1) Totally depends on how complex things are going to get. If you want a quick DAL that more or less mirrors your tables in a 1:1 fashion, go for L2S (or SubSonic if you want something more mature and supported). If you are going for more of an n-tier type thing where your tables and domain model are completely different, go for an OR/M like Entity Framework (or NHibernate if you want something that is pretty much better in every way)
2) ASP.net Membership is extremely complex, and there are bits of it that are fairly poorly engineered. However, it depends on how much experience you have with these things. If you enough to know how to take steps to avoid session fixation attacks, just roll your own because chances are it will be better then the canned solution. If you have no idea what that is, take the time to learn the default one.
Something to think about, SubSonic 3 is a pretty powerful data access generation tool. From what I understand, it basically wraps Linq to Sql inside of some very useful wrappers and makes using Linq a little more intutive. You can have a pretty powerful application built up in no time flat when using SubSonic. One little issue though, if you're using a shared hosting (say GoDaddy) you'll run into a medium trust issue. In that case you can always fall back to Linq To Sql without making many changes to your code base.
As for Aspnet_Membership. Just for the amount of tools it provides, I'd reccomend using it.
Good luck, and hope this helps.

connect to DB using MVC

I have an asp.net mvc application and i need to connecto to the DB i have saw a tutorial video that connect to DB using wizard by adding DB connection and determine the DB and add a model but i need to know if i can use connection string and query the DB or calling procedures in DB ???
I need any tutorials or step by step article that describe how to connect to DB without wizard and call procedures and query tables.
Thanks in advance and i am a begineer in MVC
I hesitate to respond to this, but EVERY video you have seen is likely using an OR/M to generate the Model and the DAL. The generated DAL will likely encapsulate your calls to the stored procedures that you're asking about.
The thing is -- and here's why you're not getting the answer you're looking for -- each OR/M is going to have a different method of retrieving data from and inserting data into the database. How you retrieve data from the DB using an OR/M is going to be different if you're using Entity Framework, Linq to SQL, SubSonic, NHibernate, or any other OR/M.
So, the question is to you. Are you using a OR/M? If so, which one? If not, then you will use the standard ADO.NET calls to retrieve and store data. This is also reflected in my comment to your original question.
Yes you can (google ado.net for tutorials on ado.net), but it's not the MVC way. The MVC way is to use some sort of ORM (Object-relational mapping) such as NHibernate, Subsonic or Linq for SQL.
how to connect to DB without wizard and call procedures and query tables.
To call a procedure (here it will return no result, just perform some action):
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection .Open();
using(SqlCommand command = connection.CreateCommand(nameofthestoredprocedure))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#someparameter", somevalue);
maCommande.ExecuteNonQuery();
}
}
You can put your connection string in the config, just like you're used to.
You can call procedures the same way you would from any .Net application too. #svinto's advice about using an ORM is another way of doing things and is well worth looking at too. Many of the good examples for ASP.Net MVC use the ORM techniques.
If you don't want to go down that route, you might benefit from creating a seperate class library project that you reference from your MVC application. Your Class Library project can act as your data access layer (DAL) where you handle db calls, etc...
Your Controllers can then call your DAL and processing methods to populate entities for the Views.
Ahmy, I think the best advice to give would be before you start off developing using the MVC framework is to have a look into the principles behind the MVC pattern and domain driven design.
Specifically , have a look at repository patterns etc.
You can still add connection strings to your web.config in a block and access them as you would have done in a webforms project, after all Asp.net MVC is based on webforms. Its just likely that you wouldn't really want to do this if you're utilising MVC the way it was intended, its all about seperation of concerns.
www.asp.net has some great intro. examples worth watching.
Try downloading NerdDinner, or even better ... ContactManager iteration 1 (the tutorial directly answers your Q). Those should give you a good idea for how to handle database access. I wouldn't suggest looking at something like Oxite or MS StoreFront though, as these are a bit more complex.
To specifically answer your question: the connection string, like in ASP.NET, can go in your web.config or hard-coded in your application.

How should I structure a simple ASP.NET MVC app?

I've been reading a few things about ASP.NET MVC, SOLID and so on, and I am trying to figure out a simple "recipe" for small-to-medium ASP.NET MVC apps that would put these concepts together; the issue that I am most concerned with is ending up with controllers that are too complex and being like code-behind files in webforms, with all type of business logic into them.
I am considering the following architecture, for a small data-driven app:
Controllers: only handle requests, call an appropriate service and return the action result to the View;
Models: POCO, handle all the business logic, authorization etc. Depends on repositories, totally ignorant of persistence infrastructure.
Repositories: implement IRepository<T>, use dependency injection and is where my db code will reside; only receives and returns POCO.
I am considering having services between the controllers and the models, but if they will just pass forward method calls I am not sure how useful it would be.
Finally there should have unit tests covering the model code, and unit+integration tests covering the repository code (following the "red-green" practice, if possible)
Thoughts?
Ian Cooper had a good post on exactly this recently:
The Fat Controller
Simple recipe: (view)Presentation Layer using ASP.NET, (controller)Code Behinds or AJAX Services Layer, (model)Application Services layer, Business Model layer, and Persistance/Data Access layer.
Of course you can slice and dice numerous ways to deal with complexities in order to build a clearly readable and understandable application.
For a recent discourse on the subject, which I have found to be very good, check out this newly published book: Microsoft .NET: Architecting Applications for the Enterprise.
These walkthroughs are quite helpful:
MVC Framework and Application Structure
Walkthrough: Creating a Basic MVC Project with Unit Tests in Visual Studio
Also see: aspnet-mvc-structuring-controllers
Rob Conery has the best answer IMO.
Check out his MVC Storefront Application, which comes with complete source code and video tutorials.

Resources