SimpleComboBox in GXT - gxt

How to use key/value pair using SimpleComboBox in GXT. I'm able to add a key to SimpleComboBox but how to add value of a particular key to a SimpleComboBox?
Later I want to retrieve value of key.
Thanks & Regards,
Anand

The simple way to have key/value in a SimpleComboBox is to use a ListStore with type BaseModel. BaseModel allows you to save data as key/value like following:
SimpleComboBox combo = new SimpleComboBox();
ListStore<BaseModel> store = new ListStore<BaseModel>();
combo.setStore(store);
combo.setDisplayField("name");
// complete the SimpleComboBox properties here.
// Now, we will create data sample for the answer
BaseModel model = new BaseModel();
model.set("id", 1);
model.set("name", "Java");
store.add(model);
BaseModel model = new BaseModel();
model.set("id", 2);
model.set("name", "PHP");
store.add(model);
as you can see from the code snippet, BaseModel stores data as key/value pairs, so you can easily get the selected element from the SimpleComboBox like:
BaseModel selectedModel = (BaseModel) combo.getValue();
String techName = selectedModel.get("name"); // return value of key name

// MySimpleComboBox extends SimpleComboBox
public MySimpleComboBox(){
super(new ListStore<Person>(new ModelKeyProvider<Person>() {
#Override
public String getKey(Person item) {
return item.id();
}
}), new LabelProvider<Person>() {
#Override
public String getLabel(Person item) {
return item.toString();
}
});
}
I did that once I think it is what your looking for (or what you were looking for).

Related

Using Object Initializers dynamically

I need to pass a list of integers to a stored procedure because Entity Framework takes too long to process the request. I'm using a User Defined Table Type to do this. I'm using EntityFrameworkExtras.EF6 and I've created a stored procedure and Table Type class to help with this. Here are those classes:
namespace MyModel{
using EntityFrameworkExtras.EF6;
[UserDefinedTableType("SelectedActivity")]
public class ChartCountryUDT
{
[UserDefinedTableTypeColumn(1)]
public int ID { get; set; }
}
[StoredProcedure("GetCountryChartData")]
public class ChartCountryStoredProcedure
{
[StoredProcedureParameter(System.Data.SqlDbType.Udt, ParameterName = "ActivityIDs")]
public List<ChartCountryUDT> ChartCountryUDT { get; set; }
}}
and here is my method to call the stored procedure passing in the Table Type and returning me a List of objects:
public List<ChartCountry> GetCountriesForChart(List<int> activityIDs)
{
using (MyEntities ctx = new MyEntities())
{
var procedure = new ChartCountryStoredProcedure()
{
ChartCountryUDT = new List<ChartCountryUDT>()
{
new ChartCountryUDT() {ID = 1 }
}
};
return (List<ChartCountry>)ctx.Database.ExecuteStoredProcedure<ChartCountry>(procedure);
}
}
As you can see in my ChartCountryUDT object initializer, I'm hardcoding one object by setting the ID value to 1. This works fine but I would like to take the activityIDs parameter that is passed in and create new objects in my object initializer for each ID in the activityIDs parameter. Is there any way of looping trough my list of activityIDs and creating new objects in my object initializer for each record?
Thanks
You are basically asking how to map (convert) List<int> to List<ChartCountryUDT>, which in LINQ is called projection (select):
var procedure = new ChartCountryStoredProcedure()
{
ChartCountryUDT = activityIDs.Select(id => new ChartCountryUDT { ID = id }).ToList()
};

Check duplicate key in Hashtable before adding a key

I have a Hashtable and I want to put check whether the Hashtable has key or not before adding a key in Hashtable. As adding a duplicate key in Hashtable throwing exception.
Basically I want to override Hashtable's virtual 'Add' method and put a check in it. I dont know how can I override Add method.
Please help me to write override method.
You can use ContainsKey.
Another way is to use the Item indexer-property which adds new keys and updates existing.
var ht = new System.Collections.Hashtable();
ht["test"] = "foo"; // added
ht["test"] = "bah"; // updated
However, you should consider to replace your old and redundant Hashtable with a generic Dictionary<Tkey, Tval>. Why?
The Add method of the Hashtable class is overridable. So try this:
class MyHashTable : Hashtable
{
public override void Add(object key, object value)
{
try
{
base.Add(key, value);
}
catch
{
// whatever
}
}
}

Javafx PropertyValueFactory not populating Tableview

This has baffled me for a while now and I cannot seem to get the grasp of it. I'm using Cell Value Factory to populate a simple one column table and it does not populate in the table.
It does and I click the rows that are populated but I do not see any values in them- in this case String values. [I just edited this to make it clearer]
I have a different project under which it works under the same kind of data model. What am I doing wrong?
Here's the code. The commented code at the end seems to work though. I've checked to see if the usual mistakes- creating a new column instance or a new tableview instance, are there. Nothing. Please help!
//Simple Data Model
Stock.java
public class Stock {
private SimpleStringProperty stockTicker;
public Stock(String stockTicker) {
this.stockTicker = new SimpleStringProperty(stockTicker);
}
public String getstockTicker() {
return stockTicker.get();
}
public void setstockTicker(String stockticker) {
stockTicker.set(stockticker);
}
}
//Controller class
MainGuiController.java
private ObservableList<Stock> data;
#FXML
private TableView<Stock> stockTableView;// = new TableView<>(data);
#FXML
private TableColumn<Stock, String> tickerCol;
private void setTickersToCol() {
try {
Statement stmt = conn.createStatement();//conn is defined and works
ResultSet rsltset = stmt.executeQuery("SELECT ticker FROM tickerlist order by ticker");
data = FXCollections.observableArrayList();
Stock stockInstance;
while (rsltset.next()) {
stockInstance = new Stock(rsltset.getString(1).toUpperCase());
data.add(stockInstance);
}
} catch (SQLException ex) {
Logger.getLogger(WriteToFile.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Connection Failed! Check output console");
}
tickerCol.setCellValueFactory(new PropertyValueFactory<Stock,String>("stockTicker"));
stockTableView.setItems(data);
}
/*THIS, ON THE OTHER HAND, WORKS*/
/*Callback<CellDataFeatures<Stock, String>, ObservableValue<String>> cellDataFeat =
new Callback<CellDataFeatures<Stock, String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(CellDataFeatures<Stock, String> p) {
return new SimpleStringProperty(p.getValue().getstockTicker());
}
};*/
Suggested solution (use a Lambda, not a PropertyValueFactory)
Instead of:
aColumn.setCellValueFactory(new PropertyValueFactory<Appointment,LocalDate>("date"));
Write:
aColumn.setCellValueFactory(cellData -> cellData.getValue().dateProperty());
For more information, see this answer:
Java: setCellValuefactory; Lambda vs. PropertyValueFactory; advantages/disadvantages
Solution using PropertyValueFactory
The lambda solution outlined above is preferred, but if you wish to use PropertyValueFactory, this alternate solution provides information on that.
How to Fix It
The case of your getter and setter methods are wrong.
getstockTicker should be getStockTicker
setstockTicker should be setStockTicker
Some Background Information
Your PropertyValueFactory remains the same with:
new PropertyValueFactory<Stock,String>("stockTicker")
The naming convention will seem more obvious when you also add a property accessor to your Stock class:
public class Stock {
private SimpleStringProperty stockTicker;
public Stock(String stockTicker) {
this.stockTicker = new SimpleStringProperty(stockTicker);
}
public String getStockTicker() {
return stockTicker.get();
}
public void setStockTicker(String stockticker) {
stockTicker.set(stockticker);
}
public StringProperty stockTickerProperty() {
return stockTicker;
}
}
The PropertyValueFactory uses reflection to find the relevant accessors (these should be public). First, it will try to use the stockTickerProperty accessor and, if that is not present fall back to getters and setters. Providing a property accessor is recommended as then you will automatically enable your table to observe the property in the underlying model, dynamically updating its data as the underlying model changes.
put the Getter and Setter method in you data class for all the elements.

Model-Identifier for Node in JavaFX 2 TreeItem

Is there a way to store an identifier of a model object or the model object itself in a JavaFX 2 TreeItem<String>? There is just Value to store the text...
I'm populating a TreeView from a list of model objects, and need to find it when the user clicks a node. I'm used to work with Value and Text in .NET Windows Forms or HTML and I am afraid I cannot adapt this way of thinking to JavaFX...
You can use any objects with TreeView, they just have to override toString() for presenting or extend javafx.scene.Node
E.g. for next class:
private static class MyObject {
private final String value;
public MyObject(String st) { value = st; }
public String toString() { return "MyObject{" + "value=" + value + '}'; }
}
TreeView should be created next way:
TreeView<MyObject> treeView = new TreeView<MyObject>();
TreeItem<MyObject> treeRoot = new TreeItem<MyObject>(new MyObject("Root node"));
treeView.setRoot(treeRoot);
I have the same issue as the OP. In addition I want to bind the value displayed in the TreeItem to a property of the object. This isn't complete, but I'm experimenting with the following helper class, where I'm passing in the "user object" (or item) to be referenced in the TreeItem, and a valueProperty (which, in my case, is a property of the item) to be bound to the TreeItem.value.
final class BoundTreeItem<B, T> extends TreeItem<T> {
public BoundTreeItem(B item, Property<T> valueProperty) {
this(item, valueProperty, null);
}
public BoundTreeItem(B item, Property<T> valueProperty, Node graphic) {
super(null, graphic);
itemProperty.set(item);
this.valueProperty().bindBidirectional(valueProperty);
}
public ObjectProperty<B> itemProperty() {
return itemProperty;
}
public B getItem() {
return itemProperty.get();
}
private ObjectProperty<B> itemProperty = new SimpleObjectProperty<>();
}

'Unexpected element: XX' during deserialization MongoDB C#

I'm trying to persist an object into a MongoDB, using the following bit of code:
public class myClass
{
public string Heading { get; set; }
public string Body { get; set; }
}
static void Main(string[] args)
{
var mongo = MongoServer.Create();
var db = mongo.GetDatabase("myDb");
var col = db.GetCollection<BsonDocument>("myCollection");
var myinstance = new myClass();
col.Insert(myinstance);
var query = Query.And(Query.EQ("_id", new ObjectId("4df06c23f0e7e51f087611f7)));
var res = col.Find(query);
foreach (var doc in res)
{
var obj = BsonSerializer.Deserialize<myClass>(doc);
}
}
However I get the following exception 'Unexpected element: _id' when trying to Deserialize the document.
So do I need to Deserialize in another way?? What is the preferred way of doing this?
TIA
Søren
You are searching for a given document using an ObjectId but when you save an instance of MyClass you aren't providing an Id property so the driver will create one for you (you can make any property the id by adding the [BsonId] attribute to it), when you retrieve that document you don't have an Id so you get the deserialization error.
You can add the BsonIgnorExtraElements attribute to the class as Chris said, but you should really add an Id property of type ObjectId to your class, you obviously need the Id (as you are using it in your query). As the _id property is reserved for the primary key, you are only ever going to retrieve a single document so you would be better off writing your query like this:
col.FindOneById(new ObjectId("4df06c23f0e7e51f087611f7"));
The fact that you are deserializing to an instance of MyClass once you retrieve the document lends itself to strongly typing the collection, so where you create an instance of the collection you can do this
var col = db.GetCollection<MyClass>("myCollection");
so that when you retrieve the document using the FindOneById method the driver will take care of the deserialization for you putting it all together (provided you add the Id property to the class) you could write
var col = db.GetCollection<MyClass>("myCollection");
MyClass myClass = col.FindOneById(new ObjectId("4df06c23f0e7e51f087611f7"));
One final thing to note, as the _id property is created for you on save by the driver, if you were to leave it off your MyClass instance, every time you saved that document you would get a new Id and hence a new document, so if you saved it n times you would have n documents, which probably isn't what you want.
A slight variation of Projapati's answer. First Mongo will deserialize the id value happily to a property named Id which is more chsarp-ish. But you don't necessarily need to do this if you are just retrieving data.
You can add [BsonIgnoreExtraElements] to your class and it should work. This will allow you to return a subset of the data, great for queries and view-models.
Try adding _id to your class.
This usually happens when your class doesn't have members for all fields in your document.
public class myClass
{
public ObjectId _id { get; set; }
public string Heading { get; set; }
public string Body { get; set; }
}

Resources