Thursday, 29 December 2016

Introduction to CQRS Command and Query Responsibility Segregation


CQRS means Command Query Responsibility Segregation. This was introduced by Greg Young and Udi Dahan. They took inspiration from a Command Query Separation which was defined by Bertrand Meyer.

The main idea behind CQS is: “A method should either be a command that performs an action ( change state of an object), or a query that returns data to the caller, but not both. In other words, asking the question should not change the answer. More formally, methods should return a value only if they are referentially transparent and hence possess no side effects.” -- Wikipedia

Command and Query Responsibility Segregation was originally considered just to be an extension of this concept. 

Because of this we can divide a method into two sets:

  •  Commands - change the state of an object or entire system (sometimes called as modifiers or mutators).
  • Queries - return results and do not change the state of an object.



CQRS is simply the creation of two objects where there was previously only one. The separation occurs based upon whether the methods are a command or a query (in Command and Query Separation, a command is any method that mutates state and a query is any method that returns a value).

When most people talk about CQRS they are really speaking about applying the CQRS pattern to the object that represents the service boundary of the application. Consider the following pseudo-code service definition.


CustomerService

void MakeCustomerPreferred(CustomerId id) 
Customer GetCustomer(CustomerId id) 
CustomerSet GetCustomersWithName(Name name) 
CustomerSet GetPreferredCustomers()
void ChangeCustomerLocale(CustomerId id, Locale locale ) 
void CreateCustomer(Customer customer) 
void EditCustomerDetails(CustomerDetails details)

Applying CQRS on the CustomerService would result in two services - 

CustomerWriteService (Command)

void MakeCustomerPreferred(CustomerId id) 
void
ChangeCustomerLocale(CustomerId id, Locale locale ) 
void CreateCustomer(Customer customer) 
void
EditCustomerDetails(CustomerDetails details)

CustomerReadService (Query)

Customer GetCustomer(CustomerId id) 
CustomerSet
GetCustomersWithName(Name name) 
CustomerSet
GetPreferredCustomers()

The real strength of this pattern is that you can separate methods that change state (Commands) from those that don’t (Query). This separation could be very handy in situations when you are dealing with performance and tuning. You can optimize the read side of the system separately from the write side. for example it allows us to host the two services differently eg: we can host the read service on one (or more) server and the write service on another server (or set of servers). 

Another benefit of this pattern is in the case of large applications. You can split developers into smaller teams working on different sides of the system (read or write) without knowledge of the other side.




Friday, 30 September 2016

Difference between WPF Label and TextBlock


What is Label

Represents the text label for a control and provides support for access keys.


What is Textblock:

The TextBlock control provides flexible text support for WPF applications. The element is targeted primarily toward basic UI scenarios that do not require more than one paragraph of text. It supports a number of properties that enable precise control of presentation, such as FontFamily, FontSize,FontWeight, TextEffects, and TextWrapping. Text content can be added using the Text property. When used in XAML, content between the open and closing tag is implicitly added as the text of the element.



I always thought it was odd that WPF has both TextBlock and Label. They both are responsible for displaying a small amount of text. Every piece of documentation about Label I have read justifies its existence by mentioning that it allows for access keys (a.k.a. mnemonics). Access keys allow you to hit Alt + SomeKey to quickly interact with a control in the UI, such as hitting Alt + O to click an “OK” button. My thought has been, “Why not just add support for access keys to TextBlock and get rid of Label?”


Recently I discovered some reasons why it makes sense for Label to exist. The rest of this blog post sheds some light on that obscure topic. Throughout this blog post we will refer to a demo application which looks like this when you first run it:



The “Username:” text is a TextBlock and the “Password:” text is a Label.

TextBlock is not a control It is a FrameworkElement

Even though TextBlock lives in the System.Windows.Controls namespace, it is not a control.  It derives directly from FrameworkElement.  Label, on the other hand, derives from ContentControl.  This means that Label can:
  1. Be given a custom control template (via the Template property).
  2. Display data other than just a string (via the Content property).
  3. Apply a DataTemplate to its content (via the ContentTemplate property).
  4. Do whatever else a ContentControl can do that a FrameworkElement cannot.
Below is a fragment of the class inheritance hierarchy containing Label and TextBlock:



Label text is grayed out when disabled

When a Label’s IsEnabled property returns false its text is “grayed out.”  TextBlock does not have this behavior by default.  Here is what the demo app looks like when the input area is disabled.  Keep in mind that the “Username:” text is a TextBlock and the “Password:” text is a Label:



The reason Label text turns gray when it is disabled is due to the fact that Label’s default control template has a Trigger which explicitly sets the Foreground property when IsEnabled is false.  Here is that Trigger from Label’s default control template:



If we really wanted TextBlocks to appear grayed out when disabled, we could repurpose that XAML seen above into a Style which is applied to TextBlocks (as seen in the demo project available at the end of this post).

Label supports access keys

This is the standard explanation of why Label exists.  You can associate a Label with another control, such as a PasswordBox, and allow the user to type an access key defined by the Label to set focus to the other control.  The access key is represented in the UI by drawing a line under the appropriate character.  If the user presses the Alt key and then the designated “access character” the target control will be given focus.

Here is what the demo application looks like after the user presses the Alt key:

Notice how every piece of text in the UI has an access key indicator, except for the “Username” TextBlock.  The “Password” Label and its target (a PasswordBox) were declared like this:

Label is much heavier than TextBlock

So far we have examined why Label can be considered better than TextBlock, but now its time to discuss the benefits of using a TextBlock instead.  Label has a higher runtime overhead than TextBlock.  Not only does Label inherit from two classes further down the inheritance hierarchy than TextBlock, but its visual tree is much more involved.

snooped the visual tree of the demo app to see what was really going on when you create a Label with an access key defined.  Below is a screenshot of Snoop displaying the visual trees of both the “Username” TextBlock and the “Password” Label (with an access key defined):



The “Username” TextBlock’s visual tree contains no child elements.  The Label, however, is much more involved.  It has a Border, which contains a ContentPresenter, which hosts an AccessText element, which finally uses a TextBlock to display the text.  So it turns out that using a Label is really just an elaborate and customizable way of using a TextBlock.

Download the demo
Demo and more detail about this can be found at below url





Friday, 1 April 2016

Avoid using magic string use Nameof operator instead

Avoid using magic string use Nameof operator instead
There are several occasions when you will need to use “magic string” within your code. Such “magic strings” are normal C# strings that map to program elements within your code. For example, when raising OnPropertyChanged event, you’d use a string for the name of the corresponding property. Unfortunately, these magic strings had no compile time validation and any program element changes (such as renaming property) wouldn’t automatically update the magic string, resulting in an inconsistency that was never caught by the compiler.

Extracting the Property Name with a Nameof Expression

public string FirstName
{
            get { return _firstName; }
            set { _firstName = value; OnPropertyChanged(nameof(FirstName)); }
}


There are several other occasions where you can avoid the writing magic string in you code.