I would like to create a bidirectional binding between an IntegerProperty and a DoubleProperty. A converter function would be easy to write to create the mapping between the two values, but I cannot find a way to do it. I am looking for something similar in functionality to StringConverter, but with generic parameters.
Is there a way to do it in JavaFX?
Since they're both implementations of Property<Number> it should just work:
DoubleProperty d = new SimpleDoubleProperty();
IntegerProperty i = new SimpleIntegerProperty();
d.bindBidirectional(i);
Related
This is a pretty basic problem and I'm pretty sure I'm doing something wrong or making some assumption. Here goes.
I'm writing a Jira plugin, which uses the Velocity template system. I have a list of ResultRow objects where ResultRow is a class with a single member variable: String key:
public class ResultRow {
public String key;
}
I have a list of these ResultRows:
List<ResultRow> rows = new ArrayList<ResultRow>();
ResultRow row = new ResultRow();
row.key = "foo";
rows.add(foo);
Map<String, Object> velocityParams = new HashMap<String, Object>();
velocityParams.put("rows", rows);
return descriptor.getHtml("view", velocityParams);
and I am trying to list these rows in a template with the following:
#foreach ($row in $rows)
<tr><td>$row.key</td></tr>
#end
I want the output to be: foo. Maddeningly, the template system simply prints the literal string "$row.key" instead of the contents of key. To verify that "$row" is indeed an object, I used the template:
#foreach ($row in $rows)
<tr><td>$row</td></tr>
#end
and the result was as expected: com.domain.jira.ResultRow#7933f2c6.
I think maybe I'm missing some requirement for the class. Does it need to be defined in some special way to suggest to Velocity that certain members are usable in templates? Does Jira use some special funky version of Velocity that only works with certain objects?
I guess the answer is you cannot do what I was trying to do. You can call member methods but you can't access member variables, which means you'll need to add getters to your class. (Could've sworn I tried that. Ah well.)
Velocity does not expose fields, only methods. There are ways to change that:
You can create your own Uberspect class that allows access to public fields.
You can wrap the instance with a modified version of Velocity's FieldMethodizer that gives access to non-static fields.
You can add and use an instance of a "tool" class to your context, such as a subclass of VelocityTool's ClassTool.
Right then, I've run into a situation using Unity that I don't know how to solve/approach...Here's my problem.
I'm developing a WPF application and I'm using MVVM (Prism Implimentation hence the Unity container). I have a ViewModel called MenuItemsViewModel (plural) which contains an IEnumerable of MenuItemViewModel (singular). In the constructor of the MenuItemsViewModel I'm populating this collection from a generator function like this...
yield return new MenuItemViewModel(eventAggregator)
{
Text = "Dashboard",
CommandText = "DASHBOARD"
};
yield return new MenuItemViewModel(eventAggregator)
{
Text = "Areas",
CommandText = "AREAS"
};
yield return new MenuItemViewModel(eventAggregator)
{
Text = "Users",
CommandText = "USERS"
}; //etc....
I don't really want to be doing this but rather relying on the container to construct these objects for me but how in Gods name do I go about that? I don't really want my Items ViewModel to have any knowledge of my Item ViewModel other than the interface it implements but I've got about 15 of these menu items, each with different property values.
I'm not completely new to DI/IoC but this is a big question for me. I see and have benefited from having my services injected but what do you do about concrete values?
Am I think totally in the wrong terms here? Should I be just resolving the concrete instance from the container and then setting the properties? That would be an option but I like my props to be readonly if possible.
I hope this is clear enough,..shout at me if not :-)
Any help is much appreciated.
I would use resolved arrays to inject menu items:
container
.RegisterInstance("DASHBOARD", new MenuItemViewModel(...))
.RegisterInstance("AREAS", new MenuItemViewModel(...))
.RegisterType<MenuItemsViewModel>(
new InjectionConstructor(new ResolvedArrayParameter<MenuItemViewModel>()))
I am having a weird issue in ASP.NET MVC with objects not being updated with UpdateModel when passed a formCollection. UpdateModel does not appear to be working properly when the object being updated is created through reflection.
Scenario: I have an application which has approximately 50 lookup tables--each of which includes exactly the same schema including typical fields like id, title, description, isactive, and createdon. Rather than build 50 views, I wanted to have a single view which could display the data from all of the lookup tables. I created an Interface called IReferenceEntity and implemented it in each of the POCOs representing my lookup tables.
Using this interface, I am able to easily populate a view with a record from the lookup table. (I pass the items to the view via the following.)
System.Web.Mvc.ViewPage<MyNamespece.IReferenceEntity>
From the database to the view, every thing works perfectly.
However, when I attempt to update the model on post, I am running into some problems.
If I explicitly declare an object reference like the following, every thing works perfectly and the values of my object are updated with the values from my form. Hence, I can then update the database.
AccountStatus a = new AccountStatus();
UpdateModel(a, formCollection.ToValueProvider());
Unfortunately, hard coding the object type would completely defeat the reason for using an interface.
(A primary objective of the application is to be able to dynamically add new tables such as lookup tables without having to do anything "special". This is accomplished by reflecting on the loaded assemblies and locating any classes which implement a specific interface or base class)
My strategy is to determine the concrete type of the object at postback and then create an instance of the type through reflection. (The mechanism I use to determine type is somewhat primitive. I include it as a hidden field within the form. Better ideas are welcome.)
When I create an instance of the object using reflection through any of the following methods, none of the objects are being updated by UpdateModel.
Type t = {Magically Determined Type}
object b = Activator.CreatorInstance(t);
UpdateModel(b, formCollection.ToValueProvider());
Type t = {Magically Determined Type}
var c = Activator.CreatorInstance(t);
UpdateModel(c, formCollection.ToValueProvider());
Type t = {Magically Determined Type}
IReferenceEntity d = Activator.CreatorInstance(t);
UpdateModel(d, formCollection.ToValueProvider());
Note: I have verified that the objects which are being created through relection are all of the proper type.
Does anyone have any idea why this might be happening? I am somewhat stumped.
If I was really "hard up", I could create factory object which would many instantiate any one of these reference entity/lookup objects. However, this would break the application's ability to allow for new lookup tables to be added and discovered transparently and is just not quite as clean.
Also, I could try deriving from an actual ReferenceEntity base class as opposed to an interface, but I am doubtful whether this would make any difference. The issue appears to be with using reflection created objects in the modelbinder.
Any help is appreciated.
Anthony
Augi answered this on ASP.NET forums. It worked with only a couple of minor modifications. Thank you Augi.
The problem is that [Try]UpdateModel methods allow to specify model type using generic parameter only so they don't allow dynamic model type specification. I have created issue ticket for this.
You can see TryModelUpdate method implementation here. So it's not difficult to write own overload:
public virtual bool TryUpdateModelDynamic<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties, IDictionary<string, ValueProviderResult> valueProvider) where TModel : class
{
if (model == null)
{
throw new ArgumentNullException("model");
}
if (valueProvider == null)
{
throw new ArgumentNullException("valueProvider");
}
//Predicate<string> propertyFilter = propertyName => BindAttribute.IsPropertyAllowed(propertyName, includeProperties, excludeProperties);
IModelBinder binder = Binders.GetBinder( /*typeof(TModel)*/model.GetType());
ModelBindingContext bindingContext = new ModelBindingContext()
{
Model = model,
ModelName = prefix,
ModelState = ModelState,
//ModelType = typeof(TModel), // old
ModelType = model.GetType(),
// new
//PropertyFilter = propertyFilter,
ValueProvider = valueProvider
};
binder.BindModel(ControllerContext, bindingContext);
return ModelState.IsValid;
}
Does your IReferenceEntity contain setters on the properties as well as getters? I would think that the last sample would work if the interface had property setters, though you'd have to cast it to get it to compile.
Type t = {Magically Determined Type}
IReferenceEntity d = Activator.CreatorInstance(t) as IReferenceEntity;
UpdateModel(d, formCollection.ToValueProvider());
Normally the reason that it won't set a property on a class is because it can't find a public setter method available to use via reflection.
Just a quick "another thing to try":
UpdateModel(d as IReferenceEntity, formCollection.ToValueProvider());
Not sure if that will work, and I haven't tried it myself, but it's the first thing that came to mind.
If I get a chance later I'll peek at the Default Model Binder code and see if there's anything in there that is obvious...
I know Grails has a map based constructor for domain objects, to which you can pass the params of a URL to and it will apply the appropriate field settings to the object using introspection, like this...
myDomainInstance = new MyObject(params)
I was wondering whether there was an equivalent method of taking the params and applying them to an existing object and updating values in the same way that the map constructor must work, something like...
myDomainInstance = params
or
myDomainInstance = fromParams(params)
Am I just wishful thinking or does such a thing exist? I can code it up myself but would rather not if it exists already.
Thanks
Adapted from the grails user guide:
obj = MyObject.get(1)
obj.properties = params
Check out the documentation for 'params' under the controller section for more information.
It really depends on what you are trying to do but an equivalent approach use databinding.
def sc = new SaveCommand()
bindData(sc, params)
This give you the benefit of using custom binding. If let say your date format is not the default one you can redefine it through a bean like this:
public class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), true));
}
}
In my ASP MVC application I'm using standard SQL (rather that Linq to SQL or other ORM) to query my database.
I would like to pass the database results to my view and iterate over the results in my view. But I'm not sure how to do this. Every example I've seen passes some string or uses L2S. I would like to pass something like nested Hashtables, but the only thing I can think of is to pass an SqlDataReader object to the view, but this sounds like a really bad idea.
How would I go about displaying my database results from a standard SQL query to my view? I would really like use Linq or other ORM, but requirements dictate we don't (don't ask me why, I don't understand). I'm doing this in VB. I'll try by best to convert any C# examples provided.
You could create simple classes for the data you want to transfer and then populate a List of objects in your controller from a data reader manually, and then pass this to your View - e.g. (C# but this should be easy to convert)
// open your connection / datareader etc.
List<Customer> customers = new List<Customer>();
while(dataReader.Read())
{
Customer c = new Customer();
c.Id = dataReader.GetInt32(0);
c.Name = dataReader.GetString(1);
// etc (you might want to use string indexers instead of ints for the get methods)
customers.Add(c);
}
// close and dispose your datareader / connection etc as usual
return View("List", customers);
MVC is about separation of concerns. Passing SqlDataReaders, DataTables, or whatever class that resides in the System.Data namespace to a view is not a good idea. You need to define a model which might talk to the database, and a controller which will pass this model to the view. If your company policy says don't use an ORM then maybe classic WebForms are better suited to your scenario than the MVC pattern.
I agree with Rashack. This article explains it in some detail.link text
In a nutshell, here's how to do it using DataTable and DataReader:
private DataTable GetData()
{
DataTable dt = new DataTable();
using (SqlConnection connection
= new SqlConnection("ConnectionString"))
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandText = "SELECT * FROM Customers";
connection.Open();
using (SqlDataReader reader =
command.ExecuteReader
(CommandBehavior.CloseConnection))
{
dt.Load(reader);
}
}
return dt;
}
Then, you can read that DataTable into an entity object that you pass around.
I think you'll find this can yield much better performance than using Linq or an ORM.
Try using DataTables - DataTable can load data from IDataReader... (I think the method's called Load)
You could create your own Data Transfer Object classes and populate instances of them using ADO.Net code. These DTO classes would be simple POCO-style classes that just contained property get/set accessors, no methods. Using POCO objects is arguably preferable to DataSets/DataTables as they are lightweight (no superfluous state) and are more intuitive to work with from an object-oriented perspective.