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 ...
随机推荐
- java POI往word文档中指定位置插入表格
1.Service demo import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.a ...
- 三十三、MySQL 导入数据
MySQL 导入数据 本章节我们为大家介绍几种简单的 MySQL 导出的数据的命令. 1.mysql 命令导入 使用 mysql 命令导入语法格式为: mysql -u用户名 -p密码 < 要导 ...
- 神经网络系列学习笔记(二)——神经网络之DNN学习笔记
一.单层感知机(perceptron) 拥有输入层.输出层和一个隐含层.输入的特征向量通过隐含层变换到达输出层,在输出层得到分类结果: 缺点:无法模拟稍复杂一些的函数(例如简单的异或计算). 解决办法 ...
- JsRender (js模板引擎)
最近学习了一下Jsrender模板渲染工具,非常不错,功能比较强大,官网说他是“简单直观 功能强大 可扩展的 快如闪电”确实如此.总结一下!! jsRender 三个最重要的概念:模板.容器和数据. ...
- float浮动布局(慕课网CSS笔记 + css核心技术详解第四章)
---------------------------------------------------------------------- CSS中的position: CSS三种布局方式: 标准流 ...
- python * args和** kwargs的用法
所属网站分类: python基础 > 函数 作者:慧雅 链接: http://www.pythonheidong.com/blog/article/18/ 来源:python黑洞网 www.py ...
- 2 Model层 -定义模型
1 ORM简介 MVC框架中包括一个重要的部分,就是ORM,它实现了数据模型与数据库的解耦,即数据模型的设计不需要依赖于特定的数据库,通过简单的配置就可以轻松更换数据库 ORM是“对象-关系-映射” ...
- Django基于Pycharm开发之三[命名空间 与过滤器]
关于命名空间的问题,在project项目中,我们可以设置路由类似于: from django.conf.urls import url,includefrom django.contrib impor ...
- Robotium测试架构规划及测试用例组织
转自:http://blog.sina.com.cn/s/blog_68f262210102vrft.html 6.1 测试架构规划 由于测试用例执行的时候是在手机上执行的,所以类似于Web的把测试数 ...
- 翻译MDN里js的一些方法属性
TypeError The TypeError object represents an error when a value is not of the expected type. [TypeEr ...