observable pattern on client side - asp.net

Is there any work around for client side data binding in mvc. I'm looking for something like implementing a observable pattern on client side somehow?

Take a look at knockout it might provide something like what you are after
From their site
Declarative Bindings Easily associate DOM elements with model data using a concise, readable syntax
Automatic UI Refresh When your data model's state changes, your UI updates automatically
Dependency Tracking Implicitly set up chains of relationships between model data, to transform and combine it
Templating Quickly generate sophisticated, nested UIs as a function of your model data
Also
Knockout is a JavaScript library that helps you to create rich,
responsive display and editor user interfaces with a clean underlying
data model. Any time you have sections of UI that update dynamically
(e.g., changing depending on the user’s actions or when an external
data source changes), KO can help you implement it more simply and
maintainably.
Headline features:
Elegant dependency tracking - automatically updates the right parts of
your UI whenever your data model changes. Declarative bindings - a
simple and obvious way to connect parts of your UI to your data model.
You can construct a complex dynamic UIs easily using arbitrarily
nested binding contexts. Trivially extensible - implement custom
behaviors as new declarative bindings for easy reuse in just a few
lines of code.
In order to prevent some of the additional work in creating viewmodels if you already have JSON objects being returned to the client you could use the Knockout Mapping plugin:
Knockout is designed to allow you to use arbitrary JavaScript objects
as view models. As long as some of your view model’s properties are
observables, you can use KO to bind to them to your UI, and the UI
will be updated automatically whenever the observable properties
change.
Most applications need to fetch data from a backend server. Since the
server doesn’t have any concept of observables, it will just supply a
plain JavaScript object (usually serialized as JSON). The mapping
plugin gives you a straightforward way to map that plain JavaScript
object into a view model with the appropriate observables. This is an
alternative to manually writing your own JavaScript code that
constructs a view model based on some data you’ve fetched from the
server.
There are also other frameworks that do similar things like:
Backbone.js
More alternatives here
If you want to implement it without using a "big" framework maybe take a look at this:
https://stackoverflow.com/questions/1005300/example-of-javascript-observer-pattern

Related

Is there an elegant solution for models that are very similair and do have a relation towards each other, but are not quite the same?

I've recently started developing in .NET core.
When developing I encountered the situation that I have to make very similair models that aren't quite the same. For example, let's talk about a booking model:
Frontend: Here I need a model that gets posted as a JSON to my backend and gets deserliazed to a sort of FrontendBooking model.
Backend: I need to add Customer data to the booking, therefore I need to add fields like: CustomerName and CustomerAddress, based on their CustomerId. The backend needs to provide this data, I do not want the frontend to determine these fields. I combine these models to prepare it for an API call. To a model called RequestBooking.
API: I sent RequestBooking to an API and get a response with a similair object that has for example a Status and BookingId added, this was added to the model by the API. So I need to deserialize this to an object called: ResponseBooking.
Database: Finally I wish to store the object to a database, not all properties of the model are relevant however, therefore I create another model called: DatabaseBooking and store this to the databse.
When a property is added, removed or changed. Then I'll have to change it for each of these models.
Is there a design pattern or some other solution, so this is more manageable?
Also, what is best practise for naming these models? Naming them all Booking doesn't feel quite right and adding what they're used for doesn't feel quite right either.
Thanks in advance.
Well, in general you will need different (although similar) models at least at these levels:
Server: here you can make use of Domain Driven Design. You will have an object Booking that is responsible for its logic and contain all properties and methods like e.g. MarkAsCancelled. You can use Entity Framework to use the same object in the database, which will correspond to a database table. EF allows you to mark some properties as not being saved in the DB. Also you can set up EF in the DbContext class and thus not use DB specific attributes in the class. So one object for DB and backend business logic.
API: obviously you cannot send your domain object to the API, e.g. REST. In the API you may want to combine properties of several domain objects or hide some properties. You will have to define a set of Data Transfer Objects (DTOs), e.g. BookingDto. How to convert your domain objects to DTOs? Solutions like AutoMapper may help. You just set up convertion rules once.
Now you can describe your API in e.g. Swagger. With Swagger Codegen you can than generate code for your server (.net) and client (e.g. JS).
In the end you will have to support the following:
API definition (e.g. Swagger). Code for server DTOs and client
objects is autogenerated. You modify API definition once, both sides
get new objects.
DDD Models that also are used for the Database. They
may be faily independent from your DTOs. Mapping is handled for you
semi-automatically by e.g. Automapper
All said is just a suggestion. All the layers and number of objects can and should be adapted to the specific needs of your project. E.g. you may want to use separate objects for the database if you are not using a relational mapper like EF or do not want to mix DB and logic.

Avoid creating models in Angular

I'm about to start a new project and I'd like to use Single Page Application technique. Since I'll be using ASP.NET I think the easiest way will be using Angular, which I'm new with.
Anyway, what scares me the most about Angular (or any other JS/TS tech), is since I don't have much time, I can't afford to rewrite all the models/entities to another language. The code and maintenance cost of this is too high for me.
tl;dr
So my question is, is there a way to have Angular use the original model/entity names so I can use them in the page without the need to rewrite any unnecessary code?
Will the .NET attributes take action?
I guess your concern is, that your business object world (entity model) needs to be reflected in your client/angular app as models (javascript objects) ?? The need for them comes also from typing errors you get in angular 2.
Creating and maintaining a transparent model world spanning server and client part is way too much effort for real world applications, although it would be nice.
I decided to use and receive the model as a result from a remote call via AJAX/WebAPI and work with these "models" in my client applications. The result then reflects your business model (entities) you have probably defined already.
this.dataService.getRecords('MT_MyEntity')
.subscribe((data: any[]) => {
var response: any = data; // Do this to avoid typing errors
var resprecords: any = response.items;
// Here you get entities;
// Deal with your business objects fetched from remote system; Use it to show in forms, ....
},
error => {
// your error handling
});
In your application you can use the entity and attributes names you have defined in your server side model (take care of upper/lower case modifications)
For me this is a pragmatic way to deal with that and it works very well.
For any decent size application the benefits of creating client side model far outweigh the effort required to create and maintain them.
This effect is more pronounce with TypeScript as it allows compile time checking of the contracts. As we move more and more code to client side and use frameworks like Angular, having a clearly defined model helps us understand what is happening. We derive the same benefits that we derive when type checking is available on server.
Having a separate client side model also allows us to adapt such model to client side UI needs (albeit sometime we create viewmodel to satisfy such requirements)
The approach of generating these client side contracts, as highlighted by #Ivan can help us to reduce the overall effort.

Best practice for managing / controlling object state with 2 way databinding using Polymer

Lets try this explanation again...
I'm new to polymer (and getting back into web dev after a relatively long absence), and I'm wondering what the recommended approach might be to more closely manage object state while employing 2 way databinding. I am currently consuming rest API (json) objects. My question is if polymer keeps a copy of the original object before initiating updates to the bound object's properties/attributes...so one might be able to easily undo the changes? While allowing 2 way databinding to work its magic is often desired, there are cases where I'd like to prevent / delay changes to the object / DOM until the user approves the changes (say via the paper-dialog component for instance). I suppose one could make a temporary copy of the object and bind fields to that version, and then only persist the changes back to the source object upon user approval. In any case, I'd be interested to hear thoughts and see an example or two of recommended approaches (especially if I am off-track with my ideas!)
I suppose one could make a temporary copy of the object and bind
fields to that version, and then only persist the changes back to the
source object upon user approval
This.
Consider that view-models are essentially different from pure data-models (sometimes called business-data). Frequently, the differences are irrelevant and one can use them interchangeably. However, be aware of scenarios where the view-model is distinct (uncommitted user edits are a good example).
The notion of a field editor that requires approval from the user is purely UI/View oriented. Whatever data is managed in that modality is purely in the domain of the view, and fetches/commits to the business-data should be discrete.

Developing a short-term web-based data entry UI

Say you had to quickly build a data-entry UI that works in a web browser, which must interface with a business layer, which must interface with a data layer.
You want to connect only to business objects, not directly to the database.
Most of the views of the UI will be simple CRUD operations, with edit/update happening within a grid.
But some of the screens will be more complex, representing many-to-many relationships.
What's the fastest way to achieve this in ASP.NET?
(Note: speed of development is high priority, code quality and re-usability are low priority.)
Entity Framework + ASP.NET Dynamic Data?
If speed of development is the main priority, then go with what you know.
For example, if you know ado.net/enterprise library then go with that. If you know Entity Framework or LINQ, then go that route.
Without a summary of your skills, it's going to be impossible for anyone to tell you the fastest way to get something up and running.
I've written a lot of little business editors like this for my company in the same manner, get it to work quickly, if it's used or needs to be improved, I deal with that later.
Start up a new asp.net project. Add a class library to the solution and reference it from the asp.net application.
Asp.Net Application
Use Master Pages and Themes
Use a repeater for the data lists and command buttons for selecting and deleting.
The repeaters work well for inner lists as well, take note of OnItemDataBound and OnItemCommand.
Use Panels to hold the lists and editors, write some logic to control when to view editors and when to view lists.
If the logic is common, then make some base pages that new editors can use and override.
Class Library
Add your business objects
Add a Linq to Sql class and add database objects as necessary.
To make it simple, you could use the some of the time tested controls and objects:
User Interface Layer: GridView for displaying and providing links for editing and deleting data. Clicking on Edit link may open up a new Asp.net web page that holds FormView for inserting and updating records. Use ObjectDataSource to link methods at the Business Logic Layer to Create/Read/Update/Delete records.
Business Logic Layer: Apart from creating CRUD methods, you might need to use light weight serializable data transfer objects to pass data between different layers and a custom mapper to trnaslate data from and to other layers.
Data Access Layer: Linq to Sql might make the data access and manipulation quick and easy.
It depends on the complexity of the application. I would go with Linq to Sql. But then using Linq to Sql does not necessary provide a good abstraction between the business layer and the data access layer. But I find that using Linq to Sql you can quickly retrieve the data out of the storage and display it on the screen.
Also, if you want fast UI then take a look at dynamic data website. That also uses Linq to Sql or Entity Framework.
One question you must think is that if you need good design or RAD.

Inherited Classes and Dynamic Views in PureMVC (AS3)

I was wondering best practices for views of inherited classes in PureMVC in this situation:
Multiple classes inherit a BaseClass (lets say InheritedClass1 and InheritedClass2)
Each InheritedClass has a respective view (derived from a base view class, but each unique)
With a given dataset (lets say ArrayCollection of InheritedClass1/2 Objects), the respective views need to be dynamically loaded.
The dataset is relatively large, so a TileList would be nice (since it only instantiates objects which are currently displayed)
I can think of a couple solutions, but I find them to be too "hackish" to be the best solution:
In View: Repeater over a BaseClassView which attributes a view to a State (set to the "InheritedClass1" state to add a InheritedClass1 object)
Pros: No unneeded memory increase (States' objects are instantiated when needed)
Cons: View is dependent on the data types, so adds coupling
In Mediator: Loop over the ArrayCollection and addChild() the views based on data type
Pros: Works.
Cons: Mediator is adding things to the View, which defeats the point of the separation of Mediator and View. Slower than a Repeater.
Any comments or other suggestions would be appreciated. Thanks!
The answer is simple if you like the first example. Why not have a map (Object()) on the mediator that assigns datatype to view component (or states). e.g.:
private static var map:Object = {"ic_oneType": "ic_oneState",
"ic_twoType": "ic_twoState"}
And the mediator can assign that map to the BaseClassView.
I'm likely to agree with the idea that you need some form of viewProxy that renders all your inherited views based on data fed to it from the mediator (e.g., first example). Can confirm or deny whether states is the best course of action in your UI though without more concrete examples.
Mediators are part of the View. How would you separate them from the View is beyond me.
I'd got with option 2.
Here's a topic from the pureMVC forum: Dynamically adding View components: where should I do it?.
The post by "pureMVC" should be of interest to you.
Also, the size of the dataset can be problematic. If it's really large you should consider using a List with renderers instead of adding a component for each item (repeaters do that). Which would further complicate things a bit because you'll have to wrap your data to keep the main component decoupled of the Model.
Cons: View is dependent on the data
types, so adds coupling
Typically, a view component has no other purpose than to display the domain data and possibly allow the user to interact with it. It is a given that the view component will need to have some understanding of the domain data.
So feeding a collection of VOs to your view component doesn't add a 'bad' coupling. A 'bad' coupling is when the view component knows about how to reach into the Model tier and manipulate the Proxy that holds the data. Or when the Proxies in the Model tier know how to get their hands on the view components or their Mediators to poke data into them.
Mediator is adding things to the View,
which defeats the point of the
separation of Mediator and View.
As Coded Signal pointed out, we're not trying to separate the Mediator from the View component. The Mediator is the one actor in the PureMVC system that should know the view component, and mediate the communications between it and the rest of the system. The Mediator is the most critical actor in the system with regard to loosening the coupling between the View tier and the Model tier.
To communicate with the view component, other actors send notifications, which the Mediator hears and responds to by manipulating the view component's exposed API; spoonfeeding it data or invoking methods on it. This effectively keeps the rest of the app from needing to know anything about the component.
The Mediator also listens to the component for events and acts on its behalf, retrieving data from the Model tier, or sending notes to to other Mediators or to trigger Commands in the Controller tier. This keeps the component from having to know anything about the system it is connected to. It simply exposes an API of properties and methods, encapsulates its own behavior and sends events when things happen that the system should know about.
So together, the Mediators and View components make up the View Tier of the application.
-=Cliff>
Cons: Mediator is adding things to the View, which defeats the point of the separation of Mediator and View
Not really: they're what the documentation refers to as a collaboration pair and should be treated as such.

Resources