Practical system design with MEF & mef[Trans from arup.codeplex.com/]

Source: Internet
Author: User

Practical System Design using MEF MVVM RX MOQ Unit Tests in wpfposted on could, by Arup Banerjeepreludethe project I s a simple temperature Converter WPF application which would allowuser to convert from Celsius to Fahrenheit and vice versa . The objective however isto demonstrate techniques that is important when building large-scale front-endenterprise Softwar E. I'll walk you through initial project inception, System Analysis,requirements gathering and a top level conceptual lo Gical diagram. Thereafter I ' Lldiscuss how the conceptual logical design would guide us with the choice offramework. Subsequently I ' ll dig deep into the world of coding while all the whilekeeping MVVM and SOLID patterns as the guiding Torc H.along the "Learn", "production" Code we use WPF, MEF discoverycomposition and IOC, Rx Concurrency and Data M  Odelling around it and its usefulside effects, Custom Dependency Properties, Control Templates and style Templateand style Triggers. All the above techNiques is to facilitate MVVM (with a word ofcaution, as-to-not-make the converters too intelligent as we cannot unit T Estthose). We ' ll also write a simple log4net Appender to provide us with useful inmemorylog messages. Finally we see practical rx-testing Virtual Time scheduling MOQ Unit testing in play.  System Analysisi looked at various temperature converters and finally settled with the Googletemperature converter for its Simplicity, sleek design and more usability withminimum clicks. The Google temperature Converter looks like below.  Googletempcon our Final systemaruptempconv functional requirements.by playing around I noted the functional requirement as Below. Functionarequirements Non Functional requirementsnonfunctionarequirementsconceptual DesignI 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. Conceptualdesignwe See, the Right text box observes on the sequence of input on the left text box and reacts to the CH Anges. Similarly we see if the user inputs on the right text box, the left text box observes on the sequence of input and reacts to it. What do we see here is a Observer Pattern in play. There is observers, the left sequence Observer and the right sequence Observer. Well from technical point of view one argue, why, and observers and why is simply let the ViewModel has one observer W Hich handles the conversion logic. Why has observer at all and instead simply implement the logic using databinding and WPF behaviours. Well the argument goes one. There is no just right answer to anything. The I look at things are to unbias my mind from technology and look at the system in its pure natural form. The Text Boxes is like the other observers which observes the data thrown by the User. The job of the data Model is provide the data and the observable orchestration. The actual processing of the data is do 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 De Cision. The reason for observers was because it more naturally depicts the system we are handling and SOLID pattern insist Sepa Ration of concern as its guiding 1st principal. Following these principles helps to alleviate a future problems and issues with design while the product matures. Both of these observers react to the changes data subject. We'll further like to handle the reaction action concurrently without blocking the UI Main Thread. Moreover if you decide to handle concurrency in UI, we had a restriction such that anytime you update a Visual, the work IS-to was sent through the Dispatcher to the UI thread. The control itself can only is toUched by it ' s owning thread. If you try the anything with a control from the another thread, you ll get a runtime unsupported operation exception.  Overall concurrency may be a overkill for this and temperature converter, but the objective here are to show techniques For building large-scale front-end enterprise system.  Therefore given we have decided our requirement for concurrency, there is many patterns at our disposal to run a piece of Work in the BACKGROUND:CONCURRENTPATTERNRX, have abstracted all the above mechanisms for concurrency using a single interf Ace 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 is input by the user. Data Model Designas discussed above, the data model primarily observes a sequence of numbers thereby inheriting from IOBSE Rvable<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 was 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.datamodeldesigncodenote that this Data Model is a  Generic base implementation Hence the Iobservable<t> interface is also exposed as Method Getobservable (), which would Then allow the Observable to be exposed through upper stack interfaces Ileftsequenceobservermodel and Irightsequenceobser Vermodel. The upper stack interfaces is composed by MEF, IOC injected and orchestrated in the MVVM play. As would be shown in the unit tests, the getobservable () interface'll allow us to inject testscheduler which facilitates Virtual time scheduling and is absolute necessity for any RX related testing. In the MVVM paradigm and while ViewModel is not being directly Using the controls but ViewModel runs and updates the UI using WPF databinding on the UI Dispatcher Thread Context. However when we'll unit test the ViewModel there would be no dispatcher thread context. Therefore We'll use the bridge pattern to decouple abstraction from implementation. Rx has already abstracted the concurrency via the IScheduler interface as discussed above and we'll leverage that as Bel ow. Rewireschedulerusage1now above is a test Setup and there is a subtle "bug". Hint the above test would work in debug test, but would fail in Test using release code. I leave this in think or else see my actual code. Schedulerusage2note below 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 was I ' ve not Applied double check lock pattern on the Value Setter. That's a potential bug because although OnNext gurantees that it'll not overlap; But this gurantee makes sense within the perspective of RX implementation. When we were implementing our own logic we should ensure, the RX grammer is intact else we can has surprises in the PR Oduction code. We can easily achieve is implementing double check lock pattern over the Setters. Alternately a lock free implementation would be assign the event delegate to a local delegate and then invoke on the LO Cal event delegate. As because delegates is immutable and thread have its own private stack, we is naturally guarded without implementing an Y lock. I had said many words but the implementation was quite simple like below. Threadsafeevent1now You can argue this _value is not guarded.  But that's not a worry-critical section of the the code because we be instead using stack value which is thread safe anyway. I ' m Logging the sequence As a side effect using do extension which does don't change the sequence, and also called prior to Onnext.schedulerusage3ob Servable Sequence Controlleras per the If case, the user inputs the left textbox; The left TextBox becomes subject and the input sequence are 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 is 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. Sequenceschedulerviewmodel designthe Mainpageviewmodel is the ViewModel for the view MainWindow.xaml. This ViewModel was located by the ViewModel Locator and injected as the DataContext of the view. The Models and controller is 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 being able to use our ViewModel in setters because Only dependency properties could is use in setters. Viewmodeldesignviewmodelinject Unit testssome 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 Coveragecode Coverage is a important tool, which gives an idea how we Code is being used. But we should don't get biased with the overall percentage. For example I don't use attached code and hence InitializeComponent can is 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's not a use of this ViewModel. ViewModeLlocator shows coverage 0, but that's not exactly true, because the viewmodellocator was only used once to inject the Mai NView.  The coverage and snapshot starts well after the View appears, by which time the viewmodellocator have already done its job. Hence Code coverage is very useful and we should use the figures judiciously. Coverage Nuget Packagesnuget is a versatile the package management tool and have been used in this project. Nugetdownload Code

  

Practical system design with MEF & mef[Trans from arup.codeplex.com/]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.