I created a parser that reads files formatted in the following way:
version="v4.5.32"
name="Test File"
date="2513.04.02"
players=
{
{
first_name="John"
last_name="Smith"
country=12
id=0
}
{
first_name="Mario"
last_name="Rossi"
country=56
id=1
}
}
next_player_id=2
matches=
{
22 47 88 1045 1048 3511
}
settings=
{
match_prefix="game"
match_reward_scalar=1,55
match_sets_points=
{
0,5 0,75 1,0
}
next_event_id=56
next_event_fired=false
next_event_probability=0,33
}
...
Basically, those files contain a list of key/value pairs in which keys are always a string and values can be either a simple value (boolean, date, float, integer, string), a record (a sublist of key/value pairs like settings) or an array (composed by simple values like matches or records like players). In order to parse and handle those values I created 3 simple classes.
1) MyPair
public sealed class MyPair
{
public MyKey Key { get; }
public MyValue Value { get; }
public MyPair(MyKey key, MyValue value) { ... }
public override String ToString()
{
return String.Concat(Key, " = ", Value);
}
}
2) MyKey
public sealed class MyKey
{
public String Name { get; }
... // other properties set by checking the name in the constructor
public Key(String name) { ... }
public override String ToString()
{
return Name;
}
}
3) MyValue
public sealed class MyValue
{
private readonly dynamic m_UnderlyingValue;
private readonly MyValueCategory m_Category;
public dynamic UnderlyingValue
{
get { return m_UnderlyingValue; }
}
public Boolean Container
{
get { return ((m_Category == ValueCategory.Array) || (m_Category == ValueCategory.Record)); }
}
public MyValueCategory Category
{
get { return m_Category; }
}
public MyValue(DateTime underlyingValue)
{
if (underlyingValue == null)
throw new ArgumentNullException("underlyingValue");
m_UnderlyingValue = underlyingValue;
m_Category = MyValueCategory.DateTime;
}
public MyValue(Boolean underlyingValue) { ... }
public MyValue(Double underlyingValue) { ... }
public MyValue(Int64 underlyingValue) { ... }
public MyValue(MyPair[] underlyingValue) { ... }
public MyValue(MyValue[] underlyingValue) { ... }
public MyValue(String underlyingValue) { ... }
public override String ToString()
{
switch (m_Category)
{
case MyValueCategory.Array:
return String.Concat("Array[", m_UnderlyingValue.Length, "]");
case MyValueCategory.Boolean:
return String.Concat("Boolean[", (m_UnderlyingValue ? "true" : "false"), "]");
case MyValueCategory.DateTime:
return String.Concat("DateTime[", m_UnderlyingValue.ToString("yyyy.MM.dd", CultureInfo.InvariantCulture), "]");
case MyValueCategory.Float:
return String.Concat("Float[", m_UnderlyingValue.ToString("F3", CultureInfo.InvariantCulture), "]");
case MyValueCategory.Integer:
return String.Concat("Integer[", m_UnderlyingValue.ToString("F0", CultureInfo.InvariantCulture), "]");
case MyValueCategory.Record:
return String.Concat("Record[", m_UnderlyingValue.Length, "]");
default:
return String.Concat("Text[", m_UnderlyingValue, "]");
}
}
}
public enum MyValueCategory
{
Array,
Boolean,
DateTime,
Float,
Integer,
Record,
Text
}
The parsing process works like a charm and returns me a MyValue instance that works like a container / root node for everything I parsed.
I'm not using WPF forms, just plain Winforms. I would like to populate a TreeView control hierarchically with the parsed data and then make that data responsive to the changes made to the TreeView nodes. I really can't figure out how to bind data to the control itself and allow a mirrored manipulation.
Any suggestion please?
You can populate your TreeView recursively with this code:
protected override void OnLoad( EventArgs e )
{
base.OnLoad( e );
MyValue root = new MyParser().Parse( "MyFilename.own" );
Populate( treeView1.Nodes, root.UnderlyingValue );
}
protected void Populate( TreeNodeCollection nodes, IList list )
{
if( list is MyPair[] )
{
foreach( MyPair pair in list )
{
TreeNode node = new TreeNode();
node.Text = pair.ToString();
node.Tag = pair;
nodes.Add( node );
if( pair.Value.Container )
Populate( node.Nodes, (IList)pair.Value.UnderlyingValue );
}
}
if( list is MyValue[] )
{
foreach( MyValue value in list )
{
TreeNode node = new TreeNode();
node.Text = value.ToString();
node.Tag = value;
nodes.Add( node );
if( value.Container )
Populate( node.Nodes, (IList)value.UnderlyingValue );
}
}
}
Result looks then like that:
As #Reza Aghaei already mentioned it is not possible to do this via data-binding. You have to maintain your lists manually after adding/removing a node. Setting node.Tag to the corresponding pair or value makes it easy for you to find and modify them.
Related
I am using a #BeanParam like this:
#GET
public Response listAllPaged(#BeanParam PagedRequest pagedRequest) {
// Do stuff...
}
The bean itself:
public class PagedRequest {
#QueryParam("sortOrder")
#DefaultValue("0")
public int sortOrder;
}
Now I would like to change the type of sortOrder to the following enum:
public enum SortOrder {
ASC("asc"),
DESC("desc");
public final String sortOrder;
SortOrder(String sortOrder) {
this.sortOrder = sortOrder;
}
}
But as soon as I do this:
public class PagedRequest {
#QueryParam("sortOrder")
#DefaultValue("asc")
public SortOrder sortOrder;
}
My REST Endpoint cannot match the signature anymore and returns a 404. Why is that? I thought that the presence of a constructor accepting a single String should allow JAX-RS to do the conversion.
What am I doing wrong?
UPDATE
I managed to make it work like this, but it does not really answer my initial question...
public enum SortOrder {
ASC,
DESC;
public static SortOrder fromString(String param) {
String toUpper = param.toUpperCase();
try {
return valueOf(toUpper);
} catch (Exception e) {
return null;
}
}
}
The Enum.valueOf(String) method is used to resolve the value. Since your SorterOrder enums are uppercase you'd be required to send the parameter in uppercase.
If you want to pass the value in lowercase only you could change the enum names to lower case, e.g. SortOrder.asc.
If you don't know or don't want to care about the case the parameter is sent in you could use a ParamConverter.
public class SortOrderParamConverter implements ParamConverter<SortOrder> {
#Override
public SortOrder fromString(final String value) {
if (value != null) {
return SortOrder.valueOf(value.toUpperCase(Locale.ROOT));
}
return SortOrder.ASC;
}
#Override
public String toString(final SortOrder value) {
return value.name();
}
}
If you want a more generic approach you could create a ParamConverter or all enums.
#Provider
public class EnumParamConverterProvider implements ParamConverterProvider {
#Override
public <T> ParamConverter<T> getConverter(final Class<T> rawType, final Type genericType,
final Annotation[] annotations) {
if (!rawType.isEnum()) {
return null;
}
final Enum<?>[] constants = (Enum<?>[]) rawType.getEnumConstants();
return new ParamConverter<T>() {
#Override
#SuppressWarnings("unchecked")
public T fromString(final String value) {
if (value == null || value.isEmpty()) {
return null;
}
for (Enum<?> e : constants) {
if (e.name().equalsIgnoreCase(value)) {
return (T) e;
}
}
// No match, check toString()
for (Enum<?> e : constants) {
if (e.toString().equalsIgnoreCase(value)) {
return (T) e;
}
}
return null;
}
#Override
public String toString(final T value) {
return value != null ? value.toString() : null;
}
};
}
}
I am trying to get list of Tbcompany table using Transformers.aliasToBean with 2 primary key fields.
I am using SQL SERVER and Hibernate 3.2.4.
My table has 2 primary fields.
Tbcompany.class
public class Tbcompany {
private TbcompanyId id;
private String hcompanycode;
public TbcompanyId getId() {
return id;
}
public void setId(TbcompanyId id) {
this.id = id;
}
public String getHcompanycode() {
return hcompanycode;
}
public void setHcompanycode(String hcompanycode) {
this.hcompanycode = hcompanycode;
}
}
And inside TbcompanyId.class :
public class TbcompanyId
implements Serializable
{
private String companycode;
private String companyname;
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof TbcompanyId)) {
return false;
}
TbcompanyId other = ((TbcompanyId) o);
if (this.companycode == null) {
if (other.companycode!= null) {
return false;
}
} else {
if (!this.companycode.equals(other.companycode)) {
return false;
}
}
if (this.companyname == null) {
if (other.companyname!= null) {
return false;
}
} else {
if (!this.companyname.equals(other.companyname)) {
return false;
}
}
return true;
}
public int hashCode() {
int rtn = 17;
rtn = (rtn* 37);
if (this.companycode!= null) {
rtn = (rtn + this.companycode.hashCode());
}
rtn = (rtn* 37);
if (this.companyname!= null) {
rtn = (rtn + this.companyname.hashCode());
}
return rtn;
}
public String getCompanycode() {
return companycode;
}
public void setCompanycode(String companycode) {
this.companycode = companycode;
}
public String getCompanyname() {
return companyname;
}
public void setCompanyname(String companyname) {
this.companyname = companyname;
}
I want to create a form and use Transformers.aliasToBean to populate the form .
This query :
Query q;
q = session.createQuery("SELECT a.id.companycode as companycode,a.id.companyname as companyname,a.hcompanycode as hcompanycode FROM Tbcompany a");
q.setResultTransformer(Transformers.aliasToBean(Tbcompany.class));
list = q.list();
gives me an error of :
org.hibernate.PropertyNotFoundException: Could not find setter for companycode on class com.loansdb.data.Tbcompany
While this query :
Query q;
q = session.createQuery("SELECT a.id.companycode,a.id.companyname,a.hcompanycode as hcompanycode FROM
Tbcompany a");
q.setResultTransformer(Transformers.aliasToBean(Tbcompany.class));
list = q.list();
gives me this error :
org.hibernate.PropertyNotFoundException: Could not find setter for 0 on class com.loansdb.data.Tbcompany
Does anyone know how to do this?
The aliasToBean transformer use the name of the SQL columns returned and try to find a field with the same name on the class target that have a set method created.
So, your query returns a a.id.companycode:
SELECT a.id.companycode as companycode,a.id.companyname as companyname,a.hcompanycode as hcompanycode FROM Tbcompany a
The error said:
org.hibernate.PropertyNotFoundException: Could not find setter for companycode on class com.loansdb.data.Tbcompany
And your Tbcompany class does not have a setter to companycode.
So, to correct your Tbcompany class and looking your query, seems to me that the class it's something like:
public class Tbcompany {
private String companycode;
private String companycode;
private String companyname;
public String setCompanycode(String companycode) {
this.companycode = companycode;
}
// create the constructor, getters and setters
}
I have a combobox which shows list of User objects. I have coded a custom cell factory for the combobox:
#FXML ComboBox<User> cmbUserIds;
cmbUserIds.setCellFactory(new Callback<ListView<User>,ListCell<User>>(){
#Override
public ListCell<User> call(ListView<User> l){
return new ListCell<User>(){
#Override
protected void updateItem(Useritem, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setGraphic(null);
} else {
setText(item.getId()+" "+item.getName());
}
}
} ;
}
});
ListView is showing a string(id+name), but when I select an item from listview, Combobox is showing toString() method return value i.e address of object.
I can't override toString() method, because the User domain object should be same as the one at server.
How to display id in combobox? Please suggest
EDIT1
I tried below code. Now combo box shows id when I select a value from the listview.
cmbUserIds.setConverter(new StringConverter<User>() {
#Override
public String toString(User user) {
if (user== null){
return null;
} else {
return user.getId();
}
}
#Override
public User fromString(String id) {
return null;
}
});
The selected value in combo box is cleared when control focus is lost. How to fix this?
EDIT2:
#FXML AnchorPane root;
#FXML ComboBox<UserDTO> cmbUsers;
List<UserDTO> users;
public class GateInController implements Initializable {
#Override
public void initialize(URL location, ResourceBundle resources) {
users = UserService.getListOfUsers();
cmbUsers.setItems(FXCollections.observableList(users));
cmbUsers.getSelectionModel().selectFirst();
// list of values showed in combo box drop down
cmbUsers.setCellFactory(new Callback<ListView<UserDTO>,ListCell<UserDTO>>(){
#Override
public ListCell<UserDTO> call(ListView<UserDTO> l){
return new ListCell<UserDTO>(){
#Override
protected void updateItem(UserDTO item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setGraphic(null);
} else {
setText(item.getUserId()+" "+item.getUserNm());
}
}
} ;
}
});
//selected value showed in combo box
cmbUsers.setConverter(new StringConverter<UserDTO>() {
#Override
public String toString(UserDTO user) {
if (user == null){
return null;
} else {
return user.getUserId();
}
}
#Override
public UserDTO fromString(String userId) {
return null;
}
});
}
}
Just create and set a CallBack like follows:
#FXML ComboBox<User> cmbUserIds;
Callback<ListView<User>, ListCell<User>> cellFactory = new Callback<ListView<User>, ListCell<User>>() {
#Override
public ListCell<User> call(ListView<User> l) {
return new ListCell<User>() {
#Override
protected void updateItem(User item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setGraphic(null);
} else {
setText(item.getId() + " " + item.getName());
}
}
} ;
}
}
// Just set the button cell here:
cmbUserIds.setButtonCell(cellFactory.call(null));
cmbUserIds.setCellFactory(cellFactory);
You need to provide a functional fromString() Method within the Converter!
I had the same problem as you have and as I implemented the fromString() with working code, the ComboBox behaves as expected.
This class provides a few of my objects, for dev-test purposes:
public class DevCatProvider {
public static final CategoryObject c1;
public static final CategoryObject c2;
public static final CategoryObject c3;
static {
// Init objects
}
public static CategoryObject getCatForName(final String name) {
switch (name) {
case "Kategorie 1":
return c1;
case "Cat 2":
return c2;
case "Steuer":
return c3;
default:
return c1;
}
}
}
The converter object:
public class CategoryChooserConverter<T> extends StringConverter<CategoryObject> {
#Override
public CategoryObject fromString(final String catName) {
//This is the important code!
return Dev_CatProvider.getCatForName(catName);
}
#Override
public String toString(final CategoryObject categoryObject) {
if (categoryObject == null) {
return null;
}
return categoryObject.getName();
}
}
What is the cleanest way to map a string column to a Uri property using Dapper?
Here's the cleanest I've been able to come up with so far (using the ITypeMap functionality):
Query:
SELECT * FROM TableWithAStringAddressColumn
POCO:
public class MyPoco
{
[ColumnSetter("DapperAddress")]
public Uri Address { get; set; }
private string DapperAddress { set { this.Address = new Uri(value); } }
}
Extensions:
partial class SqlMapper
{
public static void InitializeTypeMaps()
{
SqlMapper.SetTypeMap(
typeof(MyPoco),
new CustomPropertyTypeMap(typeof(MyPoco), SqlMapper.CustomSetterMapper));
// call out every other class that needs this kind of mapping
}
public static Func<Type, string, PropertyInfo> CustomSetterMapper =
(type, columnName) =>
{
PropertyInfo prop = type
.GetProperties()
.FirstOrDefault(p => string.Equals(columnName, p.Name, StringComparison.OrdinalIgnoreCase));
if (prop != null)
{
// find out if we need to use a different setter
ColumnSetterAttribute setterAttribute = prop.GetCustomAttributes(false).OfType<ColumnSetterAttribute>().LastOrDefault();
if (setterAttribute != null)
{
PropertyInfo setterProp = type
.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.FirstOrDefault(p => string.Equals(setterAttribute.Setter, p.Name, StringComparison.OrdinalIgnoreCase));
if (setterProp == null)
{
throw new InvalidOperationException(string.Format("Setter property misconfigured (Property={0}, Setter={1})", prop.Name, setterAttribute.Setter));
}
else
{
prop = setterProp;
}
}
}
return prop;
};
}
Custom Attribute:
public class ColumnSetterAttribute : Attribute
{
public string Setter { get; set; }
public ColumnSetterAttribute(string setter)
{
this.Setter = setter;
}
}
[edit] I'm looking for a solution I can use without needing to call out all columns in all my queries (I'd like to find a solution where I can use SELECT *).
Seems like a lot of work...
Wouldn't this be ok?
public class MyPoco
{
private string _uriMapper;
public Uri SomeUri
{
get { return new Uri(_uriMapper); }
}
public string Mapper { set { _uriMapper = value; } }
}
Edit:
public class UriContainer
{
private string _uriMapper;
public string UriMapper { set { _uriMapper = value; } }
public int Id { get; set; }
public Uri SomeUri { get {return new Uri(_uriMapper);} }
}
public class DbTests
{
[Test]
public void Can_Get_A_Uri()
{
using (var c = new SqlConnection("hello"))
{
c.Open();
var uri = c.Query<UriContainer>("select *, someuri as urimapper from uris where id = 3").Single();
Console.WriteLine(uri.SomeUri);
}
}
}
Following is part of service layer which is provided by WCF service :
[Serializable]
public class WaitInfo
{
private string roomName;
private string pName;
private string tagNo;
public string RoomName
{ get { return roomName; } set { this.roomName = value; } }
public string PName
{ get { return pName; } set { this.pName = value; } }
public string TagNo
{ get { return tagNo; } set { this.tagNo = value; } }
}
public class Service1 : IService1
{
public List<WaitInfo> GetWaitingList()
{
MyDBDataContext db = new MyDBDataContext();
var query = from w in db.WAIT_INFOs
select new WaitInfo
{
TagNo = w.PATIENT_INFO.TAG_NO,
RoomName= w.ROOM_INFO.ROOM_NAME,
PName= w.PATIENT_INFO.P_NAME
};
List<WaitInfo> result = query.ToList();
return result;
}
And following is codebehind part of UI layer which is provided by Silverlight
public MainPage()
{
InitializeComponent();
Service1Client s = new Service1Client();
s.GetWaitingListCompleted +=
new EventHandler<GetWaitingListByCompletedEventArgs>( s_GetWaitingListCompleted);
s.GetWaitingListAsync();
}
void s_GetWaitingListCompleted(object sender,
RadControlsSilverlightApplication1.ServiceReference2.GetWaitingListByCompletedEventArgs e)
{
GridDataGrid.ItemsSource = e.Result;
}
And following is xaml code in Silverlight page
<Grid x:Name="LayoutRoot">
<data:DataGrid x:Name="GridDataGrid"></data:DataGrid>
</Grid>
It is very simple code, however what I am thinking weird is property name of object at "e.Result" in the code behind page.
In the service layer, although properties' names are surely "RoomName, PName, TagNo", in the silverlight properties' names are "roomName, pName, tagNo" which are private variable name of the WaitingList Object.
Did I something wrong?
Thanks in advance.
Unless you specifically decorate your class with the DataContract attribute (which you should, instead of Serializable) then a default DataContract will be inferred. For normal Serializable types, this means the fields will be serialized as opposed to the properties.
You can markup your class in either of the following two ways. The latter will use the property accessors when serializing/deserializing your object which may be very useful or be a hassle depending on your circumstances.
[DataContract]
public class WaitInfo
{
[DataMember(Name="RoomName")]
private string roomName;
[DataMember(Name="PName")]
private string pName;
[DataMember(Name="TagNo")]
private string tagNo;
public string RoomName
{ get { return roomName; } set { this.roomName = value; } }
public string PName
{ get { return pName; } set { this.pName = value; } }
public string TagNo
{ get { return tagNo; } set { this.tagNo = value; } }
}
The method I prefer:
[DataContract]
public class WaitInfo
{
private string roomName;
private string pName;
private string tagNo;
[DataMember]
public string RoomName
{ get { return roomName; } set { this.roomName = value; } }
[DataMember]
public string PName
{ get { return pName; } set { this.pName = value; } }
[DataMember]
public string TagNo
{ get { return tagNo; } set { this.tagNo = value; } }
}