practical system design with mef & mef[ trans from arup.codeplex.com/]
Practical System Design using MEF MVVM RX MOQ Unit Tests in WPF Posted on May 21, 2015 by Arup Banerjee
Prelude The project is a simple Temperature Converter WPF Application which will allow
user to convert from Celsius to Fahrenheit and vice versa. The objective however is
to demonstrate techniques that are important when building large-scale front-end
enterprise software. I will walk you through initial project inception, system analysis,
requirements gathering and a top level conceptual logical diagram. Thereafter I’ll
discuss how the conceptual logical design will guide us with the choice of
Framework. Subsequently I’ll dig deep into the world of coding while all the while
keeping MVVM and SOLID patterns as the guiding torch.
Along the way we’ll learn how in production code we use WPF, MEF Discovery
Composition and IOC, Rx Concurrency and Data Modelling around it and its useful
side effects, Custom Dependency Properties, Control Templates and Style Template
and Style Triggers. All the above techniques are to facilitate MVVM (with a word of
caution, as to not to make the converters too intelligent as we cannot unit test
those). We’ll also write a simple Log4Net Appender to provide us with useful inmemory
log messages. Finally we see practical Rx-Testing Virtual Time Scheduling MOQ Unit Testing in play. System Analysis I looked at various temperature converters and finally settled with the google
temperature converter for its simplicity, sleek design and more usability with
minimum clicks. The Google Temperature Converter looks like below. GoogleTempCon Our Final System ArupTempConv Functional Requirements. By playing around I noted the functional requirement as below. FunctionaRequirements Non Functional Requirements NonFunctionaRequirements Conceptual Design I personally prefer top level conceptual design. It allows to more naturally understand the appropriate design patterns and accordingly help us model the system. Once we understand the relevant pattern and the associated design pattern we can design relevant data model, service models and relevant frameworks to be used. Conceptualdesign We see that the right text box observes on the sequence of input on the left text box and reacts to the changes. Similarly we see that when the user inputs on the right text box, the left text box observes on the sequence of input and reacts to it.
What we see here is an Observer Pattern in play. There are two observers, the left sequence Observer and the right sequence Observer. Well from technical point of view one may argue why two observers and why not simply let the ViewModel have one observer which handles the conversion logic. Why have observer at all and instead simply implement the logic using databinding and WPF behaviours. Well the argument goes one. There are no just right answer to anything. The way I look at things is to unbias my mind from technology and look at the system at its pure natural form.
The Text Boxes are like two observers which observes the data thrown by the user. The job of the Data Model is only to hold the data and provide the observable orchestration. The actual processing of the data is done by the controller who decide who gets a point and who loses. The ViewModel walks up and informs the View about the decision taken by the controller and asks the view to display the decision. The reason for two observers is because it more naturally depicts the system we are handling and SOLID pattern insist separation of concern as its guiding 1st principal. Following these principles helps to alleviate future problems and issues with design while the product matures.
Both of these observers react to the changes to the subject data sequence. We will further like to handle the reaction action concurrently without blocking the UI Main Thread. Moreover if you decide to handle concurrency in UI, we have a restriction such that anytime you update a Visual, the work is to be sent through the Dispatcher to the UI thread. The control itself can only be touched by it’s owning thread. If you try to do anything with a control from another thread, you’ll get a runtime unsupported operation exception. Overall concurrency may be an overkill for this simple Temperature converter, but the objective here is to show techniques for building large-scale front-end enterprise system. Therefore given we have decided our requirement for concurrency, there are many patterns at our disposal to run a piece of work in the background:
ConcurrentPatternRx, has abstracted all the above mechanisms for concurrency using a single interface called IScheduler. Given RX facilitates Observable sequence and also abstracts concurrency, it is therefore an ideal framework of choice. The observers naturally involve a sequence of data which are input by the user. Data Model Design As discussed above, the Data Model primarily observes a sequence of numbers thereby inheriting from IObservable<T> where T is the sequence type. The Model does not persist the sequence of result except for the result of the latest calculated sequence value. This result is therefore represented by the property Value. The Data Model is also a Subject for observation and hence it aggregates a _innerObservable Subject<T> of type T, in our case decimal. The logical unit of the result “Value” is represented by logical unit U. DataModelDesignCode Note that this Data Model is a generic base implementation hence the IObservable<T> interface is also exposed as method GetObservable(), which will then allow the Observable to be exposed through upper stack interfaces ILeftSequenceObserverModel and IRightSequenceObserverModel. The upper stack interfaces are composed by MEF , IOC injected and orchestrated in the MVVM play. As will be shown in the unit tests, the GetObservable() interface will allow us to inject TestScheduler which facilitates virtual time scheduling and is absolute necessity for any RX related testing . In the MVVM paradigm, while ViewModel may not be directly using the controls but ViewModel runs and updates the UI using WPF databinding on the UI Dispatcher Thread Context. However when we will unit test the ViewModel there will be no dispatcher thread context. Therefore we will use bridge pattern to decouple abstraction from implementation. Rx has already abstracted the concurrency via the IScheduler interface as discussed above and we will leverage that as below. Rewire SchedulerUsage1Now above is a test Setup, but there is a subtle “bug”. Hint the above Test will work in debug Test but will fail in Test using release code. I leave this for you to think or else see my actual code. SchedulerUsage2 Note below that the data Model also exposes events to loosely notify changes to value and unit. One thing of interest is that I’m not checking if reference equals null for the event delegate. The reference check is not necessary because I’m initializing the event delgates to no-op delegate {}. There is yet one more thing of interest which is I’ve not applied double check lock pattern on the Value Setter. That is a potential bug because although OnNext gurantees that it will not overlap; but that gurantee makes sense within the perspective of RX implementation. When we are implementing our own logic we should ensure that the RX Grammer is intact else we can have surprises in the production code. We can easily achieve that by implementing double check lock pattern over the Setters. Alternately a lock free implementation will be you assign the event delegate to a local delegate and then invoke on the local event delegate. As because delegates are immutable and thread has its own private stack , we are naturally guarded without implementing any lock. I have said many words but the implementation is quite simple like below. ThreadSafeEvent1 Now you can argue that _value is not guarded. But that is not a worry in this critical section of the code because we are instead using stack value which is thread safe anyway. I’m logging the sequence as a side effect using Do extension which does not change the sequence, and also called prior to OnNext. SchedulerUsage3 Observable Sequence Controller As per the use case when the user inputs the left textbox; the left textbox becomes subject and the input sequence is observed by the right textbox and vice versa.
The Observable Sequence Controller does the job of wiring and unwiring the appropriate Observable Sequence data Model. Note specifically in the Toggle Event, the controllers unwires both the observers, because any changes subsequent are due to change in the unit of conversion only rather than any new data sequence. MEF composes and injects the Models into the Sequence controller. SequenceScheduler ViewModel Design The MainPageViewModel is the ViewModel for the view MainWindow.xaml. This ViewModel is located by the ViewModel Locator and injected as the DataContext of the view. The Models and controller are IOC injected into the ViewModel constructor. The KeyBoardFocussed property is implemented as behaviour attached property so we can associate with a bindable command and command parameter. Note if otherwise we had used IsKeyBoardFocussed as Trigger, we would not be able to use our viewModel in setters because only dependency properties could be use in setters. ViewModelDesign ViewModelInject Unit Tests Some crucial Unit Tests techniques and design have been discussed above. These below test covers the functional specification Testing. You can check the details of implementation in the code included. UnitTest Code Coverage Code Coverage is an important tool, which gives an idea how our code is being used. But we should not get biased with the overall percentage. For example I do not use attached code and hence InitializeComponent can be safely removed. Similarly I use only the generic version of the RelayCommand<T> as I’m using commandParameter. However keeping the non Generic within the libray does not harm even though it is not use in this ViewModel. ViewModelLocator shows coverage 0%, but that is not exactly true, because the ViewModelLocator is only used once to inject the MainView . The coverage and snapshot starts well after the View appears, by which time the ViewModelLocator has already done its job. Hence Code coverage is very useful, but we should use the figures judiciously. Coverage Nuget Packages Nuget is a versatile package management tool and has been used in this project. Nuget Download Code
practical system design with mef & mef[ trans from arup.codeplex.com/]的更多相关文章
- 《The Design of a Practical System for Fault-Tolerant Virtual Machines》论文总结
VM-FT 论文总结 说明:本文为论文 <The Design of a Practical System for Fault-Tolerant Virtual Machines> 的个人 ...
- 《The Design of a Practical System for Fault-Tolerant Virtual Machines》论文研读
VM-FT 论文研读 说明:本文为论文 <The Design of a Practical System for Fault-Tolerant Virtual Machines> 的个人 ...
- Stanford机器学习笔记-7. Machine Learning System Design
7 Machine Learning System Design Content 7 Machine Learning System Design 7.1 Prioritizing What to W ...
- Machine Learning - 第6周(Advice for Applying Machine Learning、Machine Learning System Design)
In Week 6, you will be learning about systematically improving your learning algorithm. The videos f ...
- Microchip 125 kHz RFID System Design Guide
Passive RFID Basics - AN680 INTRODUCTION Radio Frequency Identification (RFID) systems use radio fre ...
- 【线性结构上的动态规划】UVa 11400 - Lighting System Design
Problem F Lighting System Design Input: Standard Input Output: Standard Output You are given the tas ...
- Machine Learning - XI. Machine Learning System Design机器学习系统的设计(Week 6)
http://blog.csdn.net/pipisorry/article/details/44119187 机器学习Machine Learning - Andrew NG courses学习笔记 ...
- 【系统设计】论文总结之:Butler W. Lampson. Hints for computer system design
Butler W. Lampson. Hints for computer system design. ACM Operating Systems Rev. 15, 5 (Oct. 1983), p ...
- UVA11400-Lighting System Design(动态规划基础)
Problem UVA11400-Lighting System Design Accept: 654 Submit: 4654Time Limit: 3000 mSec Problem Descr ...
随机推荐
- 绘制圆形 和 椭圆形:边圆形 imageellipse() 、 填充圆形imagefilledellipse()
<?php //1. 绘制图像资源(创建一个画布) $image = imagecreatetruecolor(500, 300); //2. 先分配一个绿色 $green = imagecol ...
- mysql之面试问题总结
问题1.char 与varchar的区别? varchar是变长而char的长度是固定的.如果你的内容是固定的大小,char性能更好. char[4] 与varchar[4] 存储字母a a占一个 ...
- Careercup - Microsoft面试题 - 23123665
2014-05-12 07:44 题目链接 原题: Given an array having unique integers, each lying within the range <x&l ...
- 【Container With Most Water】cpp
题目: Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, a ...
- STL学习笔记6 -- 栈stack 、队列queue 和优先级priority_queue 三者比较
栈stack .队列queue 和优先级priority_queue 三者比较 默认下stack 和queue 基于deque 容器实现,priority_queue 则基于vector 容器实现 ...
- PostgreSQL drop database 显示会话没有关闭 [已解决]
错误重现 有时候需要删除某个数据库时,会报如下错误,显示有一个连接正在使用数据库,无法删除 ERROR: database "pilot" is being accessed by ...
- windows批处理 打开exe后关闭cmd
start "" "程序路径.exe" 这样调用就OK啦.如: start "" "D:\123.exe" 如果下 ...
- LeetCode——Problem2:Add Two Numbers
这又过了一周了,总感觉刷这个好花时间呀.每次都一两个小时.让我不好安排时间.应该是我太菜了.对,没错,就是这样 1.题目 You are given two non-empty linked list ...
- MySQL 添加审计功能
MySQL社区版没有自带的设计功能或插件.调研发现MariaDB的audit plugin 同样适用于MySQL,支持更细粒度的审计,比如只审计DDL操作,满足我们的需求.因为最近测试环境的某表结构经 ...
- 【转】Unity3D 入门小技巧——鼠标拾取并移动物体
http://blog.csdn.net/sysujackjiao/article/details/69396274 一.鼠标拾取物体的原理 在Unity3D当中,想要在观察面(Aspect)中拾取物 ...