Rajnish Noonia

Tag: MVVM

  • Building a TypeScript-First Frontend SDK: An Architectural Journey

    Over the past few years I have spent much of my time on one recurring problem: how do you let many teams build many data-intensive web applications without each of them reinventing the same foundations? This post walks through the architectural journey of designing a TypeScript-first frontend SDK to answer that question. It focuses on the patterns and trade-offs rather than any particular implementation, because the ideas travel well beyond the project that prompted them.

    Application layer Individual applications built on the platform Data grid apps Dashboards Workflow tools Admin tools Others… Framework layer Native React and Angular — thin bindings over the core Angular bindings Components · Directives · DI bridge React bindings Components · Hooks · DI bridge Core Framework-agnostic TypeScript — no UI framework dependency MVVMViewModel · State IoC / DIContainer · Discovery Data gridConfig · Streaming FormsRules · Validation ShellConfig-driven LayoutPanels · Persist ThemingTokens · Dark mode MessagingEvents · Notifications VisualisationCharts · Maps StreamingObservables ObservabilityLogging · Tracing · APM SecurityAuth · Permissions AI-ready contextContext files · Agent rules Scaffolding CLI + delivery pipeline CI/CD · Containers · AWS · dev / test / prod environments
    A layered SDK: framework-agnostic core, thin React/Angular bindings, and applications on top

    The Starting Point: Why a Component Library Is Not Enough

    The usual answer to “we need consistency across teams” is a component library: styled buttons, inputs and grids published as a package. In my experience that solves perhaps a fifth of the real problem. It says nothing about where state lives, how view logic is tested without rendering, how the same feature behaves identically in two UI frameworks, how dependent form fields validate each other, or how any of it stays coherent across years of changing teams.

    So the goal shifted from “shared components” to “shared architecture”: a TypeScript-first, framework-agnostic SDK in which React and Angular are equal, native rendering targets. The choice of view framework becomes a team preference, not an architectural fork.

    Principle 1: MVVM Keeps the View Thin

    The most important decision was to adopt Model–View–ViewModel as the backbone. The view is a template that binds to properties and commands. The ViewModel is a plain TypeScript class that owns state and behaviour. The model is data and services. Nothing else is allowed to blur those lines.

    Three benefits follow. Testability: a ViewModel has no JSX and no decorators, so business logic is tested as ordinary unit tests instead of by mounting components and poking the DOM. Reuse across frameworks: the same ViewModel drives a React view and an Angular view, so behaviour is written once. Clarity: engineers always know where logic belongs, which removes a whole category of code-review debate.

    Principle 2: Dependency Injection Owned by the Core

    MVVM only works well when ViewModels can ask for what they need without knowing where it comes from. Neither framework’s native mechanism fits: Angular’s injector only exists in Angular, and React context is not really DI. The answer was an IoC container that lives in the core, independent of any UI framework, with thin bridges into each one – a hook-based resolver for React and an injector bridge for Angular.

    Services are registered against interfaces, and can be discovered by capability rather than concrete type. This is where SOLID stops being a slide and becomes the path of least resistance: new behaviour arrives as a new registration, not an edit to existing classes, and every dependency can be swapped for a test double.

    Principle 3: Layers With Enforced Boundaries

    The SDK is organised as a monorepo with three layers:

    • Core: pure TypeScript – MVVM primitives, the container, state, messaging, streaming, configuration, theming tokens and platform services. No UI framework dependency.
    • Framework bindings: thin React and Angular packages that render the core’s concepts natively and bridge the container into each framework.
    • Applications: products built on a shared, configuration-driven shell, deployable to the browser or to desktop containers.

    Build-time boundary rules stop applications from reaching into the core directly and reject circular dependencies. Architecture that is only documented erodes; architecture that fails the build stays intact.

    Principle 4: Solve Cross-Cutting Concerns Once

    Most of the value of a platform is in the unglamorous capabilities that every application needs and no team wants to build. Rather than leave them to each project, the SDK provides them as shared services:

    • Configuration-driven shell and layout: navigation, panels and workspaces declared in configuration, with dockable panels whose arrangement is persisted per user.
    • State persistence: any screen can opt in to having column widths, filters, sort order and layout restored on reload.
    • Data grid abstraction: grids configured declaratively, with streaming updates delivered through observables, so teams write configuration and a ViewModel rather than grid plumbing.
    • Forms with a rule engine: field dependencies, visibility and validation expressed as rules; client and server validation surface through one pipeline.
    • Design tokens: semantic colours, spacing and typography exposed as typed constants and CSS variables, with dark mode as a first-class theme.
    • Observability and security: structured logging, tracing and application performance monitoring wired in by default, alongside authentication and permission handling.

    Principle 5: Start Every Project From Working, Not Blank

    A scaffolding CLI turns the SDK into a starting point rather than a set of instructions. A few commands produce an application that already has the shell, theming, authentication, observability, CI/CD pipelines, container configuration and cloud deployment templates for AWS across dev, test and production environments. The decisions that usually consume a project’s first sprint are already made, and every project starts in the same shape – which makes moving between them much easier for engineers.

    Principle 6: Design for AI-Assisted Development

    A newer lesson: an SDK now has two audiences, human developers and AI coding agents. Each package carries a concise context file describing its patterns, naming conventions and rules, and a routing structure points an agent at only the context relevant to its task. Generated projects inherit these files automatically.

    Treating that context as a maintained deliverable – updated alongside code and checked in CI – keeps agents inside the architecture instead of inventing their own. The result is AI assistance that accelerates teams without quietly eroding standards.

    Principle 7: Governance That Scales

    • Enforced module boundaries at build time
    • Semantic versioning with deprecation windows, so nothing disappears without warning
    • Living documentation: component catalogues and visual regression tests in the pipeline
    • Context files as a contract for both humans and agents

    What I Took Away

    The measurable outcome was that applications which once took months could be delivered in weeks, with a consistent look, feel and behaviour. But the more lasting lessons were architectural:

    • Separate behaviour from rendering early; it is very hard to retrofit.
    • Own your dependency injection in the core if you want framework independence.
    • Encode rules in the build, not in wiki pages.
    • Invest in the boring cross-cutting services – that is where teams lose the most time.
    • Treat AI context as part of the product, not an afterthought.

    A good platform is measured by how rarely the teams building on it need to think about it.

  • ViewModel First – ViewCaching

    With View model first approach, view are usually created via DataTemplate, and each time a view model is injected in the content control, the corresponding view is recreated.

    If you have complex view where it take bit time to create view, you may see the performance hits. To avoid the performance hit you may want to cache the view and use the cached view when available. This can be done via creating CacheContentControl and you choice of view factory.

    The basic idea is to wrap the view inside CacheContentControl and delegate the view creation logic to your view factory. The attached sample uses weakreference view factory,say if GC has not collected the view, you may use the cached view instead of creating view each time. This will work with controls like tab control docking controls etc.

    The CacheContentControl  code

    public class CacheContentControl : ContentControl
        {
            public CacheContentControl()
            {
                Unloaded += ViewCache_Unloaded;
                ViewFactory = WeakReferenceViewFactory.Instance;
            }
    
            void ViewCache_Unloaded(object sender, RoutedEventArgs e)
            {
                Content = null;
            }
    
            private Type _contentType;
            public Type ContentType
            {
                get { return _contentType; }
                set
                {
                    _contentType = value;
                   //  use you favorite factory
                    Content = ViewFactory.GetView(value);
                }
            }
    
            public IViewFactory ViewFactory { get; private set; }
        }
    

    In the DataTemplate, use the ViewCache, pass the type of the real view you want to use:

    <DataTemplate DataType=”{x:Type moduleB:Panel3Vm}”>

    <Border Background=”Green”>

    <local:CacheContentControl ContentType=”{x:Type moduleB:Pane3 }” Margin=”5″/>

    </Border>

    </DataTemplate>

    The example uses standard data template (red option) to demonstrate each time you navigate to panes the corresponding views are recreated with new hash code.

    If you select CacheContentControl (green option) and navigate the view is only created once. If you click on button to collected the GC then view are created on navigation if they are claimed by GC.

    Why ViewModel first ?

    I prefer to use view model first approach. For many reasons:

    • Vms are your application containing most of logic apart from glue code in form of behaviors or triggers.
    • If you creates views then you are responsible for its life and cleanup code. You have to deal with threading and other issues which are difficult to test. On the other hand of you create vms and leave the view creation logic with WPF via data template.. you don’t have to worry about threading issue. And there will be better separation of concerns.
    • With vm first approach zero code behind.
    • With a project level isolation for view and vms you can restrict developers using view specific things like dispatcher in the view model leaving more cleaner and testable code base. I.e view project sprojec to vm. And vm project should not refer to any presentation lib.
    • If there is clear boundary between view and vm. Both can evolve and will be less fragile.
    • Allows more complete testing of logic to open new Views and ViewModels
    • Tends to be DRYer (don’t repeat yourself ) as applications get larger
    • View and ViewModel are more independent and can be worked on separately more easily.

    For more details see attached source code (download and rename docx to zip)

    Viewcache Source Code

  • WPF Introduction

    The Windows Presentation Foundation (or WPF) is a graphical subsystem for rendering user interfaces in Windows-based applications. WPF, was initially released as part of .NET Framework 3.0. Designed to remove dependencies on the aging GDI subsystem, WPF is built on DirectX, which provides hardware acceleration and enables modern UI features like transparency, gradients and transforms. WPF provides a consistent programming model for building applications and provides a clear separation between the user interface and the business logic.

    WPF also offers a new markup language, known as XAML which is an alternative means for defining UI elements and relationships with other UI elements. A WPF application can be deployed on the desktop or hosted in a web browser. It also enables rich control, design, and development of the visual aspects of Windows programs. It aims to unify a number of application services: user interface, 2D and 3D drawing, fixed and adaptive documents, advanced typography, vector graphics, raster graphics, animation, data binding, audio and video.

    Microsoft Silverlight is a web-based subset of WPF that enables Flash-like web and mobile applications with the same programming model as .NET applications. 3D features are not supported, but XPS and vector-based drawing are included.

    It is compatible with multiple web browser products used on Microsoft Windows, Linux (using Novell Moonlight), Mac OS X operating systems & Mobile devices.

    WPF is designed to allow you to create dynamic, data driven presentation systems. Every part of the system is designed to create objects through property sets that drive behavior. Data binding is a fundamental part of the system, and is integrated at every layer.

    Traditional applications create a display and then bind to some data. In WPF, everything about the control, every aspect of the display, is generated by some type of data binding. The text found inside a button is displayed by creating a composed control inside of the button and binding its display to the button’s content property.

    Display technology evolution on windows …

    • User32 : Standard controls like buttons, textbox etc. This provides the windows look and feel for buttons and textboxes and other UI elements. User32 lacked drawing capabilities. Window forms are using User32 to render several controls including .net 2.0,vb, vc++ etc.
    • GDI (Graphics device interface) : Abstract graphics of drawing from hardware’s like printers ,monitors etc. Microsoft introduced GDI to provide drawing capabilities. GDI not only provided drawing capabilities but also provided a high level of abstraction on the hardware display. In other words it encapsulates all complexities of hardware in the GDI API. Several GDI API are available in windows platform to perform custom drawing. Hooks like subclassing cab be used to override default drawing of win32 controls on windows Or developers can create custom controls and use GDI API’s to render on screen.
    • GDI+ : JPG, PNG Image support, gradient shading, Anti Alising. GDI+ was introduced which basically extends GDI and provides extra functionalities like jpg and PNG support, gradient shading and anti-aliasing. The biggest issue with GDI API was it did not use hardware acceleration and did not have animation and 3D support. Object oriented approach to flat GDI+ API’s are available in .net which internally based on GDI+.
    • DirectX : Targeted for game programmers, Hardware  Acceleration (is a process in which we use hardware to perform some functions rather than performing those functions using the software which is running in the CPU.),support for animation,3D support, full colour graphics, Capture and play streaming media. One of the biggest issues with GDI and its extension GDI+ was hardware acceleration and animation support. This came as a biggest disadvantage for game developers. To answer and server game developers Microsoft developed DirectX. DirectX exploited hardware acceleration, had support for 3D, full color graphics , media streaming facility and lot more.
    • WPF : Based on direct (internally), support for primitive objects like text, shapes, controls etc, declarative UI using XAML, support for audio , video formats, define styles and templates for UI elements.  DirectX had this excellent feature of using hardware acceleration. Microsoft wanted to develop UI elements like textboxes,button,grids etc using the DirectX technology by which they can exploit the hardware acceleration feature. As WPF stands on the top of directX you can not only build simple UI elements but also go one step further and develop special UI elements like Grid, FlowDocument, and Ellipse. Oh yes you can go one more step further and build animations.WPF is not meant for game development. DirectX still will lead in that scenario. In case you are looking for light animation ( not game programming ) WPF will be a choice. You can also express WPF using XML which is also called as XAML.In other words WPF is a wrapper which is built over DirectX.

     The figure shows the overall architecture of WPF. It has three major sections presentation core, presentation framework and milcore.

     User32 :  It decides which goes where on the screen. User32 is used to determine what program gets what real estate. As a result, it’s still involved in WPF, but it plays no part in rendering common controls.

    • DirectX : WPF uses directX internally. DirectX talks with drivers and renders the content.
    • Milcore :  Mil stands for media integration library. This section is a unmanaged code because it acts like a bridge between WPF managed and DirectX / User32 unmanaged API. The composition engine in milcore is extremely performance sensitive, and required giving up many advantages of the CLR to gain performance. Milcore.dll is the core of the WPF rendering system and the foundation of the Media Integration Layer (MIL). Its composition engine translates visual elements into the triangle and textures that Direct3D expects. Though milcore.dll is considered a part of WPF, it’s also an essential system component for Windows Vista. The Desktop Window Manager (DWM) in Windows Vista uses milcore.dll to render the desktop.
    • Presentation core :– This is a low level API exposed by WPF providing features for 2D , 3D , geometry etc.,  includes base types, such as UIElement and Visual, from which all shapes and controls derive.
    • Presentation framework :  This section has high level features like application controls , layouts . Content etc which helps you to build up your application. The vast majority of Windows Presentation Foundation developers will work exclusively with this layer.
    • *Red colour box indicate WPF layer.

     

    Silverlight : WPF on web – platform independence

    The Silverlight runtime plug-in is essentially a ‘micro’ version of the .NET CLR. This runtime is hosted�
    within the client side browser. This runtime will host your Silverlight assemblies, as well as the Silverlight base class libraries. This runtime will JIT CIL code, handle threads, exceptions and garbage collection. This is a good thing, as your current .NET programming skills apply directly to Silverlight development.

    In addition to the ‘micro-CLR’, Silverlight supports a subset of the .NET base class libraries. When a�
    requesting browser loads a Silverlight page, any required assemblies are downloaded to the user’s machine, if they are currently not installed. Like any other .NET program, you can build your own code custom libraries for use within your Silverlight programs.

    A Silverlight application is deployed from a web server as an ‘XAP’ (zip file) package. The XAP file contains the compiled Silverlight assembly, any embedded resources, and any referenced assemblies. The Silverlight runtime downloads the XAP package and executes its contents in web browser.

    Once loaded by the plug-in, the SL application is able to make remote calls (to the web server or any arbitrary endpoint) using WCF technologies. The entire web page does *not* need to be refreshed when the SL web plug in changes state. This can greatly enhance the end user experience.

    Silverlight architecture is altogether different that WPF, however it tries to implement the features available in WPF. From developer prospective there is no major difference in WPF or Silverlight even though Silverlight CLR is not same as WPF CLR.

  • Composite Application Guidance with Prism 2.0

    Composite Application Guidance, affectionately known as Prism, version 2 was released in oct 2009.  Prism provides guidance and code that can help you build modular applications that can adapt to constant changing requirements. Prism guidance is a set of tools, samples, references and written guidance to help you more easily build modular applications.  Generally the “modular” application will feature several screens, flexible user interaction and role-based behavior.  Composite applications using these patterns are meant to be loosely coupled and contain independently evolving pieces that can work together. They are “built to last” and “built for change.” This means that the application’s expected lifetime is measured in years and that it will change in response to new, unforeseen requirements. This application may start small and over time evolve into a composite client—composite applications use loosely coupled, independently evolvable pieces that work together in the overall application. Applications that do not demand these features and characteristics may not benefit from the Composite Application Guidance.

     What’s new Prism 2.0?

    • Composite Support for Silverlight: Provides guidance on modularity, UI composition, commanding, and event aggregator in Silverlight. The Reference Implementation demonstrates how to use the Prism library with Silverlight.
    • Multi-targeting: Ability to share code between Silverlight and WPF. Provide guidance in the form of patterns, documentation, and tooling on how to share code between Silverlight and WPF. The tooling has its own msi that you can download.
    • Improved UI Composition: Added View Discovery to UI Composition. View Discovery: when a region is created, the region looks for all the ViewTypes associated with the region and automatically instantiates and loads the corresponding views. This is a simple approach to create new views.
    • Hands-on-Lab for Silverlight: Provide a Hands-on-Lab for Silverlight that walks you through how to create your first application using Prism.
    • New UI: Upgraded the UI with this release which includes new Silverlight and WPF animations.

     The Prism release adapts Model-View-ViewModel (MVVM) model (refers to this as the presentation model to match what some other pattern documentation in the greater technology world uses) in the reference implementation of the Stock Trader application.

    Prism 2 is an evolution from a July 2008 release (Prism 1) that was primarily for WPF applications.  The version v2 release brings updates and those concepts to Silverlight, including an implementation of commanding in Silverlight as well as demonstration of the use of input validation using these concepts.

    Prism consists of:

    • Reusable library components, for both WPF and Silverlight.
    • All source code, Unit tests, Automated acceptance tests.
    • Hands on labs (26) that guide you through all aspects of creating a composite application.
    • Quickstarts (9) that illustrate all components of prism.
    • A completely functional reference implementation that shows you how to build a composite application.
    • A lot of documentation and guidance:
      • How to create composite applications
      • How to use the Prism libraries
      • How to use Dependency Injection in your application (Unity)
      • How to create applications that target both WPF and Sliverlight.
      • Which design patterns were used to create prism
      • How to use separated presentation patterns (like Model – View – Viewmodel) to test your UI logic
      • And much, much more.
    • Api Reference documentation
    • A Visual Studio Plugin that helps you to target both WPF and Silverlight with a single codebase. 

    You should consider using prism:

    • If you want to create modular applications, in WPF and / or Silverlight so you can Develop, Test, Version and Deploy your modules independently of each other.
    • If you want to create an application that targets both WPF and Silverlight with a single codebase, or at least reuse a lot of code assets between WPF and Sliverlight.
    • If you want to minimize initial download size Silverlight applications. Prism allows you to just download the minimum of functionality you need to start your application. Other modules can be downloaded on a background thread or on demand.
    • If you are interested in using separated presentation patterns, because you want to create Unit Tests for your UI logic or if you want to make it easier to reskin your application.

    Links :