Cqrs In In C Most Trivial Possible Example

CQRS in in C# most trivial possible example

Hello everybody,

today I want to make compendium of CQRS for very simple case.

So, at one of the projects I seen following way of implementing code:

public class WriteModel
{
        //common properties
        public int SomeEntity {get;set; } // ID of some entity
}

public class ReadModel : WriteModel
{
        public string AdditionalProperty {get;set; }
}

and that way of implementing it was proudly named CQRS. To be honest I wasn't very agreeable on that part, so I decided to hear opinions of other people, not only mine understanding of what I read in book.

And I'd like to save one of the comments not only at stackoverflow, but also at my web site.

So, what's wrong with this approach?

Liskov Substitution Principal is one problem -- the WriteModel supports mutations (via commands); to inherit from the WriteModel as you do here implies that the ReadModel also supports commands. Which implies that the WriteModel is not the only way to mutate the state of the model. That's very bad. If reverse the hierarchy, then you have a ReadModel supporting queries (good), and then the WriteModel inheriting from it also supporting queries. That's bad, but not to such a degree.  In other words, by doing this, you are losing separation of the two models. When you abandon CQRS like this, you are giving up the benefits the pattern affords. Let's imagine this exercise -- suppose you start with a model representation using Command Query Separation (aka: CQS). A trivial implementation might look like

public class Model {
    private Model.State state;

    // queries go here
    // these never change the model state

    // commands go here
    // these can change the model state
    // they don't usually return data
}

So for an example like a model of a bank account, a naive model might look like:

// CQS
public class Account {
    private Account.State state;

    // commands
    public void deposit(Money m) {...}
    public void withdraw(Money m) {...}

    // queries
    public Money getBalance() {...}

    private class State {...}
}

Superficially, all that CQRS adds here is the refactoring of the commands and queries into two separate implementations (ie: the "write model" and the "read model").

// CQRS
public class Account {
    public class WriteModel {
        private Account.State state;

        // commands
        public void deposit(Money m) {...}
        public void withdraw(Money m) {...}
    }

    public class ReadModel {
        private Account.State state;

        // queries
        public Money getBalance() {...}
    }

    private class State {...}
}

This, by itself, doesn't buy you very much -- two separate interfaces instead of one gives you some assurance that the compiler can enforce that the read only representation of the account can't be used to change it. Greg Young's key insight at this point: because we have separated the two models, we no longer need to use the same representation of the account state in both cases. In the abstract form, it might look more like:

// CQRS
public class Account {
    public class WriteModel {
        private WriteModel.State state;

        // commands
        public void deposit(Money m) {...}
        public void withdraw(Money m) {...}

        private class State {...}
    }

    public class ReadModel {
        private ReadModel.State state;

        // queries
        public Money getBalance() {...}

        private class State {...}
    }
}

This is a really big deal, because WriteModel.State can now be optimized for writes, and ReadModel.State can be optimized for reads. You can have completely different representations, completely different persistence strategies, even different skill levels of programmers working each model (programmers working with the read model may introduce bugs, but they can't possibly corrupt your client's data, because data modifications are restricted to the write model). But all of that goes away if you insist on the two models sharing a representation of state.

No Comments

Add a Comment

Crud With Mongodb Version 2

CRUD with MongoDB version 2

Hello everybody,

today I want to describe CRUD options in MongoDB version 2.

So, let's start with Reading. 

In MongoDB reading can be considered as following options:

  1. Finding all documnets
  2. Filtering
  3. Sorting
  4. Definitions and builders.

Creating documents in MongoDB is simple. You can do it just with Insert ( letter C ). 

And here you have plenty of options:

  1. Replace
  2. Update
  3. Upsert

I'll also mention deleting, or letter D.

And also I want to describe how to use projections as way to limit what you take from MongoDB

So, let's start with synchronous finding of some information in MongoDB. 

Suppose I have following classes declarations:

public abstract class MongoEntityBase
    {
        // ReSharper disable once InconsistentNaming
        public ObjectId _id { getset; }
    }
 
    public class SampleClarification : MongoEntityBase
    {
        public ObjectId SomeId { getset; }
        public int RectificationNumber { getset; }
        public string RectificationReason { getset; }
        public string RectificationText { getset; }
    }

This class will give me option of working with  SampleClarification collection in my MongoDB database.

Also please look at Default construction of database context for MongoDB:

public class SampleDataContext
    {
        public IMongoDatabase Database;
 
        public SampleDataContext()
        {
            var client = new MongoClient("http://localhost:27017/sample");
            Database = client.GetDatabase("sample");
        }
    }

In order to get this collection synchronously, I will need to add interface collection to datacontext. Data context will be transformed to this: 

public class SampleDataContext
    {
        public IMongoDatabase Database;
        public SampleDataContext()
        {
            var client = new MongoClient("http://localhost:27017/sample");
            Database = client.GetDatabase("sample");
        }
        public IMongoCollection<SampleClarification> SampleClarifications => Database.GetCollection<SampleClarification>("sample");
    }

The most important part here is SampleClarifications

And then you can search for all SampleClarifications in the following way:

SampleDataContext sc = new SampleDataContext();
var allDocs = sc.SampleClarifications.Find(new BsonDocument()).ToList();

then   allDocs will be list in memory of all documents.

So, that was syncrhonous call. 

Now I want to demonstrate asyncrhonous call ( that will be as easy as cake ):

SampleDataContext sc = new SampleDataContext();
var allDocs = await sc.SampleClarifications.Find(new BsonDocument()).ToListAsync();

But let's say you want to iterate through returned documents, and do something with them. Then very handy can be function ForEachAsync. And I recommend to use it with cursor. 

The next is going filtering. One of the ways of filtering can be the following:

SampleDataContext sc = new SampleDataContext();
            var allDocs = await sc.SampleClarifications.Find(new BsonDocument()
                    {
                        { "RectificationNumber" , 4}
                }
                ).ToListAsync();

Do you have an impression, that pointing string is not great way to make filtering? If yes, you are not alone. And MongoDB driver has some new features for filtering:

SampleDataContext sc = new SampleDataContext();
           
var allDocs = await sc.SampleClarifications.
             Find(Builders<SampleClarification>.Filter.Gte(a => a.RectificationNumber, 7)).ToListAsync();

One of the ways to read filters creation can be the following: build me the filter on a SampleClarification type  which returns SampleClarificaiton instances where RectificationNumber is  Greater or equal 7.

Other posibilities can be Lte - less equal, Eq - equal to, etc. 

Another useful feature is using Where. For example like this:

SampleDataContext sc = new SampleDataContext();
            
var allDocs = await sc.SampleClarifications.
        Find(Builders<SampleClarification>.Filter.Where(a => a.RectificationNumber == 7)).ToListAsync();

IMHO where is intended for cases if you don't want to remember Lte, Eq, Gte, Ne, etc. But Where has one important feature. You can pass there nullable value.

Another interesting feature of MongoDB is combining filtering features. See the following code:

SampleDataContext sc = new SampleDataContext();
 
var filter = Builders<SampleClarification>.Filter.Empty;
 
if (true /*some condition*/)
{
     filter = filter & Builders<SampleClarification>.Filter.Where(a => a.RectificationText.Contains("aaa"));
}
 
var allDocs = await sc.SampleClarifications.
        Find(filter).ToListAsync();

Pretty interesting, huh??? I was surprised when seeen & instead of &&.

But that's not all. Let me introduce you another shortcut: &=. Like this:

if (true /* another condition */)
{
      filter &= Builders<SampleClarification>.Filter.Gte(a => a.RectificationNumber, 20);
}

Sorting

For sorting you can work again with Builder. It can be achieved like this:

SampleDataContext sc = new SampleDataContext();
 
var filter = Builders<SampleClarification>.Filter.Empty;
var sorting = Builders<SampleClarification>.Sort.Ascending(t => t.RectificationNumber);
var allDocs = await sc.SampleClarifications.Find(filter).Sort(sorting).ToListAsync();

If you feel bored to do a lot of typing in order to Sort something, you can see to SortBy function:

SampleDataContext sc = new SampleDataContext();
var filter = Builders<SampleClarification>.Filter.Empty;
var allDocs = await sc.SampleClarifications.Find(filter).SortBy(s => s.RectificationNumber).ToListAsync();

Or you can use even more complicated schema:

SampleDataContext sc = new SampleDataContext();
var filter = Builders<SampleClarification>.Filter.Empty;
var allDocs = await sc.SampleClarifications.Find(filter).
    SortBy(s => s.RectificationNumber)
    .ThenByDescending(a => a.TenderId)
    .ThenBy(a => a.RectificationReason).ToListAsync();

Inserting or C from CRUD

You can insert either one element, or more. Here is example how to create one:

SampleDataContext sc = new SampleDataContext();
var filter = Builders<SampleClarification>.Filter.Empty;
var clar = new SampleClarification();
clar.RectificationNumber = 10;
clar.RectificationReason = "some reason";
clar.RectificationText = "fasdfdas fdsfas";
await sc.SampleClarifications.InsertOneAsync(clar);

Replacing or almost U from CRUD

First of all what is replacing. Replace is when you find document, delete it, and instead of it put new one, with modified values.

First of all you will need to find element, then update it's value, and then save it. Here is example:

SampleDataContext sc = new SampleDataContext();
//var filter = Builders<SampleClarification>.Filter.Where(r => r.TenderId == ObjectId.Parse("56d55f1d4ee6bc45a0d7b539"));
//var clar = sc.SampleClarifications.Find(filter).FirstOrDefault();
 
//or another way:
var clar =  sc.SampleClarifications.Find(a => a.TenderId == ObjectId.Parse("56d55f1d4ee6bc45a0d7b539")).FirstOrDefault();
 
if (clar != null)
{
    sc.SampleClarifications.ReplaceOne(r => r._id == clar._id, clar);
}

Replace one, will take as paramether search criteria, and will replace passed element.

U from CRUD or Update

Well, for making update you'll need Builder with update policy. See the example of code:

SampleDataContext sc = new SampleDataContext();
 
var text = "fasfds afasfas";
var clar =  sc.SampleClarifications.Find(a => a.TenderId == ObjectId.Parse("56d55f1d4ee6bc45a0d7b539")).FirstOrDefault();
var modificationsUpdate = Builders<SampleClarification>.Update
    .Set(a => a.RectificationReason, text)
    .Set(v => v.RectificationNumber, 35);
 
if (clar != null)
{
    sc.SampleClarifications.UpdateOne(c => c._id == clar._id, modificationsUpdate);
}

Also you can make it async if you wish.

Another U from CRUD or Upsert

Upsert means the following. If upsert option is set to true, then if not matching document exists, then it will be inserted. If document exists, then it will be replaced. 

Code which can be helpful:

SampleDataContext sc = new SampleDataContext();
 
var text = "fasfds afasfas";
var clar =  sc.SampleClarifications.Find(a => a.TenderId == ObjectId.Parse("56d55f1d4ee6bc45a0d7b539")).FirstOrDefault();
UpdateOptions options = new UpdateOptions
{
    IsUpsert = true
};
 
if (clar != null)
{
    sc.SampleClarifications.ReplaceOne(c => c._id == clar._id, clar, options);
}

Finally Delete or D

Finally you can delete any document. It's relatively easy:

SampleDataContext sc = new SampleDataContext();
sc.SampleClarifications.DeleteOne(a => a.RectificationNumber == 10);

Projections

Let's say that you want to return not full list of SampleClarification fields, but subset of them. For this purpose you can use projections. 

Imagine, that you don't want to extract all fields from SampleClarification, and for this purpose you created the following view class:

public class SampleClarificationView : MongoEntityBase
    {
        public ObjectId TenderId { getset; }
        public int RectificationNumber { getset; }
    }

Then you can use projections:

SampleDataContext sc = new SampleDataContext();
var filter = Builders<SampleClarification>.Filter.Empty;
var middle = sc.SampleClarifications.Find(filter).Project(r => new SampleClarificationView()
{
    _id =  r._id,
    TenderId = r.TenderId,
    RectificationNumber = r.RectificationNumber
});
var result = await middle.ToListAsync();

Result will contain not all fiedls.

No Comments

Add a Comment

How To Call Method Of Angularjs Controller Outside Of Angularjs In Javascript

How to call method of AngularJS controller outside of AngularJS in javascript

Hello everybody,

today I want to write few words about AngularJS and js integration.

Recently I had opportunity to cowork with one guy, which is great in knowing javascript, but absolutely hates to learn and apply AngularJS. So, I had task in front of me, to give him sone kind of JS object, which he can use in order to execute some method of AngularJS controller.

So I had some AngularJS controller. 

here is the fragment of it:

'use strict';
 
var controller = 'toolBoxController';
 
angular
    .module('examples')
    .controller(controller, TbController);//register

Then I've added class ( in terms of javascript ):

(function (window, undefined) {
    function toolBoxObject() {

//this function finds controller, which is binded to toolBox div, and executes method of it
        this.unSelect = function () {
            var scope = angular.element('#toolBox').scope();
            scope.$apply(
                    function() {
                        angular.element('#toolBox').controller().unSelect();
                    }
                );
        }

And then in controller I had following method:

var tbObject = new ToolBoxObject();
 
function TbController() {
    var vm = this;
    vm.tb = tbObject;
    vm.ToolBoxButtons = new Array();
    tbObject.controller = this;
//etc.....

And then following method was intended for execution:

vm.unSelect = function () {
 //some kind of implementation
}

I'm ready to bet that you want to ask, why on earth it was needed to use 

var scope = angular.element('#toolBox').scope();

and not just execute mehtod of controller. Well, the answer is simple without scope, the method of controller was executed but results of execution wasn't displayable at screen, and with apply results was possible to show on the screen.

No Comments

Add a Comment

Svg Drawings

SVG drawings

Hello everybody.

Today I want to share with you simple way to draw Mutual Style Fund box with help of javascript and svg in html5 with usage of module pattern of javascript

Recently I had task to make at web site drawings with javascript. After some research I decided to use javascript and svg. Here is screenshot of result:

You can choose scaling size and row and column to display.

Here it goes html code:

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<meta charset="utf-8"/>
	<script src="Scripts/jquery-1.10.2.js"></script>
	<script src="Scripts/MorningStar.js"></script>
</head>
<body>
    <script type="text/javascript">
        function Display() {
            var scale = $('#num').val();
            var x = $('#xRect').val(); // in which column to display filled rectangle
            var y = $('#yRect').val(); // in which row to display filled rectangle
            return MorningStarDisplayer.Draw('svgOut', 640, 480, 1280, 960, scale, x, y);
        }
    </script>
    <div>
        <table>
            <tr>
                <td>Scale:</td>
                <td> <!--scaling size-->
                    <input type="number" id="num" value="0.25" />
                </td>
            </tr>
            <tr>
                <td>
                    Column number starting from 0
                </td>
                <td>
                    <input type="number" id="xRect" value="0" />
                </td>
            </tr>
            <tr>
                <td>
                    Row number starting from 0
                </td>
                <td>
                    <input type="number" id="yRect" value="0" />
                </td>
            </tr>
        </table>
        <input type="button" value="Display Morning star" onclick="return Display();"/>
        <br/>
    </div>
    <div id="svgOut">
    </div>
  </body>
</html>

And here goes javascript code of module:

'use strict';
var MorningStarDisplayer = (function (window, undefined) {
    //Here goes variables, which are needed for internal usage. 
    var start = '<svg width="{width}" height="{height}" viewBox="0,0,{viewBoxW},{viewBoxH}" xmlns="http://www.w3.org/2000/svg">';
    var continuation = '<g><title>Mutual Fund Style Box</title>';
    var templateRect = '<rect id="svg_{i}" height="100" width="100" y="{y}" x="{x}" stroke-width="5" stroke="#000000" fill="none" />';
    var templateRectFiller = 'fill="none"';
    var svgEnd = '</g></svg>';
 
    function drawMoringStarChart(idForSvg, width, height, viewBoxW, viewBoxH, scale, fillX, fillY) {
        scale = 1 / scale;
        var resultHtml = '';
        var newStart = start.replace('{width}', width).
            replace('{height}', height).
            replace('{viewBoxW}', viewBoxW * scale).
            replace('{viewBoxH}', viewBoxH * scale);
        resultHtml = resultHtml + newStart + continuation;
 
        for (var x = 0; x < 3; x++) {
            for (var y = 0; y < 3; y++) {
                var currentX = x * 100 + 10;
                var currentY = y * 100 + 10;
 
                var rect = templateRect.replace("{i}", x * y)
                    .replace("{y}", currentY)
                    .replace("{x}", currentX);
                if (== fillX && y == fillY) {
                    rect = rect.replace(templateRectFiller, '');
                }
                resultHtml = resultHtml + rect;
            }
        }
        resultHtml = resultHtml + svgEnd;
 
        $('#' + idForSvg).html(resultHtml);
    }
     return {
        Draw: drawMoringStarChart
    };
})();

Here you can see, how easier is to use code of module, then to use code of spaghetti code. 

No Comments

Add a Comment

Module And Revealing Module Design Patterns In Javascript

Module and revealing module design patterns in Javascript

Hello everybody,

today I want to propose you interesting comparison of two design patterns in javascript.  As you probably know, javascript doesn't have idea of public and private members. So in order to implement them some tricks are used. That is module and "revealing module".

Take a look at samples of them:

Module

Revealing module

var md = ( function(){

 var privateMember = “private”;

return {

            publicMember : “publicMember”

        };

}

)();

var md = ( function(){

 var privateMember = “private”;

 var publicMember = “publicMember”;

return {

            publicMember : “publicMember”

};

}

)();

The difference is where are members declared. In module all private members are declared inside of the function, and public members inside of return object. While revealing module has all of it's members declared inside of the function, and then returned only public members.

One of the common critisizm of revealing module pattern is challenge in distinguishing from declaration which member is public and which private. One of the common conventions is to prefix private members with prefix _. For example 

var md = ( function(){

 var _privateMember = “private”;

 var publicMember = “publicMember”;

return {

            publicMember : “publicMember”

};

}

)();

No Comments

Add a Comment

Enterprise Service Bus

Enterprise Service Bus

Hello everybody,

I continue to publish damp of my understnading of the Universe.

Now it will be about Enterprise Service Bus as part of building distributed systems.

ESB can be considered as tool for organizing code. 

There are two kinds of ESB:

1. Brokered

2. Decentralized.

Features of brokered:

a. Configuration in one point

b. One configuration team.

c. Mediator makes decision.

Samples of brokers: TIBCO, BizTalk, Web Sphere.

Features of Decentralized:

a. configured indepenently

b. coworking between teams

c. services makes decisions independently

Samples of decentralized: NServiceBus, MassTransit, Rhino Service Bus. 

If to continue comparison between Brokered/Decentralized, then brokered is app, that installed somewhere in the network, while decentralized tends to be NuGet package in your solution ( I assume that developers prefer to have option of controlling ).

No Comments

Add a Comment

Domain Driven Design In One Schema

Domain driven design in one schema

Hello everybody,

today I want to share with you DDD in one schema. 

So, when I first time tried to grasp what is DDD, I heard Bounded context, domain model, Entity objects, Value objects, etc. 

Then I started to read "Domain-Driven Design: Tackling Complexity in the Heart of Software" of Eric Evans and initially was lost in his terms.

After a while I was lost what goes in what. After re-reading I've got the point. 

Enterprise application can have some vocabulary. It can be one, or more. But if it has more then one vocabulary, it can be useful to separate those vocabularis by the definition bounded context.

Each bounded context can have it's own Domain model. 

Each domain model can have entity objects and value objects. And so on. In order not to loose in all of this I've made for myself following schema:

Arrows goes from parent set to child sets:

No Comments

Add a Comment

Normalization In Human Brain And Artificial Neural Network

Normalization in human brain and artificial neural network

Hello everybody,

today I want to write few words about normalization in neural networks and why it is needed or can be needed, but not only from mathematical prospective. Here I mentioned some mathematical reasons why normalization and scaling can be needed.

First of all, you can be surprised, but your brain also does normalization quite often. As way of example give answers at the following questions:

1.     What is color of tree?

2.     What is color of banana?

3.     What is color of logo of Coca-Cola?

4.     In which quantities GDP is measured?

5.     What is color of skin of people in Africa?

I can’t give 100% guarantee, but most probably you answered that tree is green, banana is yellow, Coca-Cola is red, GDB is measured in billions and Africans are black skinned.

 But if to look at some pictures:

you can see that tree has other colors, not just green.

Banana has other colors, not just yellow.

Coca-Cola has other colors, not just red.

Also there are countries which have their GDP measured not in billions but in millions of dolars. I can't explain why our brain behaves like this, but that is interesting feature of human brain, that it makes some kind of normalization. Actually if to speak about any kind of good report to CEO, CTO, VP, your boss, etc., great report is something, that display in form of pictures not some raw data, but normalized data as some chart.

It's also possible to assume, that our body makes some kind of normalization of information which it gives to brain.  It means that it's possible to cut of hearing part of brain ( for example if it is affected by cancer ) , and switch hearing to some neurons in head which responsible for sight ( of course it's very complicated surgery ).

One more example of normalization which brain does is the following: imagine, that 800 of 1000 times you see, some observation. What will you conclude? You will make conclusion, that some observation has probablity 80%. And that statement can also can be considered as normalization which was perfomed by your brain.

Summary

So, as for neural network user it means the following, next time, when you'll have to normalize and scale in your input, you should remember that not only artifical neural network needs normalized data, but your brain also operates with normalized data.

No Comments

Add a Comment

Impedance Mismatch

Impedance mismatch

Hello everybody,

today I want to boast about one new phrase in my vocabulary: 

impedance mismatch.

It means the following: difference between what you have in your C# code ( as example ) and have that is persisted in db.

For example if you have client, which has orders, and each order thas items, but in C# you'll have clinet, which has list of orders and each order will have list of items, than you can really understand what is impedance mismatch.

1 Comment

  • Gale said

    Yes. I have impedance mismatch as well. Too often.

Add a Comment