How to print all object fields dynamicly even if on of the fields is object - c#-4.0

I want want to print all the fields in object and if one of the field is object i want to print it fields and on and on (with recursion).
I wrote function but i get this error once i've entering to recursion.
Field '_str1' defined on type 'ConsoleApplication1.StringTest' is not
a field on the target object which is of type
'System.Reflection.RtFieldInfo'.
This is the Code:
static void OutPutObject(dynamic dyn,Type pType)
{
List<string> lFieldsList = new List<string>();
// Get the type of MyClass.
Type lType = pType;
// Get the FieldInfo of MyClass.
FieldInfo[] myFields = lType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
// Display the values of the fields.
for (int i = 0; i < myFields.Length; i++)
{
if (myFields[i].FieldType.IsClass && myFields[i].FieldType.Name != "String")
{
Type tType = myFields[i].FieldType.GetType();
OutPutObject(myFields[i], pType);
}
else
{
Console.WriteLine(string.Format("{0}: {1}", myFields[i].Name, myFields[i].GetValue(dyn)));
}
}
}
public class IntTest
{
private int a = 1;
private int b = 2;
}
public class StringTest
{
private string _str1;
private string _str2;
private IntTest intl;
public StringTest()
{
_str1 = "str1";
_str2 = "str2";
}
}

I've change your code and now it works!
Please notice that the inner classes must have default constructor.
static void OutPutObject(object obj, Type pType, bool isFirst)
{
// Get the FieldInfo of MyClass.
FieldInfo[] myFields = pType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
// Display the values of the fields.
for (int i = 0; i < myFields.Length; i++)
{
if (myFields[i].FieldType.IsPrimitive || myFields[i].FieldType == typeof(Decimal) || myFields[i].FieldType == typeof(String))
{
if (!isFirst)
{
object temp = Activator.CreateInstance(pType);
obj = temp;
}
Console.WriteLine(string.Format("{0}: {1}", myFields[i].Name, myFields[i].GetValue(obj)));
}
else if (myFields[i].FieldType.IsClass)
{
Type tType = myFields[i].FieldType;
OutPutObject(myFields[i], tType, false);
}
}
}

You can use following lines to write object public fields. I tested on .NET 4.0
Type type = obj.GetType();
foreach (var f in type.GetFields().Where(f => f.IsPublic)) {
Console.WriteLine("Name: "+f.Name+" Value: "+ f.GetValue(obj) );
}

Related

Changing the Default Option for Column Filters

Is it possible to change the default option all column filters? I'm pretty sure I can accomplish this with some JavaScript, but I'd like to know if there's any way within the Acumatica framework to change this.
The answer will be no. The filter is inside the PX.Web.UI.dll in the PXGridFilter class which is an internal class. The property that you are interested in is the Condition.
The value is set inside one of the private methods of the PXGrid class. The code of the method is below:
private IEnumerable<PXGridFilter> ab()
{
List<PXGridFilter> list = new List<PXGridFilter>();
if (this.FilterID != null)
{
Guid? filterID = this.FilterID;
Guid guid = PXGrid.k;
if (filterID == null || (filterID != null && filterID.GetValueOrDefault() != guid))
{
using (IEnumerator<PXResult<FilterRow>> enumerator = PXSelectBase<FilterRow, PXSelect<FilterRow, Where<FilterRow.filterID, Equal<Required<FilterRow.filterID>>, And<FilterRow.isUsed, Equal<True>>>>.Config>.Select(this.DataGraph, new object[]
{
this.FilterID.Value
}).GetEnumerator())
{
while (enumerator.MoveNext())
{
FilterRow row = enumerator.Current;
string dataField = row.DataField;
PXCache pxcache = PXFilterDetailView.TargetCache(this.DataGraph, new Guid?(this.FilterID.Value), ref dataField);
if (this.Columns[row.DataField] != null)
{
List<PXGridFilter> list2 = list;
int valueOrDefault = row.OpenBrackets.GetValueOrDefault();
string dataField2 = row.DataField;
string dataField3 = row.DataField;
int value = (int)row.Condition.Value;
object value2 = pxcache.ValueFromString(dataField, row.ValueSt);
string valueText = row.ValueSt.With((string _) => this.Columns[row.DataField].FormatValue(_));
object value3 = pxcache.ValueFromString(dataField, row.ValueSt2);
string value2Text = row.ValueSt2.With((string _) => this.Columns[row.DataField].FormatValue(_));
int valueOrDefault2 = row.CloseBrackets.GetValueOrDefault();
int? #operator = row.Operator;
int num = 1;
list2.Add(new PXGridFilter(valueOrDefault, dataField2, dataField3, value, value2, valueText, value3, value2Text, valueOrDefault2, #operator.GetValueOrDefault() == num & #operator != null));
}
}
return list;
}
}
}
if (this.FilterRows != null && this.FilterRows.Count > 0)
{
for (int i = 0; i < this.FilterRows.Count; i++)
{
PXFilterRow row = this.FilterRows[i];
list.Add(new PXGridFilter(row.OpenBrackets, row.DataField, row.DataField, (int)row.Condition, row.Value, row.Value.With(delegate(object _)
{
if (this.Columns[row.DataField] == null)
{
return _.ToString();
}
return this.Columns[row.DataField].FormatValue(_);
}), row.Value2, row.Value2.With(delegate(object _)
{
if (this.Columns[row.DataField] == null)
{
return _.ToString();
}
return this.Columns[row.DataField].FormatValue(_);
}), row.CloseBrackets, row.OrOperator));
}
}
return list;
}
UPDATE
The below JS code allows you to change the condition of the last set filter:
px_all.ctl00_phG_grid_fd.show();
px_all.ctl00_phG_grid_fd_cond.items.items[7].setChecked(true);
px_all.ctl00_phG_grid_fd_ok.element.click();
px_all.ctl00_phG_grid_fd_cond.items.items[7].value "EQ"
px_all.ctl00_phG_grid_fd_cond.items.items[8].value "NE"
px_all.ctl00_phG_grid_fd_cond.items.items[9].value "GT"
px_all.ctl00_phG_grid_fd_cond.items.items[13].value "LIKE"
px_all.ctl00_phG_grid_fd_cond.items.items[14].value "LLIKE"
px_all.ctl00_phG_grid_fd_cond.items.items[15].value "RLIKE"
px_all.ctl00_phG_grid_fd_cond.items.items[16].value "NOTLIKE"
px_all.ctl00_phG_grid_fd_cond.items.items[18].value "ISNULL"
px_all.ctl00_phG_grid_fd_cond.items.items[19].value "ISNOTNULL"

Accessing Map Value

static void getRecommendations(Map<User, HashMap<Item, Double>> map, User to) {
scores = sortMapByScore(scores, to);
TreeMap<User, Double> scores1 = (TreeMap<User, Double>) scores.get(to);
Set<User> user = (Set<User>) scores1.keySet();
Iterator<User> itr = user.iterator();
Map<Item, Double> rec = new HashMap<Item, Double>();
int i = 0;
while (itr.hasNext() && i < 5) {
User u = itr.next();
/* for(Item e:map.get(to).keySet()){ */
for (Item e1 : map.get(u).keySet()) {
if (!map.get(to).containsKey(e1)) {
if (rec.containsKey(e1)) {
double sc = rec.get(e1);
rec.put(e1, sc + map.get(u).get(e1) * scores.get(to).get(u));
} else {
// System.out.println(scores);
rec.put(e1, map.get(u).get(e1) * scores.get(to).get(u));
}
// }
}
}
i++;
}
TreeMap<Item, Double> res = new TreeMap<Item, Double>(
new ValueComparator(rec));
res.putAll(rec);
int k=0;
for(Item d:res.keySet()){
System.out.println(d.getmTitle());
k++;
if(k==5){break;}
}
}
I am using nested HashMap and TreeMap in this example.But I am facing the below problem.
In the code above in the line
rec.put(e1, map.get(u).get(e1) * scores.get(u).get(to));
I am getting a NullPointerException, even though I am using the same HashMap's keyset to get the Values.

Trying to create a package for my java application

I am in the process of putting together a simple RPG game engine in java. At this point everything works fine while all my classes are in one directory. Basically, I know I am going to end up with a heap of files and wish to organise them into a package structure. I followed the directions at http://www.jarticles.com/package/package_eng.html but can't seem to make the magic happen. The two classes posted are the least dependent of the lot and I figure if I can get these working then the rest shouldn't be a drama. For the record I am using openJDK in Leeenux (remix of Ubuntu netbook Remix)
First class
package adventure.engine;
import java.util.*;
public class Inventory
{
ArrayList itemList = new ArrayList();
public Inventory()
{
}
public void addItem()
{
}
public void removeItem()
{
}
}
And the second:
package adventure.engine;
import adventure.engine.*;
public class PlayerCharacter
{
private String name = "Player";
private String race;
private String plrClass;
private int level;
private int xp;
private int levelXp;
private Inventory inventory = new Inventory();
//---------
//Abilities
//---------
private static final String[] abilitiesList = {"Strength",
"Dexterity",
"Constitution",
"Intelligence",
"Wisdom",
"Charisma"};
private int[] abilitiesValues = new int[abilitiesList.length];
//------
//Skills
//------
private static final String[] skillsList = {"Acrobatics" , "Insight",
"Arcana" , "Intimidate",
"Athletics" , "Nature",
"Bluff" , "Perception",
"Diplomacy" , "Religion",
"Dungeoneering" , "Stealth",
"Endurance" , "Streetwise",
"Heal" , "Thievery",
"History"};
private int[] skillsValues = new int[skillsList.length];
//***********
//Constructor
//***********
public PlayerCharacter()
{
level = 1;
xp = 0;
levelXp = 1000;
setAbility("Strength", 8);
setAbility("Dexterity", 10);
setAbility("Constitution", 10);
setAbility("Intelligence", 10);
setAbility("Wisdom", 10);
setAbility("Charisma", 10);
} //public PlayerSheet()
//*************
//Class Methods
//*************
public void addXp(int val)
{
xp += val;
if (xp >= levelXp)
{
level++;
xp -= levelXp;
//levelXp += ;
}
} //public void addXp(int val)
public void updateSkills()
{
}
//Mutators
public void setName(String n)
{
name = n;
}
public void setLevel(int l)
{
level = l;
}
public void setRace(String r)
{
race = r;
}
public void setXP(int x)
{
xp = x;
}
public void setClass(String c)
{
plrClass = c;
}
//set ability value by name
public void setAbility(String a, int val)
{
for(int i = 0; i < abilitiesList.length; i++)
{
if(abilitiesList[i].compareTo(a) == 0)
{
abilitiesValues[i] = val;
}
}
}
//set ability by index
public void setAbility(int index, int val)
{
abilitiesValues[index] = val;
}
//set skill by name
public void setSkill(String name, int val)
{
for(int i = 0; i < skillsList.length; i++)
{
if(skillsList[i].compareTo(name) == 0)
{
skillsValues[i] = val;
}
}
}
//set skill by index
public void setSkill(int index, int val)
{
skillsValues[index] = val;
}
//Accessors
public static String[] getAbilityList()
{
return abilitiesList;
}
public static String[] getSkillsList()
{
return skillsList;
}
//retrieve an ability value by name
public int getAbility(String a)
{
int val = 0;
for(int i = 0; i < abilitiesList.length; i++)
{
if(abilitiesList[i].compareTo(a) == 0)
{
val = abilitiesValues[i];
break;
}
}
return val;
}
//retrieve an ability value by index number
public int getAbility(int i)
{
return abilitiesValues[i];
}
public int getSkill(String s)
{
int val = 0;
for(int i = 0; i < skillsList.length; i++)
{
if(skillsList[i].compareTo(s) == 0)
{
val = skillsValues[i];
break;
}
}
return val;
}
public int getSkill(int i)
{
return skillsValues[i];
}
public String getName()
{
return name;
}
public String getRace()
{
return race;
}
public String getPlrClass()
{
return plrClass;
}
public int getLevel()
{
return level;
}
public int getXP()
{
return xp;
}
public int getLevelXP()
{
return levelXp;
}
} //public class PlayerCharacter
Classes reside in /home/user/Java/adventure/engine
Output from echo $classpath is /home/james/Java:/.:
when I attempt to compile the second class I get the following error:
PlayerCharacter.java:18: cannot find symbol
symbol : class Inventory
location: class adventure.engine.PlayerCharacter
private Inventory inventory = new Inventory();
^
PlayerCharacter.java:18: cannot find symbol
symbol : class Inventory
location: class adventure.engine.PlayerCharacter
private Inventory inventory = new Inventory();
Any feedback on this would be greatly appreciated.How to solve this?
Two things.
1) You might not have compiled Inventory
2) PlayerCharacter and Inventory are in same package. So there is no need to import.
You should be compiling them as
javac adventure/engine/Inventory.java
javac adventure/engine/PlayerCharacter.java

Blackberry - How if addElement() doesn't work?

I am a newbie of Blackberry developing application. I try to store all xml parsing data to an object, and set them to a vector.
public class XmlParser extends MainScreen {
Database d;
private HttpConnection hcon = null;
private Vector binN;
public Vector getBinN() {
return binN;
}
public void setBinN(Vector bin) {
this.binN = bin;
}
LabelField from;
LabelField ttl;
LabelField desc;
LabelField date;
public XmlParser() {
LabelField title = new LabelField("Headline News" ,LabelField.HCENTER|LabelField.USE_ALL_WIDTH);
setTitle(title);
try {
URI myURI = URI.create("file:///SDCard/Database/WebFeed.db");
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement("SELECT feed_url, feed_name FROM WebFeed");
st.prepare();
Cursor c = st.getCursor();
while (c.next()) {
Row r = c.getRow();
hcon = (HttpConnection)Connector.open(r.getString(0));
hcon.setRequestMethod(HttpConnection.GET);
hcon.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
hcon.setRequestProperty("Content-Length", "0");
hcon.setRequestProperty("Connection", "close");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
builder.isValidating();
Document document = builder.parse(hcon.openInputStream());
Element rootElement = document.getDocumentElement();
rootElement.normalize();
NodeList list = document.getElementsByTagName("item");
int i=0;
while (i<10){
Node item = list.item(i);
if(item.getNodeType() != Node.TEXT_NODE) {
NodeList itemChilds = item.getChildNodes();
int j=0;
while (j<10){
Node detailNode = itemChilds.item(j);
if(detailNode.getNodeType() != Node.TEXT_NODE) {
if(detailNode.getNodeName().equalsIgnoreCase("title")) {
ttl = new LabelField(getNodeValue(detailNode)) {
public void paint(Graphics g) {
g.setColor(Color.BLUE);
super.paint(g);
}
};
from = new LabelField(r.getString(1), LabelField.FIELD_RIGHT|LabelField.USE_ALL_WIDTH);
ttl.setFont(Font.getDefault().derive(Font.BOLD));
from.setFont(Font.getDefault().derive(Font.BOLD));
add (from);
add (ttl);
} else if(detailNode.getNodeName().equalsIgnoreCase("description")) {
desc = new LabelField(getNodeValue(detailNode), 0, 70, USE_ALL_WIDTH);
add(desc);
} else if(detailNode.getNodeName().equalsIgnoreCase("dc:date")) {
date = new LabelField(getNodeValue(detailNode), 11, 5, USE_ALL_WIDTH) {
public void paint(Graphics g) {
g.setColor(Color.ORANGE);
super.paint(g);
}
};
add(date);
add(new SeparatorField());
} else if(detailNode.getNodeName().equalsIgnoreCase("pubDate")) {
date = new LabelField(getNodeValue(detailNode), 0, 22, USE_ALL_WIDTH) {
public void paint(Graphics g) {
g.setColor(Color.ORANGE);
super.paint(g);
}
};
add(date);
add(new SeparatorField());
} else {
System.out.println("not the node");
}
} else {
System.out.println("not text node");
}
j++;
}
}
i++;
BinNews bin = new BinNews();
bin.setProv(from.getText());
bin.setTitle(ttl.getText());
bin.setDesc(desc.getText());
bin.setDate(date.getText());
binN.addElement(bin);
}
setBinN(binN);
}
//setBinN(binN);
st.close();
d.close();
} catch (Exception e) {
add (new LabelField(e.toString(),LabelField.HCENTER|LabelField.USE_ALL_WIDTH));
System.out.println(e.toString());
}
}
public String getNodeValue(Node node) {
NodeList nodeList = node.getChildNodes();
Node childNode = nodeList.item(0);
return childNode.getNodeValue();
}
}
I try to store all data from an object called BinNews, to a vector called binN. But when I do debugging, I found that BinN has null value, because "binN.addElement(bin)" doesn't work.
Please advise.
First, you don't actually call setBinN until after the while(i < 10) loop completes. So when you say binN.addElement(bin) then binN will be null.
However your setBinN(binN) call doesn't make sense because you're passing in binN and then setting it to itself which isn't going to do anything.
What you can do is have binN = new Vector(); at the top of the constructor and then it won't be null later on. I don't think the setBinN call will be necessary later on if you're adding the BinNews objects straight to binN.

Easy way to search a string for strings

I'm trying to find the easiest way to search a string for an array of possible strings. I know the easy way to do this for characters is to use myString.IndexOfAny(charArray). But how what if I'd like to search my string for strings and not just characters? Are there any .net tricks or methods that make this easier?
Basically, I'd like to do something like this:
string myName = "rahkim";
string[] names = new string[] {"joe","bob","chris"};
if(myName.IndexOfAny(names) >= 0)
{
//success code//
}
I know there are ways to do this with loops, etc. But I was hoping for something inherent in the framework.
You should define if you want to to find equal strings or search for a matching substring. Both ways are easy pre-LINQ and with LINQ.
string myName = "rahkim";
string[] names = new string[] { "joe", "bob", "chris" };
Equal Strings, LINQ
bool contains = names.Contains(myName);
Equal Strings, Pre-LINQ
bool contains = new List<string>(name).Contains(myName);
Substrings, LINQ
bool contains = names.Any(name => name.Contains(myName));
Substring, Pre-LINQ
bool contains = false;
foreach(string name in names)
if (name.Contains(myName))
contains = true;
If anyone else found this while trying to search for a .Net method like String.IndexOfAny(String[]), this is my solution:
C#
public int IndexOfAny(string test, string[] values)
{
int first = -1;
foreach (string item in values) {
int i = test.IndexOf(item);
if (i >= 0) {
if (first > 0) {
if (i < first) {
first = i;
}
} else {
first = i;
}
}
}
return first;
}
VB
Public Function IndexOfAny(test As String, values As String()) As Integer
Dim first As Integer = -1
For Each item As String In values
Dim i As Integer = test.IndexOf(item)
If i >= 0 Then
If first > 0 Then
If i < first Then
first = i
End If
Else
first = i
End If
End If
Next
Return first
End Function
You can do a LastIndexOfAny(String[]) by just switching the
i < first
to
i > first
You can (also) use the static IndexOf method of the Array class:
bool hasName = Array.IndexOf(names, myName) > -1;
int IndexOfAny(String[] rgs) would indeed be nice but it's nominally an O(n^2) operation. If, in your application, the set of strings rgs is large and always the same, the most efficient approach is to load them into a trie data structure once, and then use the trie repeatedly to search for them within the unknown strings given at runtime.
Here is the relevant code, adapted from a C# trie source I found on the web, attributed to "Kerry D. Wong." In my version, each string in the trie has a "payload" of generic type TValue. To use this trie to simply search for substrings, the payload could always be set to true, as illustrated with simple_trie.
The other thing I changed here is that this trie automatically adapts allow for storage of arbitrary Unicode strings. The array at each node—which characterizes a trie—adjusts its base and length to accomodate the range of Unicode characters which need to be stored at that node. This allows for case-sensitive matching, for example.
The C# 3.0 initialization syntax is handy for this trie, but enabling it requires a dummy implementation of IEnumerable in order to compile. The CLR doesn't seem to call GetEnumerator() and I suggest that you don't try to enumerate with its result either.
using System;
using System.Collections.Generic;
using System.Linq; // only used in Main()
class Program
{
// trie with payload of type <String>
static Trie<String> value_trie = new Trie<String>
{
{ "rabbit", "cute" },
{ "giraffe", "tall" },
{ "ape", "smart" },
{ "hippo", "large" },
};
// degenerate case of a trie without payload
static Trie<bool> simple_trie = new Trie<bool>
{
{ "rabbit", true },
{ "giraffe", true },
{ "ape", true },
{ "hippo", true },
};
static void Main(String[] args)
{
String s = "Once upon a time, a rabbit met an ape in the woods.";
// Retrieve payloads for words in the string.
//
// output:
// cute
// smart
foreach (String word in value_trie.AllSubstringValues(s))
Console.WriteLine(word);
// Simply test a string for any of the words in the trie.
// Note that the Any() operator ensures that the input is no longer
// traversed once a single result is found.
//
// output:
// True
Console.WriteLine(simple_trie.AllSubstringValues(s).Any(e=>e));
s = "Four score and seven years ago.";
// output:
// False
Console.WriteLine(simple_trie.AllSubstringValues(s).Any(e => e));
}
}
class TrieNode<TValue>
{
private TrieNode<TValue>[] nodes = null;
private TValue m_value = default(TValue);
private Char m_base;
public Char Base { get { return m_base; } }
public bool IsEnd { get { return !m_value.Equals(default(TValue)); } }
public TValue Value
{
get { return m_value; }
set { m_value = value; }
}
public IEnumerable<TrieNode<TValue>> Nodes { get { return nodes; } }
public TrieNode<TValue> this[char c]
{
get
{
if (nodes != null && m_base <= c && c < m_base + nodes.Length)
return nodes[c - m_base];
return null;
}
}
public TrieNode<TValue> AddChild(char c)
{
if (nodes == null)
{
m_base = c;
nodes = new TrieNode<TValue>[1];
}
else if (c >= m_base + nodes.Length)
{
Array.Resize(ref nodes, c - m_base + 1);
}
else if (c < m_base)
{
Char c_new = (Char)(m_base - c);
TrieNode<TValue>[] tmp = new TrieNode<TValue>[nodes.Length + c_new];
nodes.CopyTo(tmp, c_new);
m_base = c;
nodes = tmp;
}
TrieNode<TValue> node = nodes[c - m_base];
if (node == null)
{
node = new TrieNode<TValue>();
nodes[c - m_base] = node;
}
return node;
}
};
class Trie<TValue> : System.Collections.IEnumerable
{
private TrieNode<TValue> _root = new TrieNode<TValue>();
// This dummy enables C# 3.0 initialization syntax
public System.Collections.IEnumerator GetEnumerator()
{
return null;
}
public void Add(String s, TValue v)
{
TrieNode<TValue> node = _root;
foreach (Char c in s)
node = node.AddChild(c);
node.Value = v;
}
public bool Contains(String s)
{
TrieNode<TValue> node = _root;
foreach (Char c in s)
{
node = node[c];
if (node == null)
return false;
}
return node.IsEnd;
}
public TValue Find(String s_in)
{
TrieNode<TValue> node = _root;
foreach (Char c in s_in)
{
node = node[c];
if (node == null)
return default(TValue);
}
return node.Value;
}
public IEnumerable<TValue> FindAll(String s_in)
{
TrieNode<TValue> node = _root;
foreach (Char c in s_in)
{
node = node[c];
if (node == null)
break;
if (node.Value != null)
yield return node.Value;
}
}
public IEnumerable<TValue> AllSubstringValues(String s)
{
int i_cur = 0;
while (i_cur < s.Length)
{
TrieNode<TValue> node = _root;
int i = i_cur;
while (i < s.Length)
{
node = node[s[i]];
if (node == null)
break;
if (node.Value != null)
yield return node.Value;
i++;
}
i_cur++;
}
}
};
Here's the right syntax:
if(names.Contains(myName))
{
//success code//
}
if (names.Contains(myName))
{
//success code//
}

Resources