How to bind Maps of Maps, or some other way to structure the data - spring

I am not even sure how to go about asking this, but I will try to give it a shot.
I have an existing application that I support that consists of a dynamically generated form of a bunch of values. The form is broken into a matrix of rows and columns, and the JSP uses this information to construct the required form:inputs. To build the form I have some Java classes like such (mostly pseudo code just so you get an idea as to what I am doing):
class Form {
List<FormParts> parts;
}
class FormParts {
List<FormRow> rows;
List<FormHeader> headers;
}
class FormRow {
String name;
}
class FormHeader {
String name;
}
I use these classes to dynamically build the form in the JSP by looping through the FormParts, then using the FormRows and FormHeaders to build a table of form:inputs, using a counter to index the resulting answers List described here in the FormResponse:
class FormResponse {
List<FormAnswer> answers;
}
class FormAnswer {
int rowNumber;
int headerNumber;
String value;
}
The problem I am having is the List<FormAnswer> answers. Because it's a List I have to store all the Answers, even the empty ones (nulls), in order to be able to provide the ability to reload the FormResponses from the DB. This is creating a HUGE amount of junk rows in my table, and making the application slow. When I first wrote this about 4 months ago, however, I remember I struggled for some time trying to figure out how to make Spring MVC bind to a Map of Maps, which would be a MUCH better way to implement this since I could simply skip the answers I don't need. I remember the problem was that, internally in Spring MVC, those Lists and Maps become LazyList and LazyMap.
Does anyone have another possible solution to this?

Check my answer on dynamic forms with Spring here at Auto populating Set .
The key is to use Map<Integer, YourObject> instead of lists. With that you can have gaps in your indexes.
Using Map of Maps is not possible, because the generics will be erased. The map always need to be property of object. So your example should be OK.
Concept of LazyList / LazyMap is long dead. Spring is capable of manipulating any list and map type. If the Map property is null, an instance of LinkedHashMap is created by default.
Other possibility is to do your binding and validation manually and just send JSON via the wire (i.e. submit your form as JSON in <input type="hidden"> or directly via AJAX).

Related

Petapoco missing attributes IgnoreOnInsert, IgnoreOnUpdate

I'm trying to use Petapoco in my Umbraco powered website. On my poco's I have a column called Created which has a default sql value (getDate()). I would like that column to be ignored on insert and update by Petapoco, but not on read.
Any idea how can I achieve that elegantly? perhaps with a custom mapper or including some new attributes in Petapoco engine (like IgnoreOnInsert, IgnoreOnUpdate).
I've been using some hacks, one of them was having two poco's for each table, one for insert-update and one for reading. But it's difficult to accept that as satisfactory.
I usually just make a class constructor and set the date property there. Something like
public class WhatEvs
{
...
public WhatEvs()
{
DateCreated = DateTime.Now;
}
}
In case anyone is still interested in this, I eventually found a nice solution.
And that is to stop using Petapoco and switch to NPoco, which has a nice attribute called 'ComputedColumn'.
If you decorate a property with [ComputedColumn] attribute, that property will not be used when NPoco generates insert and update queries, but it will be used in select queries.
That allows me to nicely have database handled values like CreatedDate or UniqueGuid which I don't touch, but am able to get when querying.
Thanks to Aaron who kindly answered this problem here:
https://github.com/CollaboratingPlatypus/PetaPoco/issues/421#issuecomment-348390149

'Existing Entity' constraint

I'm reading some data from an excel file, and hydrating it into an object of class A. Now I have to make sure that one of the fields of the data corresponds to the Id of a specific Entity. i.e:
class A{
protected $entityId;
}
I have to make sure that $entityId is an existing id of a specific entity (let's call it Foo). Now this can be achieved using the choice constraint, by supplying the choices option as all of the existing ids of Foo. However this will obviously cause a performance overhead. Is there a standard/better way to do this?
I'm a bit confused about what you are doing, since you seem to talk about Excel parsing, but at the same time you mention choices, which in my opinion relate to Forms.
IMO you should handle directly the relationship to your entity, instead of only its id. Most of the time it is always better to have directly the related entity as attribute of your class A than only the id, and Symfony manipulates such behaviours pretty well.
Then just have your Excel parser do something like this:
$relatedEntity = $this->relatedEntityRepository->find($entityId);
if (!$relatedEntity) {
throw new \Exception();
}
$entity->setRelatedEntity($relatedEntity);
After doing this, since you were talking about Forms, you can then use an EntityType field which will automatically perform the request in database. Use query_builder if you need to filter the results.

Strongly typed ViewData for complex object persistence

I'm working on a ASP.NET MVC system where you may click on a ajax link that will open a window (kendo window but it does not affect the situation) which a complex flow. To make this less of a nightmare to manage, I made a ViewModel (as I should) but this ViewModel is a complex object due to the complexity of the procedure.
There is anywhere from a single to 5 windows that asks various questions depending on a lot of conditions (including, but not limited to, what time you click the link, who you are, what schedule is attached to your account and, obviously, your previous answers in this flow).
The problem is that having a complex object, I cannot simply make #Html.HiddenFor(o=>o.XXX). So I proceeded to find an alternative and it led me with a single option, TempData. I'm really not a fan of dynamics and object types. I'd really like to have this View Model strongly typed.
What would be the best way to approach this?
Here is a case where using Session or TempData might make sense. Contrary to popular belief, you can make these somewhat strongly-typed. Not like a viewmodel, but you can avoid keychain messes by using extension methods.
For example, instead of doing something like this:
TempData["NestedVariable1"] = someObject;
...
var someObject = TempData["NestedVariable1"] as CustomType;
You can write extension methods to store these variables, and encapsulate the keys and casting in the extension methods.
public static class ComplexFlowExtensions
{
private static string Nv1Key = "temp_data_key";
public static void NestedVariable1(this TempData tempData, CustomType value)
{
// write the value to temp data
tempData[Nv1Key] = value;
}
public static CustomType NestedVariable1(this TempData tempData)
{
// read the value from temp data
return tempData[Nv1Key] as CustomType;
}
}
You can then read / write these values from either controllers or views like this:
TempData.NestedVariable1(someObject);
...
var someObject = TempData.NestedVariable1();
You could use the same pattern with Session as well. And instead of saving each individual scalar value in a separate variable, you should be able to store an entire nested object graph in the variable. Either that, or serialize it to JSON and store that, then deserialize when you get it back out. Either way, I think this beats a ton of hidden fields written out to your view's form.

Best practice for persisting database-stored lookup data at app level in MVC

Slogging through MVC+EF and trying to focus on doing things the right way. Right now I'm looking to add a dropdown to a form but I'd like to avoid hitting the database every time the page loads so I'd like to store the data in the app level. I figure creating an application level variable isn't the best approach. I've read about using the cache and static utility functions but surprisingly, nothing has sounded terribly definitive. (Static classes bad for unit testing, caching bad
So I have two scenarios that I'm curious about, I'm not sure if the approach would differ between the two.
1) A basic lookup, let's say the fifty states. Small, defined, will never change. Load at application startup. (Not looking for a hard coded solution but retrieval from the database.)
2) A lookup that will very rarely change and only via an admin-like screen. Let's say, cities/stores where your product is being sold. So data would be stored
in the model but would be relatively static unless someone made changes via the application. So not looking to hit the database every time I need to populate a dropdown/listbox.
Seems like basic stuff but it's basically the same as this topic that was never answered:
Is it good to use a static EF object context in an MVC application for better perf?
Any help is appreciated.
I will address you question in a few parts. First off, is it inherently bad to use static variables or caching patterns in MVC. The answer is simply no. As long as your architecture supports them it is OK. Just put your cache in the right place and design for testability as I will explain later.
The second part is what is the "right" way to have this type of persisted data stored so you don't have to make round trips to the DB to populate common UI items. For this, I don't recommend storing EF objects. I would create POCO objects (View models or similar) that you cache. So in the example of your 50 states you might have something like this:
public class State
{
public string Abbreviation { get; set; }
public string Name { get; set; }
}
Then you would do something like this to create your cached list:
List<State> states = Context.StateData.Select(s => new State { Abbreviation = s.Abbreviation, Name = s.Name}).ToList();
Finally, whatever your caching solution is, it should implement an interface so you can mock that caching method for testing.
To do this without running into circular references or using reflection, you will need at least 3 assemblies:
Your MVC application
A class library to define your POCO objects and interfaces
A class library do perform your data access and caching (this can obviously be split into 2 libraries if that makes it easier to maintain and/or test)
That way you could have something like this in your MVC code:
ICache myCache = CacheFactory.CreateCache();
List<State> states = myCache.ListStates();
// populate your view model with states
Where ICache and State are in one library and your actual implementation of ICache is in another.
This is what I do for my standard architecture: splitting POCO objects and interfacees which are data access agnostic into a separate library from data access which is the separate from my MVC app.
Look into using a Dependency Injection tool such as unity, ninject, structuremap, etc. These will allow for the application level control you are looking for by implementing a kernel which holds on to objects in a very similar way to what you seem to be describing.

Displaying computed data with external dependencies

I'm building a report that needs to include an 'estimate' column, which is based on data that's not available in the dataset.
Ideally I'd like to be able to define a Java interface
public int getEstimate(int foo_id, int bar_id, int quantity);
where foo_id, bar_id and quantity are available in the row I want the estimate presented.
There will be multiple strategies for producing the estimate so it would be good to use an interface to allow swapping them when needed.
Looking at the BIRT docs, I think it's possible I ought to be using the event handler mechanisms, but that seems to only allow defining a class to use and I'd somehow like to inject a configured estimator.
A non-obfuscated example might be to say that I have a dataset which includes an IP address column, and I'd like to be able to use some GeoIP service to resolve the country from the IP address. In that case I'd have an interface public String getCountryName(String address) and the actual implementations may use MaxMind, a local cache or some other system.
How would I go about doing this?
Or.. would I be better off by writing a scripted data source that can integrate the computed data before delivering it to BIRT?
Or.. some sort of scripted data source that is then used to create a join data set?
I think a Scripted Data Source would work fine, but a Java-based event handler would be more straightforward. You can implement it as a simple POJO and get access to any and all the complex objects and tools that will allow you to calculate your estimate. The simplest solution of all may simply to be adding a calculated field to the data set.
When creating the calculated field, you can get pretty complex in terms of the scripting logic you can leverage in order to produce the resultant value. The nicest thing about this route is that all the other column values in the row (which I assume you need to calculate the estimate) are made available via the Expression editor. You can pull in complex objects (POJOs) to help in your calculations here as well by using the "Packages" object (i.e. var red = new Packages.redwood.HelloWorld())
If you want to create the Event Handler class, here is what I would do. I would create a text object and bind the onCreate even to your POJO (by extending the TextItemEventAdapter) and override the "onCreate" method. There you can do any work you want to and at the end simply call 'text.setText(theEstimateResult);' to make the estimate itself visible. As far as accessing data values to do your calculations, You can get to those in the POJO too. I assume the estimate will be a part of a larger table of values. You can access any specific row value via the reportContext.
Those are the two ideas I would give a try first. The computed column is the fastest to implement and the least likely to throw you a curve during deployment. Let me know which way you choose and we can hash it out further if needed.

Resources