What approach is good for US State ListBox/DropDownList - object

What is the best approach to bind US State in WPF (in ListBox or in DropDownList)? Should I use DataTable to bind this data? Is binding DataTable to WPF object right programming approach? Or Should I use class/object. I mean get data from database and convert it to Generic Object List and then bind this list to WPF object?
Thanks,

public class States
{
private string name;
public string Name
{
get
{
return name;
}
}
private string id;
public string Id
{
get
{
return id;
}
}
}
List<States> states = new List<States>();
//get from database
foreach( states DataSource)
{
name = "Alabama";
id = "1";
}
// next Cache list of states for better performance
Many ways...
One approach is to use a list class. get from data source, next cache for better performance.

Related

Are POCO objects just "persistent ignorant" or something more?

RPM1984 in this question speaks about POCO are "persistent ignorant" objects. But he doen´t speak about how much logic can hold. For example:
class Person {
public string FirstName { get; set; }
}
Or this:
class Person {
private string firstName = string.Empty;
public string Firstname {
get
{
return this.firstname;
}
set {
if (value.Length > 26)
{
throw new System.ComponentModel.DataAnnotations.ValidationException("Firstname is too long");
}
this.firstname = value;
}
}
}
Both are "persistent igonrant". The first one is for sure a POCO class. But is it the second a valid POCO? It has some logic but it could be persisted without problem and its logic is not more than a validation. Can it be considered POCO?
Thanks
Yes, the second one is a valid POCO, because it doesn't use a persistence specific detail. The whole point of POCOs is to say that a certain object doesn't depend on a db access library. If, for example, you would decorate Person with an EF specific attribute then, you would have to reference EF everywhere you'd use that class.

Object creation events in ServiceStack's OrmLite

I need to set an event handler on objects that get instantiated by OrmLite, and can't figure out a good way to do it short of visiting every Get method in a repo (which obviously is not a good way).
To give some background - say I have a class User, which is pulled from database; it also implements INotifyPropertyChanged. I want to assign a handler to that event. Having it auto-populated from Funq would be ideal, but of course OrmLite doesn't ask Funq to hydrate the new object.
So I'm stuck.
Any hints in a right direction would be appreciated.
It sounds to me like you're mixing in presentation logic with your data access logic. If I was in your position I would not attempt to implement INotifyPropertyChanged on a model (such as your User class). Instead I would create a ViewModel and place the databinding logic there (MVVM Style).
Having INotifyPropertyChanged on the data model is not quite logical when you get down to it. If I were to update the database record it would not fire this event for example (but the property has changed). It makes a lot more sense on a ViewModel.
Beyond solving your original issue it also makes building complex screens a lot easier by letting you aggregate, compose, and filter data for display purposes. If you need to pull in information from your database, a RSS feed, a stock ticker web API, and twitter you can do so in your ViewModel.
public class User
{
[AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
}
public class UserViewModel : INotifyPropertyChanged
{
private string _name;
public UserViewModel(User user)
{
_name = user.Name;
}
public string Name
{
get { return _name; }
set {
if (value == _name) return;
_name = value;
OnPropertyChanged("Name");
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Small Note: This answer was written in the context of display data on a screen with a ViewModel, however, the same concept applies to observing model changes for any purpose.

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.

Add behavior to existing implementation - C# / Design Pattern

My current implementation for service and business layer is straight forward as below.
public class MyEntity { }
// Business layer
public interface IBusiness { IList<MyEntity> GetEntities(); }
public class MyBusinessOne : IBusiness
{
public IList<MyEntity> GetEntities()
{
return new List<MyEntity>();
}
}
//factory
public static class Factory
{
public static T Create<T>() where T : class
{
return new MyBusinessOne() as T; // returns instance based on T
}
}
//Service layer
public class MyService
{
public IList<MyEntity> GetEntities()
{
return Factory.Create<IBusiness>().GetEntities();
}
}
We needed some changes in current implementation. Reason being data grew over the time and service & client cannot handle the volume of data. we needed to implement pagination to the current service. We also expect some more features (like return fault when data is more that threshold, apply filters etc), so the design needs to be updated.
Following is my new proposal.
public interface IBusiness
{
IList<MyEntity> GetEntities();
}
public interface IBehavior
{
IEnumerable<T> Apply<T>(IEnumerable<T> data);
}
public abstract class MyBusiness
{
protected List<IBehavior> Behaviors = new List<IBehavior>();
public void AddBehavior(IBehavior behavior)
{
Behaviors.Add(behavior);
}
}
public class PaginationBehavior : IBehavior
{
public int PageSize = 10;
public int PageNumber = 2;
public IEnumerable<T> Apply<T>(IEnumerable<T> data)
{
//apply behavior here
return data
.Skip(PageNumber * PageSize)
.Take(PageSize);
}
}
public class MyEntity { }
public class MyBusinessOne : MyBusiness, IBusiness
{
public IList<MyEntity> GetEntities()
{
IEnumerable<MyEntity> result = new List<MyEntity>();
this.Behaviors.ForEach(rs =>
{
result = rs.Apply<MyEntity>(result);
});
return result.ToList();
}
}
public static class Factory
{
public static T Create<T>(List<IBehavior> behaviors) where T : class
{
// returns instance based on T
var instance = new MyBusinessOne();
behaviors.ForEach(rs => instance.AddBehavior(rs));
return instance as T;
}
}
public class MyService
{
public IList<MyEntity> GetEntities(int currentPage)
{
List<IBehavior> behaviors = new List<IBehavior>() {
new PaginationBehavior() { PageNumber = currentPage, }
};
return Factory.Create<IBusiness>(behaviors).GetEntities();
}
}
Experts please suggest me if my implementation is correct or I am over killing it. If it correct what design pattern it is - Decorator or Visitor.
Also my service returns JSON string. How can I use this behavior collections to serialize only selected properties rather than entire entity. List of properties comes from user as request. (Kind of column picker)
Looks like I don't have enough points to comment on your question. So, I am gonna make some assumption as I am not a C# expert.
Assumption 1: Looks like you are getting the data first and then applying the pagination using behavior object. If so, this is a wrong approach. Lets say there are 500 records and you are showing 50 records per fetch. Instead of simply fetching 50 records from DB, you are fetching 500 records for 10 times and on top of it you are adding a costly filter. DB is better equipped to do this job that C# or Java.
I would not consider pagination as a behavior with respect to the service. Its the behavior of the presentation layer. Your service should only worry about 'Data Granularity'. Looks like one of your customer wants all the data in one go and others might want a subset of that data.
Option 1: In DAO layer, have two methods: one for pagination and other for regular fetch. Based on the incoming params decide which method to call.
Option 2: Create two methods at service level. One for a small subset of data and the other for the whole set of data. Since you said JSON, this should be Restful service. Then based on the incoming URL, properly call the correct method. If you use Jersey, this should be easy.
In a service, new behaviors can be added by simply exposing new methods or adding new params to existing methods/functionalities (just make sure those changes are backward compatible). We really don't need Decorator or Visitor pattern. The only concern is no existing user should be affected.

Managed Beans and TabContainer

I ask this squestion on behalf of one of my developers. Haven't looked into details myself.
Assume you have a simple managed bean (=contact) This bean has a method to get the contacts firstName.
I can open an xpage and bind the bean to a computedText Field #{contact.firstName}
In our application we use a tabContainer to have multiple documents of the same type ( contact ) open.
How do I have to use my bean in the container?
faces-config.xml:
<managed-bean>
<managed-bean-name>person</managed-bean-name>
<managed-bean-class>com.package.Person</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
Java Bean Class:
public class Person implements Serializable {
private String strDocumentID;
private Document docData;
private String strFirstName;
private String strLastName;
private static final long serialVersionUID = 2934723410254681213L;
public Person() {
//setting the DocumentUniqueID of the current in a tab opened document
//attention: there could be more than one open tab, all with different documents
//and even different document types; and it is possible to switch back and forth between tabs
//DocumentId = ???;
//Setting the values from the stored document to the object
//setValues();
}
private void setValues() {
try {
Session session=NotesContext.getCurrent().getCurrentSession();
Database currdb=session.getCurrentDatabase();
docData=currdb.getDocumentByUNID(DocumentId);
setStrFirstName(docData.getItemValueString("FirstName"));
setStrLastName(docData.getItemValueString("LastName"));
} catch (NotesException e) {
throw new FacesException("Could not open document for documentId "+ DocumentId, e);
}
}
public Document getDataDocument() {
return docData;
}
public void setDataDocument(Document docData) {
this.docData = docData;
}
public String getDocumentId() {
return DocumentId;
}
public void setDocumentId(String documentId) {
DocumentId = documentId;
}
public String getStrFirstName() {
return strFirstName;
}
public void setStrFirstName(String strFirstName) {
this.strFirstName = strFirstName;
}
public String getStrLastName() {
return strLastName;
}
public void setStrLastName(String strLastName) {
this.strLastName = strLastName;
}
}
Custom Control with computed field:
person.strFirstName
So, the problem is the constructor of the Person Class. It needs to get the "link" to the opened document when the document is opened in a tab and everytime when switched back to this tab. And this without the use of any Data source, because this is what should be done by the managed bean itself.
So, hope that helped to get a little bit more understanding of the problem.
If not, please ask again.
My advice:
make another meta bean implementing map interface. Alter its getter to instantiate and return your data bean. Binding may be then:
meta[someparamwithunid].field
And save would be:
meta[someparamwithunid].setValues()
Like this:
public class People implments java.util.Map {
Map<String,Person> people = new HashMap<String,Person>();
public Person get(String unid) {
if people.keySet().contains(unid) {
return people.get(unid)
} else {
// make instance and store it in people map, return it
}
// implement other methods
}
With view scope I think there is no problem with concurrency.
Frantisek points into the right direction. Your request bean would not be a person bean, but a people bean. You then can use an expression like
#{people[index].name}
to refer to a specific person. People would be the managed bean and the index could either be the UNID or the tab number. I find the later one easier to implement. you need to have a loadPerson(index) = UNID function to load an existing person. More information on the use of Expression language can be found here:
Sun Oracle JSF documentation or in some Course materials.
Hope that helps.
I'm not sure if this bean will work in the requestScope because you have probably a lot of partial refreshes with the tabcontainer (maybe try change it to a higher level scope).

Resources