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/]的更多相关文章

  1. 《The Design of a Practical System for Fault-Tolerant Virtual Machines》论文总结

    VM-FT 论文总结 说明:本文为论文 <The Design of a Practical System for Fault-Tolerant Virtual Machines> 的个人 ...

  2. 《The Design of a Practical System for Fault-Tolerant Virtual Machines》论文研读

    VM-FT 论文研读 说明:本文为论文 <The Design of a Practical System for Fault-Tolerant Virtual Machines> 的个人 ...

  3. Stanford机器学习笔记-7. Machine Learning System Design

    7 Machine Learning System Design Content 7 Machine Learning System Design 7.1 Prioritizing What to W ...

  4. 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 ...

  5. Microchip 125 kHz RFID System Design Guide

    Passive RFID Basics - AN680 INTRODUCTION Radio Frequency Identification (RFID) systems use radio fre ...

  6. 【线性结构上的动态规划】UVa 11400 - Lighting System Design

    Problem F Lighting System Design Input: Standard Input Output: Standard Output You are given the tas ...

  7. Machine Learning - XI. Machine Learning System Design机器学习系统的设计(Week 6)

    http://blog.csdn.net/pipisorry/article/details/44119187 机器学习Machine Learning - Andrew NG courses学习笔记 ...

  8. 【系统设计】论文总结之: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 ...

  9. UVA11400-Lighting System Design(动态规划基础)

    Problem UVA11400-Lighting System Design Accept: 654  Submit: 4654Time Limit: 3000 mSec Problem Descr ...

随机推荐

  1. Java 技术栈

    JAVA是一个面向对象的编程语言,由SUN公司的程序员所开发.它不仅吸收了C++的各种优点,而且还撇弃了C++中难以理解的概念,如多继承.指针等:因此JAVA语言具有功能强大且简单易用两个特征, JA ...

  2. javascript oo实现

    很久很久以前,我还是个phper,第一次接触javascript觉得好神奇.跟传统的oo类概念差别很大.记得刚毕业面试,如何在javascript里面实现class一直是很热门的面试题,当前面试百度就 ...

  3. API Star:一个 Python 3 的 API 框架

    为了在 Python 中快速构建 API,我主要依赖于 Flask.最近我遇到了一个名为 "API Star" 的基于 Python 3 的新 API 框架.由于几个原因,我对它很 ...

  4. php同一个用户同时只能登陆一个, 后登陆者踢掉前登陆者(排他登陆)

    通常用户登陆,如果没有特别的限定, 同一个用户可以同时登陆, 今天搞了一个东西限定一个用户不能同时登陆到一个系统上, 后登陆者会把前面登陆的踢出来.(有点像QQ,同个帐号不能在多个地方同时在线, 后面 ...

  5. Air Pollution【空气污染】

    Air Pollution Since the 1940s, southern California has had a reputation for smog. 自20世纪40年代以来,南加利福尼亚 ...

  6. DOS中断及程序调用

    http://www.cnblogs.com/ynwlgh/archive/2011/12/12/2285017.html

  7. EF上下文对象创建之线程内唯一

    在一次请求中,即一个线程内,若是用到EF数据上下文对象,就创建一个,那么会造成数据混乱,每次创建的对象执行相应的数据库操作,此同时,其他的EF对象内获得的数据可能已经是“过期”的了.即这个数据已经变动 ...

  8. Flume-NG源码分析-整体结构及配置载入分析

    在 http://flume.apache.org 上下载flume-1.6.0版本,将源码导入到Idea开发工具后如下图所示: 一.主要模块说明 flume-ng-channels 里面包含了fil ...

  9. 「微信小程序免费辅导教程」25,基本内容组件text的使用及个人帐号允许的服务类目

  10. 《Scrum实战》第4次课【全职的Scrum Master】作业汇总

    1组: 孟帅 http://www.cnblogs.com/mengshuai1982/p/7375008.html 3组: 张亚辉 http://www.jianshu.com/p/df9eee08 ...