Entity Framework Context lifetime - wpf

I have a WPF desktop app that using EF orm for mapping. My app have several pages
and each page has several windows. EF context is created per form. Pages in app using stateless entity only to show data the user.
My problem is that a page should update an entity for a single task and for this reason there should be a context living on this page. Therefore where I open window on this page for update other entities, there are 2 contexts active on this page.
How I can prevent this condition?

Create a new class "ClientRepository" in your project. This class will contain all entity framework access logic your client has.
Use this class in all your windows and pages.
If you configure this class to behave as singleton, you will only have one entity framework context.
Ideally this can be done using a DI framework like Microsoft Unit or Ninject, but of course you can also do it manually.
Singltons?
You might ask yourself, whether its a good idea to you singletons here.
I had a similar question once and thus asked Brian Noyes (Microsoft MVP) on a "MVVM" course on the pluralsight website.
In his response he wrote: "...most of my client services are Singletons anyway and live for the life of the app."
So, for a client service, its ok to have a singleton.

Related

Context Lifetime on a WinForms app .Net6 with Dependency Injection

I am having some issues with context lifetime on my .NetCore 6 win forms application. In summary, I have a button that when clicked calls a repository which then retrieves a record from my DB and displays one value from that record in a text field. This works ok until that value changes in the database. Further clicks of the button continue to display the old value.
This is how I register my context in the winforms app
services.AddDbContext<MyContext>(b => b.UseSqlServer(connectionString));
I then register my services like this:
services.AddScoped<IMyRepo, MyRepo>();
I guess this is an issue where the form is long running and never disposes the context, hence why the result is always the same until the form is closed and reopened with a fresh context.
I am using this in my repo to force a new result each time, however is seems like a bit of a mission to do this for every request to the DB I make...
_entities.Entry(log).Reload();
Is there a cleaner way I can do this without having to do the reload?
Honestly, I wouldn't use the MS IoC AddDbContext for WinForms/WPF. There probably is a way to have it play nice with some form of lifetime scope, but I'm honestly not aware of one. I don't use it for web projects either, simply because it scopes the DbContext to the request and I like to have a bit more control over the lifetime of the DbContext in some situations. (Dealing with poisoned contexts for instance)
For web and WPF I've used a Unit of Work pattern called the DbContextScope to manage the DbContext and relationship with the Repositories. The idea being that the consumers use an injected DBContextScopeFactory to create a DbContextScope (wrapping one or more DbContext instances) and the Repositories accept an injected DbContexScopeLocator to gain access to a requested DbContextScope.
The original EF6 implementation was by Medhi El Gueddari (https://github.com/mehdime/DbContextScope || https://www.nuget.org/packages/Mehdime.Entity)
For EF Core 6: (https://www.nuget.org/packages/Zejji.DbContextScope.EFCore6)
Alternatively if the scope of a DbContext can be contained within the repository calls themselves (tracked entities don't need to be passed outside of the repository) then you could also just use an injected DbContextFactory class to provide DbContext instances on demand. The advantage of a UoW pattern like above is that you have control over the scope the DbContext instance(s) live so multiple operations can be committed together or rolled back. The DbContext instance is available between multiple repositories if needed.

Can AngularJS work in Java EE MVC Architecture : JSP->Servlet->EJB3.1->Business Object->DAO

I have a quick question on considering AngularJS (current stable version - 1.3.9) for an upcoming application that we are building on an existing framework. The current framework has a Java EE MVC architecture and here are the current components mentioned in sequential order in which they get invoked:
View - JSPs: This layer gets as response Java Objects and we use jsp:useBean to access its properties and display on screen.
If any modifications are done on the page, it goes through a ControllerServlet i.e a Java file which has code to access the HttpRequest and HttpSession related information. The controller also does a lookup in JNDI to find the name of the bean to invoke based on the HttpRequest parameter name, e.g. PageId
Once the EJBBean lookup is returned, the controller invokes an EJB 3.1 "no-interview" view - These are Stateless Beans annotated with #Stateless
EJBBean classes then invoke BusinessObject classes, we call them "BO" which internally gets referenced by the DAO interface
A DAO implementation class is the one which is responsible for CRUD operations
Our Problems as of now:
The view is tightly coupled to Java Objects that are returned from DAOs and since the response is not converted to JSON, a lot of scriptlet code is used to display their value (I know scriplets are oldskool, but being a legacy solution there is no choice)
jQuery is used to manipulate the DOM before sending it to the controller layer
View is not the official record of whats happening on the screen, unlike AngularJS where I could easily understand
Developers write custom CSS for different browsers manually
Proposed Solution
View shall be designed for the new application using AngularJS
Take advantage of Bootstrap css classes which has readily available CSS which can be combined with AngularJS
Each request goes to ControllerServlet using $http service to ensure we use existing MVC architecture i.e routing every request through Controller
EJB Layer to be RESTFul to return data in JSON Format
Viewport specific css code for responsive web design - i.e same screen should render on multiple devices and platforms
Questions:
Is the proposed solution feasible? What are the downsides?
Is it a good practice to reference EJB Bean classes as RESTFul services?
Do we get access to all the Java EE objects / interfaces using AngularJS? For e.g. HttpRequest, HttpSession, etc.
Will it help in performing better by switching to this architecture?
Question from Management - Why not stick with jQuery! - Probably the hardest of all the questions to convince the management of Angular's benefits
Hope you guys can help throw some suggestions
i'm using spring 4.0.1 , hibernate 4.3.5 ,jackson 1.9.2 , I'm creating a RESTful webservice that returns a data in JSON format and angularjs in front-end which is loosely coupled with back-end.
concerning your questions;
the solution is feasible of course , until now there no downsides
except session management is tricky because Restful ws is stateless
.
it's provide a very elegant feature that you can access all your
functionality via any application web-client-side, desktop or
mobile.
angular app is fully isolated from back-end app you can maintain
requests and session in the server and respond with what you like in
json format to angular
same as 2
i hope it's helpful

Design decision to migrate Silverlight application

I have a silverlight application, it has pretty complex UI. In some forms I am using MVVM pattern. However there are many forms where code behind file has most of the form logic code (no view model).
Silverlight application is having both business and UI logic. There is a WCF service which SL application is directly calling. This WCF service is a data service (DB logic).
I want to migrate silverlight application into HTML5. I have following questions.
There are many links to migrate the SL application to HTML5 (even using MVVM pattern). Many suggests to use some JS framework library like AngularJS/Knockout. Can you please tell me which one works best for migration from SL?
Where would I put the business logic? Can I write my business logic using JS library? Also in case I write business logic using some library then won't it expose all my logic to client?
In case JS library is not the right thing to write the business logic then what other technology I should use? WebAPI or something else?
Atul Sureka
For Server Side Code Reusablity (MVVM) Code use AngularJS/KendoUI
Use C# Object to JavaScript Object Convrsion
Server Side Logic we can Re-Use, Client Side Logic C# to Java Script
User Rest API's

Should I use Servlet for Database access and Display results in JSP using JSTL?

I've been learning Java for more than 6 months. I'm developing a web app and learning through building it. I'm using Glassfish Server and MySql. No frameworks. Using Servlet, JSP and EJB.
Now I'm querying database through JSP page and displaying results. Is this the best way? or Should I use servlet for querying database and displaying results in JSP?
I want to display only part of the resultset object and show the remaining if the user wants to see it. So Could I implement this using jsp alone?
I would recommend usind your Servlet to handle the database-connunication only and perhaps some logging on the usage of the Connection. The logic would best be implemented in JSP alone since you can better maintenance it.
Querying database through JSP page is not the best way. And because you are not using any framework is definitely not the best way to learn. While learning you need to try as much frameworks as possible to find out which one you can use or not to use. You are also need to learn patterns for building Java EE applications.
Should I use servlet for querying database and displaying results in jsp?
This approach is much better, but is not enough because of coupling database code with servlet code.
I want to display only part of the resultset object and show the remaining if the user wants to see it. So Could I implement this using jsp alone?
What do you want to display should be coded in the servlet.
You should avoid coding your business logic codes in your JSPs. Segrate your application into multiple layers, take a look at MVC design pattern.
Model: These are plain POJO classes where your DB transaction and business logic happens.
Controller: This is where your servlets goes. These classes accept user request, call appropriate Model classes and send response to view.
View: This is you JSPs, displays data to users. Avoid using Scriptlets in your Jsps. Use JSTL and EL.
Take a quick look at this example MVC application, and do your own searching on MVC. Hope it helps you to get started.

SEO for a single view AngularJS app

I have a SPA here and I´m wondering what should I do to get it properly indexed by Google bot.
I read a lot on multiple views angularjs apps (hashbanging and that stuff) but my app has just one view / controller.
Should I create an html copy for each of the items being shown and link them together?
Thanks in advance,
Ariel
In AngularJS, you can compile templates & cache them using a variety of techniques - you'll need to write a process or build into your runtime logic building these templates & binding them to data, writing them out as static files.
Google allows for special handling based on user-agent. I have a friend who says, "This was called cloaking, before Google owned Angular." This is true. You need to setup server logic that re-directs any Google-bot user agent (or other search engine agents you care about) dynamically to one of these static "Search-Bot Friendly" pages.
Although this is more work, there are obviously bonuses to being able to maintain a set of content that search crawlers "see" and a (potentially different) set of content consumed by real users.
This is also the reason why AngularJS as a client-side framework quickly falls down the rank list when search visibility is a primary objective of the project.

Resources