.Net Code Monkey RSS 2.0
 Monday, September 21, 2015
A type-safe framework for calling stored procedures in .Net
Monday, September 21, 2015 6:16:50 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
Asp.Net | C# | Database | SQL | SQL Server | SQL Server 2005 Express | SQL Server 2008 Express | Stored Procedures | Type Safe
 Friday, June 05, 2015

Command and Query Responsibility Segregation (CQRS) - A simple Example

Over the coming weeks I intend to create a small example web application using the Command and Query Responsibility Segregation pattern. I will then publish this example to my Github and use it as an example framework for a future project I have at work. I hope to rattle out any pitfalls in this example so the development on the work project flows a bit smoother. There seems to be many examples (good and bad, complex and simple) on the web, but I think to get the concept firmly wedged into my brain I need to actually code one.

CQRS provides a mechanism which allows segration of responsibilities for querying of the data from that of updating the data. I'm not going to go into any more detail of what CQRS is in this article as there are plenty of articles on the internet much more eloquently written than anything I could produce. This article is not trying to show the correct way of doing CQRS either. It is more of a published walk-through of my learning!


I am going to use five primary layers Presentation Layer, Application Services Layer, Domain Layer, Data Access Layer, and Database. These will then be cross divided into two stacks, the Command Stack and the Query Stack. The Domain Layer in the Command Stack may be sub divided into further tiers. I'm going to build the application as a C# ASP.Net MVC application. The database layer will be a SQL Server database. Reading of the application data will occur through the Query Stack and creates, updates and deletes of the application data will occur through the Command Stack.

The ASP.Net MVC Application will have a reference to the ApplicationServices.dll. The
ApplicationService.dll will have a reference to the DomainModel.dll and will communicate via interfaces defined in the DominInterfaces.dll. The DomainModel.dll will reference the CommandDataAccess.dll. The ApplicationService.dll will also have a direct reference to the QueryDataAccess.dll again communicating via a set of defined interfaces QueryDataAccessInterfaces.dll. Both the CommandDataAccess.dll and the QueryDataAccess.dll will communicate with the database. There may also be some shared dlls providing common shared code. The CommandDataAccess.dll will implement a simple repository pattern.

When the MVC application makes a request to the Application Services for data to display, the request will be routed down the query stack. Regardless of whether the request be for a list of objects or an object in detail, each request will be fulfilled by a Data Transfer Objects (DTOs) or a list of DTOs. The DTO will completely represent all of the data required and wil be populated from database stored procedures. The stored procedures may return data from multiple database tables flattened into a single record This is the only logic that is applied in the query stack; no domain logic is applied elsewhere. The DTOs will be visible from all levels of the Query stack and will be used in the MVC Controller to map data to the View Model.

When the MVC application needs to update data the request to update will be routed via the command stack and the application services will use the domain model to implement any domain logic required to be applied to any of the commands.

Git Hub Code



CQRS for the Common Application

Friday, June 05, 2015 5:30:52 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.Net | C# | CQRS | domain | Layers | MVC | ommand and Query Responsibility Segregation | Stacks
 Friday, February 06, 2015

Game State Manager for Unity3D - Part 6 - Adding An Event Manager

Previous Part - Part 5

One of my colleagues, John Collinson, made me aware that it is common to have a centralised implementation for raising events in game development, so following his pattern I will now extend the UnityStateManager to encompass an EventManager as well. So the first thing we will do is to create a new empty "GameEventManager" class.
/// <summary>
/// Handles raising of game events
/// </summary>
internal class GameEventManager
This class will be accessed via the GameManager in the same way that the GameSceneManager is. We will add a property called "EventManager" of type "GameEventManager" the "GameManager" class. We will extend the Game Manager's constructor to initialise the GameEventManager. We will add a method which will create a new instance of the
/// <summary>
/// Gets (or privately sets) the game event manager.
/// </summary>
/// <value>
/// The event manager.
/// </value>
internal GameEventManager EventManager { get; private set; } 
/// <summary>
/// Initializes a new instance of the <see cref="GameManager"/> class.
/// </summary>
public GameManager()
    // Create a new EventManager and give it to the instance to use
    EventManager = CreateEventManager();

    // Create a new SceneManager and give it to the instance to use
    SceneManager = CreateSceneManager();

/// <summary>
/// Creates the event  manager.
/// </summary>
/// <returns></returns>
private GameEventManager CreateEventManager()
    // Create a new instance of the game's event manager
    GameEventManager gameEventManager = new GameEventManager();

    // return the scene manager
    return gameEventManager;
The members of the game's event manager will now be able to be called from the static State object in a consistent way like so...
We can now look at moving the events that are raised in the GameSceneManager into the GameEventManager. First we will look at the GameSceneChanged event. We pick up the event declaration and the "RaiseGameSceneChangedEvent" method from the GameSceneManger, move it to the GameEventManagerand  change the modifier from "private" to "public".
#region GameSceneManger.GameSceneChanged

/// <summary>
/// Occurs when the game scene has changed.
/// </summary>
public event GameSceneChangedHandler GameSceneChanged;

/// <summary>
/// Raises the game scene changed event.
/// </summary>
/// <param name="originalScene">Indicates the original scene.</param>
/// <param name="newGameScene">Indicates the new game scene.</param>
public void RaiseGameSceneChangedEvent(GameSceneIdentifier originalSceneIdentifier,
    GameSceneIdentifier newGameSceneIdentifier)
    // See if we have any delgates attached that need to
    // be called after we change game scene
    if (GameSceneChanged != null)
        // Create new game scene changed event data
        GameSceneChangedEventArgs gameSceneChangedEventArgs =
            new GameSceneChangedEventArgs(newGameSceneIdentifier, originalSceneIdentifier);

        // Raise the event
        GameSceneChanged(this, gameSceneChangedEventArgs);


We now have to pop into the GameSceneManager's "OnGameSceneChange" to update the call to "RaiseGameSceneChangedEvent" as this is now in the new GameEventmanager class.
// Raise the game scene changed event to notify any listeners that
// the game state has changed.
State.GameManager.EventManager.RaiseGameSceneChangedEvent(originalSceneIdentifier, newGameSceneIdentifier);
Then a quick change to the wiring up of the event handlers in GameManager.CreateSceneManager. Leave the GameSceneChanging event handler wiring as it is for the moment. We will change that when we move that event.

// Wire up the event handlers
EventManager.GameSceneChanged += gameSceneManager_GameSceneChanged;
gameSceneManager.GameSceneChanging += gameSceneManager_GameSceneChanging;
Lastly don't forget to import any namespaces to correct any remaining compile errors. We must now follow the same process for the "GameSceneChanging" event.

Once this is complete we can run the Unity project and everything should still work.

Note: Some people prefer to use the term "TriggerBlahBlahBlah" rather than "RaiseBlahBlahBlah". I come from a Visual basic background originally so tend to use "Raise..."     

All Parts

Part 1
Part 2
Part 3
Part 4
Part 5

Full Code

The full code for this part can be found at Part 6 of the UnityStateManager repository.

Friday, February 06, 2015 7:16:24 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
C# | Game Scene Manager | Game State Manager | Unity3D | Game Event Manager
 Wednesday, February 04, 2015

Game State Engine for Unity3D - Part 5 - Plumbing it all in to Unity3D

Following on from Part 4  (http://www.duanewingett.info/2015/01/29/GameStateEngineForUnity3DPart4SubscribingToEvents.aspx) where we hooked into the events we will now plumb everything we have coded into the unity project its self.

So if we go into Unity and Save the current scene as "Initialize" (save in the scenes folder), the create and save two more scenes "Intro" and "MainMenu". Go to Unity's build Settings Menu and make sure that the only included scenes are...
...and are in that order. We will create a script called "Initialize" and attach it to the  "Initialize" scene. As we want the initialize scene to transition straight to the "Intro" scene, in this "Start" method of whose script we will call the SceneManager's SetGameScene and pass the Intro scene identifier.
public class Initialize : MonoBehaviour {
    // Use this for initialization
    void Start () {
If you follow the call stack through (Using "Go To Definition" in Visual Studio / "Go To Declaration" in MonoDevelope) until we reach "GameSceneManager.OnGameSceneChange" you will see that the SceneManager raises an event when the scene is allowed to change. Our GameManager already subscribed to that event so lets find that.
/// <summary>
/// Handles the GameSceneChanged event of the gameSceneManager control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="GameSceneChangedEventArgs"/> instance containing the event data.</param>
/// <exception cref="System.NotImplementedException"></exception>
void gameSceneManager_GameSceneChanged(object sender, GameSceneChangedEventArgs e)
    throw new System.NotImplementedException();
Lets remove the code that throws the NotImplementedException and replace this with a call to a method that will load the level for the value of the GameSceneIdentifier which was passed to this event handler in the event data.
/// <summary>
/// Handles the GameSceneChanged event of the gameSceneManager control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="GameSceneChangedEventArgs"/> instance containing the event data.</param>
/// <exception cref="System.NotImplementedException"></exception>
void gameSceneManager_GameSceneChanged(object sender, GameSceneChangedEventArgs e)
    // Load the level using the GameSceneIdentifier from the event data


The LoadLevelByGameSceneIdentifier method will contain the code to change the game Level or Scene in Unity. We will do that by calling the UnityEngine's "Application.LoadLevel(...)". This method has two overloads; one takes a parameter of type string which identifies the level name, and the other of type integer which identifies the index of the level to be loaded. This index corresponds to the order of the included scenes set in Unity's "Build Settings" dialogue. We will use the overload which takes an integer, so to do this we will first create a levelIndex variable of integer type and populate that from the GameSceneIdentifier that has been passed to this method.
/// <summary>
/// Loads the level by game scene identifier.
/// </summary>
/// <param name="gameSceneIdentifier">The game scene identifier.</param>
private static void LoadLevelByGameSceneIdentifier(GameSceneIdentifier gameSceneIdentifier)
    // Get the level index from the GameSceneIdentifier. This must match 
    // the same index as defined in Unity's Build Settings dialogue. 
    // We will also need to explicitly cast the identifier as an int.
    int levelIndex = (int)gameSceneIdentifier;

    // Call through to the Unity Engine's method to load a scene / level 
    // using our levelIndex. 
Add a game object into the Intro scene (maybe some text) so you can easily identify the scene has transitioned from the "Initialize" scene and has loaded correctly.

Running Unity up now the game should start in the "Initialize" scene and immediately transition to the "Intro" scene. You may chose to use the Intro scene to show introduction credits while loading assets, etc.

Lets add another script to transition from the "Intro" to "MainMenu" and attach it to the Intro scene (or an object in the scene like the camera)
public class Intro : MonoBehaviour
    // Use this for initialization
    void Start()

        //3 seconds later
        // Change to main menu

    IEnumerator DelayMethod(float delay)
        yield return new WaitForSeconds(delay);
Running this up in Unity now should make the game transition immediately to the "Intro" scene and then pause before transitioning to the "MainMenu" scene.


So why all this code just to transition the scene? could we not just have put "Application.LoadLevel(1);" in the "Start" method of the "Initialize" script? Well yes we could, but we'd have to start adding any logic around whether changing the scene is valid in the scene scripts. There may be logic like "is the game saved" that needs to be checked before a scene can change, say for instance when changing from "Playing Game" to "Load a saved game" It is not really the responsibility of the scene to know or care about this logic or any rules about what scene changes are valid.

So we encapsulate all this logic in the GameManager and SceneManager objects and access this through the static State class giving a single point of access. The SceneManager also allows for subscribers to may want to "block" a scene change to set the cancel flag. The SceneManager also provides a call back for the calling code to run if a transition fails.

It's also good coding practice to separate concerns into separate classes to make code re-use and maintenance easier and to help identify bugs when they occur. So these are the reasons why I have gone down this route. I hope some of these articles have helped you. Please feel free to leave any comments or questions, below.

All Parts

Part 1
Part 2
Part 3
Part 4

Full Code

The full code for this part can be found at the UnityStateManager repository.

Wednesday, February 04, 2015 7:36:34 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
C# | Game Scene Manager | Game State Manager | Unity3D
<October 2015>
Creator of ruby on Rails
 Harry Pierson
Passion * Technology * Ruthless Competence
 Joshua Flanagan
A .NET Software Developer
 Martin Ffowler
Author, speaker, and loud-mouth on the design of enterprise software
 Michael Schwarz's Blog
Developing applications on the Microsoft platform since Windows 3.1!
 Scot GU
Scott Guthrie lives in Seattle and builds a few products for Microsoft
 Scott Hanselman
Programming Life and the Zen of Computers
About the author/Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2015
Duane Wingett
Sign In
Total Posts: 68
This Year: 15
This Month: 0
This Week: 0
Comments: 52
Pick a theme:
All Content © 2015, Duane Wingett
DasBlog theme 'Business' created by Christoph De Baene (delarou)