Sessions in MVC [closed] - model-view-controller

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Where does session handling fit in the overall concept of MVC? The model or the controller?

The purpose of the SessionState is to persist data about the user's session from one HttpRequest to the next. In some cases this is an an easier solution than manually implementing cookies or creating a data store for session info and passing an identifier. MVC's way of doing this is to use TempData, which wraps SessionState. This means it is probably unnecessary to directly access the SessionState unless you are overriding some of the core infrastructure. I think of a Model as being a more metaphorical representation of data. Using session-data in the Model wouldn't seem entirely right, because the model is probably representing some business logic, that SessionState would unnecessarily complicate. System.Web.Mvc provides a lot of mechanisms that allow us to maintain state without having to use the HttpContext directly. These mechanism are contained as properties of the ControllerContext, the ActionFilter filtering contexts, the ExceptionContext, the AuthorizationContext, the ModelBindingContext, RouteData and ViewContext. They help to separate the bunch of different things that one might store in a session state collection in more logically separated compartments.
TempData is available from the ControllerContext and the ViewContext. This is your access point to session state functionality. If you want to control the handling and writing of this data, and aren't sure where, action filters are a pretty good injection point, because they keep that concern out of the primary business-oriented controller action. This article explores the use of an ActionFilter that automatically persists the model state across requests: http://blog.jorritsalverda.nl/2010/03/10/maintainable-mvc-post-redirect-get-pattern/. I think it may be helpful. The question was not terribly specific... If I did not directly address your question please clarify.

I prefer keeping them at the Controller level or to hide them in custom Action Filters or model binders.
Session state is really a web client concept, I prefer to keep them out of my model for layering sake. Or at minimum I'd wrap it in my own Session or context interface.

Related

How do I manage common data when creating microservices [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Im refactoring a monolith to microservies. I am not clear on data responsibility and access with microservices. From what I read we should take vertical slices.
So each service should be responsible for its own UI/WebAPI/DB, with distinct responsibility.
For example if I had a monolith shopping cart app, I could break it into the following services:
CustomerAccount
ProductSearch
ProductMaintenance
ShoppingCart
Ordering
What do I do with shared data, how do I determine what part of the system is responsible for it?
e.g. In my shopping cart example...
The CustomerAccount, ShoppingCart and Ordering need to know about the Customer data.
The ProductSearch, ProductMaintenance, ShoppingCart and Ordering need to know about Product Data data.
The Ordering will update the number of products available, but so should the productMaintenance.
So should the services send messages back and forth to get data from one another,
or should there be a master service, which handles the communication/workflow between services
or should they read/write from a common database
or something else?
This seem little late to answer but it may be good for future use.
Microservice calling another Microservice is totally fine, what you should be aware of is in case the communication between Microservices becomes to chatty than you should look at a different solution(maybe duplication of data across services, or have it with in same service).
In your case I would build a separate services for each entity that you call for common and reevaluate the situation afterwards.
Hope this helps
Best regrads
Burim

Explications about EventSourcing, Microservice, CQRS [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am currently building an app, and i would like to use microservices as pattern and GraphQl for communication. I am thinking about using kafka / rabbitmq + authZ + auth0 + apollo + prisma. And all of this running on docker.
I found many ressources on event sourcing, the advantage/disavantage, and I am stuck on how it work in the real world. As far, this is how i will do it:
Apollo engine to monitor request / responses..
Auth0 for authentification management
AuthZ for authorization
A graphql gateway. Sadly I did not find a reliable solution, I guess i have to do it my self using apollo + graphql-tool to merge schema.
And ideally:
Prisma for the read side of bill's MS
nodejs for the write side of bill's MS
Now if I understand correctly, using apache kafka + zookeeper :
Kafka as the message broker
Zookeeper as an eventstore.
If I am right, can I assume:
There would be 2 ways to validate if the request is valid:
Write's side only get events (from event store, AKA zookeeper) to validate if the requested mutation is possible.
Write's side get a snapshot from a traditional database to validate the requested mutation.
Then it publish an event to kafka (I assume kafka update zookeeper automatically), and then the message can be used by the read's side to update a private snapshot of the entity. Of course, this message can also be used by others MS.
I do not know apache kafka + zookeeper very well, in the past i only used messaging service as rabbitmq. They seems similars in the shape but very different in the usage.
The main difference between event sourcing and basic messaging is the usage of the event-store instead of a entity's snapshot? In this case, can we assume that not all MS need an event's store tactic (i mean, validating via the event store and not via a "private" database)? If yes, does anyone can explain when you need event's store and when not?
I'll try to answer your major concerns on a concept level without getting tied up with the specifics of frameworks and implementations. Hope this will help.
There would be 2 ways to validate if the request is valid:
. Write's side only get events (from event store, AKA zookeeper) to validate if the requested mutation is possible.
. Write's side get a snapshot from a traditional database to validate the requested mutation.
I'd go by the first option. To execute a command, you should rely on the current event stream as authority to determine your model's current state.
The read model of your architecture is only eventually consistent which means there is an arbitrary delay between a command happening and it being reflected on the read model. Although you can work on your architecture to try to ensure this delay will be as small as possible (even if you ignore the costs of doing so) you will always have a window where your read model is not still up to date.
That being said, your commands should be run against your command model based off your current event store.
The main difference between event sourcing and basic messaging is the usage of the event-store instead of a entity's snapshot? In this case, can we assume that not all MS need an event's store tactic (i mean, validating via the event store and not via a "private" database)? If yes, does anyone can explain when you need event's store and when not?
The whole concept of Event Sourcing is: instead of storing your state as an "updatable" piece of data which only reflects the latest stage of such data, you store your state as a series of actions (events) that can be interpreted to reach such state.
So, imagine you have a piece of your domain which reads (on a free form notation):
Entity A = { Id: 1; Name: "Something"; }
And something happens and a command arrives to change the name of such entity to "Other Thing".
In a traditional storage, you would reach for such record and update it to:
{ Id: 1; Name: "Other Thing"; }
But in an event-sourced storage, you wouldn't have such a record, you would have an event stream, with data such as:
{Entity Created with Id = 1} > {Entity with Id = 1 renamed to "Something"} > {Entity with Id = 1 renamed to "Other Thing"}
Now if you "replay" these events in order, you will reach the same state as the traditional storage, only you will "know" how your got to that state and the traditional storage will forget such history.
Now, to answer your question, you're absolutely right. Not all microservices should use an event store and that's even not recommended. In fact, in a microservices architecture each microservice should have its own persistance mechanism (many times being each a different technology) and no microservice should have direct access to another's persistance (as your diagram implies with "Another MS" reaching to the "Event Store" of your "Bill's MS").
So, the basic decision factor to you should be:
Is your microservice one where you gain more from actively storing the evolution of state inside the domain (other than reactively logging it)?
Is your microservice's domain one where your are interested in analyzing old computations? (that is, being able to restore the domain to a given point in time so you can understand its state's evolution pattern - consider here something as complex auditing where you want to understand past computations)
Even if you answer "yes" to both of these questions... will the added complexity of such architecture be worth it?
Just as a closing remark on this topic, note there are multiple patterns intertwined in your model:
Event Sourcing is just the act of storing state as a series of actions instead of an updatable central data-hub.
The pattern that deals with having Read Model vs Command Model is called CQRS (Command-Query Responsibility Segregation)
These 2 patterns are frequently used together because they match up so nicely but this is not a prerequisite. You can store your data with events and not use CQRS to split into two models AND you can organize your domain in two models (commands and queries) without storing any of them primarily as events.

Disadvantages to define a form bean with session scope in struts 1.x

What are the major disadvantages in using a form bean with session scope in struts 1.x?
You need to implement reset() if your form contains attributes populated from checkboxes. You don't need that to request-scoped form beans.
You need to reset the form to its default values if you show a creation form for the second time, else the creation form will redisplay the data coming from the last created/updated object.
You can't have two browser tabs or frames using the same form, because they will walk on each other's toes.
Form beans should be in the request scope by default.
Just try to work with both scopes and choose one preferred for yourself. But I should say there is small difference when you are working with persistent objects (and ORM tools like Hibernate), just because properties are persisted in database between requests.
Infamous checkboxes (and corresponding boolean properties). If you are working with persistent objects (editing boolean properties of some entity), you'll need extra code to reset checkboxes anyways. Scope doesn't matter because boolean property is persistent (isn't cleared automatically between requests).
When you are working with complex persistent objects (hierarchies of objects, mapped by Hibernate onto set of related database tables), often you'll just nest persistent object into form-bean and use nested properties, e.g. <html:text property="purchase.client.name" /> (of course, you can create getters/setters in form-bean for each property of the entire hierarchy, but this is tedious and will complicate further development). For creation you'll just create new empty purchase object in form-bean, for edition you'll load existing purchase from database (request for edit will contain some identifier of object you want to change). Scope doesn't matter again.
About two browser tabs. More important and underestimated problem arises with usage of AJAX requests, especially when they are not idempotent and are overlapped in time (browser issues request for update 1, then request for update 2, while update 1 is still processed on server) - although it is very strange design (I mean overlapping update requests simultaneously in one session from one user). Yes, in that case you'll need to separate data in different requests. But moreover, your action (if we are talking about Struts 1) should be thread-safe, and your business logic should be ready to concurrent/conflicting updates (solve synchronization problems, lock objects, merge/override/reject updates etc.). If you are developing multi-user application, this may happen also when two different users want to change the same object simultaneously. Again, bean scope has little importance comparing to the whole problem.
As you can see, there is only one disadvantage with session-scoped form bean, and it arises only in relation to serious design flaw (overlapping update requests from one user).

Where does session data belong in Wicket?

Since Wicket automatically manages session state by serializing the components in my page, I'm left wondering, at which level I should attach my state data. More specifically, it seems like a bug I'm having is caused by the WebApplication object being shared among sessions.
Is the application instance shared between sessions?
Should I always attach session data to the Page instance?
What happens if I reuse components with attached session state on multiple pages? Are those instances shared, i.e. if I set the state on the component on one page, is it carried over to another?
I'm guessing, the third bullet point depends on object identity. What does Wicket use to determine that, equals() (like, is it using a Map)?
The data I attached to the application object is state I would need in many pages, so I didn't attach it to the page objects. Is that the correct way to do it in Wicket?
Yes, that's the point of having an Application object. You can store and access application-wide data (usually config) through your Application subclass at any point.
No. There are cases when you need to share session data across multiple pages where storing it in a Session object is more adequate. (An example could be a user login, which definitely belongs to the session and may be used by any page.) Of course you can pass the data around between the pages but it's not a very good strategy. Where the cutoff point is will be your decision: if data is shared between two pages, you might want to pass it from one to the other, if there are 20 pages, you definitely won't want to.
You're not supposed to reuse component instances across different pages. Of course you'll reuse the class but you'll have to construct a new one on each page. This is exactly where storing data in the Session object might come handy.
To clarify: The number of pages sharing state is an indication of where to put the data, but what really matters is how tightly you want the items sharing data to be coupled:
If you pass data as parameters between pages, they will form a tightly coupled group. Depending on what the pages represent, this might be desirable. An example for this may be a wizard-like sequence of pages, with each page knowing what the pages before and after are.
But in the login example we see the opposite: the component populating the login name (probably some kind of login form) must not know about what other components are going to use it. So the logical solution is to store the login name in the session and let each component fetch it as and when they need it.
There are multiple ways to get hold of the current Session object. Check the documentation of the class to see how.
To summarize the information there: Wicket discourages type-unsafe session properties by not providing generic setProperty-like methods. Instead, you are supposed to extend Session, or for most projects, more adequately, WebSession and place typesafe properties in that class. You then override newSession on your application class.

Edit a model over several views

Is it possible to have one model that you break up into several views so that the user is not overwhelmed by the amount of data they will need to input? I'm trying to build a turbo tax like interface where a question or two are asked, then the user clicks next to answer the next set of questions and so on.
The Model doesn't seem make sense to break up into more models. Since it is a single distinct entity, like a questionnare.
See similar question for a nice example:
multi-step registration process issues in asp.net mvc (splitted viewmodels, single model)
It is possible to use the same model for multiple views, but you should decide how you want to preserve the state as you go though this "wizard". One approach can be to cross-post between the views and keep the state in post data, but in that case you have to add a lot of hidden fields for all model properties that are otherwise not displayed in an input on the current view. Another approach can be to persist the partially filled model, with the additional benefit, that the user might be able to continue after a session timeout or another problem, but then you might need to clean up stale data and be flexible in the validation on the database level. You can also preserve the state in the session if you want. Finally, you can also keep the state in the browser independent from the post data and do only AJAX calls with the server until you reach the point when you want to save everything.

Resources