Do I understand this MVC right? - symfony

I'm refactoring a large web app with another developer's help. In my mind, the backend is organized like so:
Symfony PHP: controller
PostgreSQL DB: model
As I understand it, the client-side browser is the 'view' of the server.
The frontend is additionally organized like this:
Redux.js: model + controller // this is all mildly simplified
React.js: view
Is it, therefore, conceptually correct to consider the client-side browser as the view of the server's state, and further, that the browser maintains its own state, controller, and view of the server-side data?
I'm a server-side "expert" (emphasize the quotes), while my helper is a front-end pro. We're deliberately trying to separate frontend and backend and restrict interaction to JSON payloads beyond the initial page load. If I'm looking at the global organization of the project right, it'll really help me organize our master codebase.

I don't think it's particularly helpful to think of the client-side app as just a view of the server-side state anymore.
The client-side is its own MVC application. Strictly, I don't think react-redux is actually MVC. It's considered an alternative to MVC. React is the View in MVC, but also a little bit of the Controller, and redux is an opinionated way of using the Model. You should read more here: http://redux.js.org/docs/introduction/Motivation.html
Relationship of the client-side M to the server-side M
Maybe another way of thinking about this is that the server has a 'model' and a part of the redux state-tree is actually kind of a view of that 'model' (like a list of todos derived from and kept in sync with a todo table on the server-side).
Parts of the redux state-tree could also have nothing to do with the server-side 'models' and could just be useful for storing client-side state (like the current url/route).
My firm belief is to not worry too much about the terminologies too much and stick to first principles. The server has state, the client-app has state. A part of the client-app's state is derived from and/or synced to the server-side state. The rest of the client-app's state helps generate the UI that the user sees. As the user interacts with the app, code is triggered that manipulates the state. Once you write a simple react-redux app, you'll see where all these pieces go!

Sounds about right.
The state of the application
React components maintain internal state. The state is updated via this.setState upon an event (e.g. click, mouse move, keyboard input, timeout, AJAX response, etc.). When this.setState is called, en entire re-render of the component is scheduled, after which, the component is then redrawn.
The cycle pretty much continues. You can think of React's state to work just like a traditional LAMP web app, that is, in an example web app, user submits a form, the page is updated with new content. Only that instead of you setting up the listeners, and imperatively telling react what data to pass in to this.setState, with a traditional LAMP app, you do so declaratively in the HTML declaration of the <form>, in the inputs that you define.
Albeit, the above React vs LAMP example is probably a bad analogy, because React does not directly work with the server. It's your responsibility on how to design your code to work with the server.
Communication with server
So, with LAMP, trivially, if you want user input to persist on the server, you simply record the input from a form POST request.
With react, there's an extra step on your end.
When a user triggers an event (click, mouse move, keyboard input, etc.), you first need to issue an AJAX request, which, of course, the server will act on the request (e.g. store form input).
In the (successful) response callback, you would then call this.setState to update what the server responded with. With a traditional LAMP app, you would get an entirely new web page rendered with the user's persisted data. With React, instead, you get back some piece of data (perhaps JSON or XML) which isn't the web page, but is used by your front-end application to determine what the page should look like.

Is it, therefore, conceptually correct to consider the client-side
browser as the view of the server's state, and further, that the
browser maintains its own state, controller, and view of the
server-side data?
Yes, it is completely correct.
In fact, you can think about your web app as an MVC that lives inside another MVC (the browser) that is then executed inside another MVC (the OS windowing system). Which communicates with another MVC across the wire (your backend app).
Now, swap MVC for "the implementation of a software design pattern", because there is no canonical definition of what MVC is. There are many variations, for example, MVC in the server is quite different from MVC in a client machine.
The server side approach is based on what is known as Java Model 2. This design shares the same philosophy as MVC and most of its components resemble it, so we all call it MVC. Which is not incorrect, although inexact too.
http://givan.se/mvc-past-present-and-future/#server-mvc
You can compare all of the documented patterns that belong to the MVC collection here:
http://mvc.givan.se/

Related

Asp .NET Web API using MVVM pattern

I'm trying to understand how I should use the MVVM pattern for a CRUD operation. Currently I have methods in my API controller such as below. My question is: using MVVM pattern, should I still build my api like that (e.g., accessing DB)? Or should it be changed? If nothing changes, in which case I would implement ViewModels and how they should be managed by the API? I made some researches but it's still not clear for me.
public IHttpActionResult GetProduct(int id)
{
var product = _context.Products.SingleOrDefault(p => p.Id == id);
return Ok(product);
}
[HttpPost]
public IHttpActionResult CreateProduct(Product product)
{
...
_context.Products.Add(product);
_context.SaveChanges();
return Created(new Uri(Request.RequestUri + "/" + product.Id), product);
}
I think part of the problem is that you don't understand the role of MVVM in a web application. To understand, you have to look at a web application as composed of two separate applications--the server side, and the client side.
Server side, the pattern being used is MVC (not surprising, it's called ASP.NET MVC for a reason). If you're trying to fit your understanding of MVVM around the MVC pattern--don't. It doesn't apply. The MVC pattern on the server is simple to understand and implement; don't try to crowbar any MVVM into it. Just design your server side code using the server side pattern.
Client side is a different matter. By default, ASP.NET MVC using Razor pages renders your HTML on the server and delivers it for display to the client. And, typically, that HTML is designed to respond to users interaction with the page by posting back to the server. Your controller methods interpret these postbacks, perform the required logic, and render the correct razor page in response. But this isn't the only way to write a website.
More and more common, people are designing Single Page Applications. These use ajax callbacks to send the result of user actions back to the server, and then process the response. Server side, these requests are almost always handled through a WebApi controller method, not an ASP.NET MVC controller method. The request comes across the wire as ajax, and the result is usually returned as ajax. No HTML gets rendered. This is where MVVM comes into play.
Client side, these web pages typically use a javascript MVVM (ish) framework, like knockoutjs or angular. The response json is used to update view models that are bound to HTML elements in the web page. These frameworks handle synchronizing updates and user actions between the UI and these view models, just like Bindings synchronize updates between the UI and your view models in WPF.
Simply put, MVC is its own thing, and MVVM usually only exists within the client side of a website, and usually only when the website extensively uses ajax callbacks instead of postbacks.
And, to answer your direct question, if you're using MVVM on the client side, using ajax calls to perform your CRUD ops, you should design your WebApi controller methods to Post/Get/Put/Delete your data.
Personally, I always use the Repository Pattern for anything to do with CRUD operations, such as interacting with an entity in a database.
I would create a separate class called "ProductRepository" and put all the methods to Get, Create, Update, and Delete a Product in that class. This way, only your Respository cares about the details of interacting with the database and performing the CRUD operations on it. Your entire application should not care about how this gets done, only your Repository class. This is something known as the Single Reponsibility Principle. It is part of the "SOLID" principles of design and architecture.
Then, in either your Controller or ViewModel or where ever you need it to happen, you just have to instantiate the ProductRepository and use its methods throughout your application.
If you use a separate Web API for your service layer and data access layer, then you don't really need MVC. You just need a front-end framework to consume the Web API URLs, like AngularJS or any other JS framework of your choice.
If you want to use MVC, then you don't really need Web API. You can just build your service layer and data access layer into the MVC application, or build them as separate projects (class libraries) and include them in your overall project solution. It all just depends upon how you want the architecture to be and how complex you want to go with it.
But either way, a "ProductRepository" should be involved -- whether it is in your Web API (if you go that route), or in your MVC project (if you go that route). The ultimate goal is to have separation of concerns. You want to separate your business logic layer from your data access layer. You don't want to be making direct calls to the database throughout your entire application. That will result in code that is very tightly coupled and hard to test and maintain over time. If you ever change out databases in the future, you only want to update one place in the code, instead of many places.
Hope this helps you out some! Best regards and happy coding!!!

Is event based model used in node the same as the event based model used in C# applications?

I've heard about node.js and event based programming and things like the node event loop. In college I remember that I made an ASP.net web application. The professor said that ASP.net uses an event based architecture where callback functions on the server side were triggered by different events on the client side.
Are the two different technologies using the concept for events and event driven programming?
They're similar in that they're both using the idea of events - something that calls your code, rather than you going out and looking for changes. But in practice they're quite different.
In node (and in asp.net MVC) the events in question from the client are "this URL was requested". That's it. There's no more granularity other than the contents of the request.
In ASP.NET Webforms, they work very hard to synthesize events based on what happened on the client page. The events you get are "text changed", "button clicked", "checkbox checked"... basically the same kind of stuff you'd get in a straight desktop app.
It turns out that the Webforms model gets really, really complicated really fast, and the abstraction layer gets in the way of doing things like ajax calls.
Another thing node does is that just about everything is async events, unlike ASP.NET. Database call? Async in node, sync in ASP.NET. Read a file? Async in node, sync in ASP.NET. HTTP request to another server? You get the idea.
ASP.NET can do those things async, but you have to go out of your way to do it, and it uses threads. In node the async stuff is pretty natural and it doesn't need to use threads, resulting (somewhat surprisingly) in higher throughput in some cases.
So yes, they're the same in the sense that they're both "events", but the details are staggeringly different.
Yes, node uses an event based architecture where callback functions on the server side are triggered by different events on the client side.
Why Node.js is a big deal.
1) Using the same language on the client and the server speeds development.
2) Every web developer already knows JavaScript. The transition path to using it on the server has a lower learning curve.
3) Modules built for Node.js are all event driven. Writing event driven code on other platforms usually requires you to sift through third party modules to find the ones that are event driven. For example, there are several event driven libraries for Python, but most third party networking libraries for Python are synchronous because of Python's heritage. Same with Ruby, Java, Scala and many other platforms.
4) Speed. Node.js runs on the V8 javascript engine. It may not be quite as fast as Java or C#, but it's light years ahead of Python, Ruby and PHP. Python, Ruby and PHP make up a huge portion of the web application market share. When developers with their primary experience based in those languages need more speed, Node.js is a logical place to find it.

Attaching an event listener to all URLRequest's

We have a flex application that connects to a proxy server which handles authentication. If the authentication has timeout out the proxy server returns a json formatted error string. What I would like to do is inspect every URLRequest response and check if there's an error message and display it in the flex client then redirect back to login screen.
So I'm wondering if its possible to create an event listener to all URLRequests in a global fashion. Without having to search through the project and add some method to each URLRequest. Any ideas if this is possible?
Unless you're only using one service, there is no way to set a global URLRequest handler. If I were you, I'd think more about architecting your application properly by using a delegate and always checking the result through a particular service which is used throughout the app.
J_A_X has some good suggestions, but I'd take it a bit farther. Let me make some assumptions based on the limited information you've provided.
The services are scattered all over your application means that they're actually embedded in multiple Views.
If your services can all be handled by the same handler, you notionally have one service, copied many times.
Despite what you see in the Adobe examples showing their new Service generation code, it's incredibly bad practice to call services directly from Views, in part because of the very problem you are seeing--you can wind up with lots of copies of the same service code littered all over your application.
Depending on how tightly interwoven your application is (believe me, I've inherited some pretty nasty stuff, so I know this might be easier said than done), you may find that the easiest thing is to remove all of those various services and replace them by having all your Views dispatch a bubbling event that gets caught at the top level. At the top level, you respond to that event by calling one instance of your service, which is again handled in one place.
You may or may not choose to wrap that single service in a delegate, but once you have your application archtected in a way where the service is decoupled from your Views, you can make that choice at any time.
Would you be able to extend the class and add an event listener in the object's constructor? I don't like this approach but it could work.
You would just have to search/replace the whole project.

Does the SessionState attribute in MVC 3 work properly?

I'm managing a rather large project, written in asp.net webforms + mvc3, with a large user base, and a pretty high daily visitor count. Basically, there are a lot of requests at any given moment.
One of my controllers in MVC that handles / resizes images on the fly has the following attribute applied to it:
[SessionState(SessionStateBehavior.Disabled)]
Now, if an action in the controller tries to access the session - it obviously throws an exception - so we're good so far.
The problem is: if I go to the IIS Worker Processes window (Win Server 2008 R2, IIS 7.5), and check the current requests for this site, I can sometimes see the requests to an action in this controller. Their current state is locked in State: RequestAcquireState, Module Name: Session. Sometimes these locks go over a second or two in this state.
Wasn't the whole point of the attribute in the first place to make the requests to the controller ignore the state, and not waste time (and possibly being locked) trying to acquire the state?
If this is so - am I doing something wrong here, or does the problem lie elsewhere?
[migrated from comments]
If you're using a custom controller factory or route handler, make sure that they're aware of the controller's session state behavior. Marking a controller as not requiring session state requires cooperation from both of these components. Out-of-box, the DefaultControllerFactory and MvcRouteHandler are designed to work with this. See DefaultControllerFactory.GetControllerSessionBehavior and MvcRouteHandler.GetHttpHandler for more information. If you're writing custom components, you can use those methods as inspiration.

Session information in .net (asp and webservice)

I'm making a .net component, resulting in a dll assembly, that will be referenced by an asp.net site, and in another project by an asmx webservice. All code is version 2.0.
The component has a few functions that call an external webservice, which returns an object. One of these functions is for example Login(username, password), which generates amongst others a unique session id for this user. The resulting information and session id are stored in variables in the component.
The issue in the website is:
When the user logs in in the frontend, and my component gets called and checks the login and generates the session id, I want that information in my component to persist when the user browses to another page in the site.
The issue in the web service using my component is:
I don't really care much about session state, but I want the component to just work. If per call a new session id is generated, that's okay.
The combination of the two environments causes the following problem for me:
I can't use the asp.net Session() variable in my component without referencing system.web, which is kinda silly and might not be available in the web service project that includes my component
I can't program my component as a singleton, because then in the website application, it's shared amongst all visitors, overwriting sessions and whatnot
making an array of "session information" in my component and maintaining that is hard to program (when does it get invalidated?) and might not work in a web farm environment
Is there a solution to this situation? Or should I make two instances of my component, one for use in websites, and one for use in web services?
Perhaps I'm not understanding what your asking but why can't you do something like:
Component.Login(user,pass);
Session["Component"] = Component.SessionID
I've created an extra class "Factory" which has a .Create(byref Session as HttpSessionState), that looks if the passed in session object is Nothing, if not, it checks if there is a Component object in it, if so, it uses it, if not, it creates it and adds it to the session.
In the case of the webservice call, the factory gets the Nothing-parameter, so it doesn't check in the session object. It seems to work.
Thanks for your answers!

Resources