Dynamic Object C# 4.0 , Creating columns at runtime from Pre-defined values - c#-4.0

I have used dynamic object but here is a situation where the column names comes from a pre-defined string arrays.How can i create objects at runtime with these pre-defined set of column values?.
The reason why i wanted to do this way is to create a custom class and add custom validation attributes in it so that i can use reflection at runtime to populate values to these dynamic objects mapped to my custom class and validate the values using a single function.
dynamic x = new MyCustomClass();
x.Name = "Jones"; // The Field or Column name "Name" comes from a array of strings.
Validator.Validate(x); //Here i use reflection to iterate through the custom attributes on MyCustomClass and validate them based on conditions.
Is it possible to do something like this x."Name" = "Jones"; :-)

I would suggest perhaps adding an indexer property to your MyCustomClass?
public string this[string binder] {
get {
string result;
return (this.TryGetMember(binder, out result)) ? result : string.Empty
}
set {
this.TrySetMember(binder, value);
}
}
x["Name"] = "Jones";

Related

Can I dynamically set a PXDataFieldAssign parameter of a PXDataFieldParam object?

I have code that sets the PXDataFieldAssign value as follows:
pf = new PXDataFieldAssign<xTACProjectTask.dueDate>(someValue);
I also have a table, holding the DAC field names, such as "xTACProjectTask.dueDate". This table also has a checkbox field to determine whether to use this DAC field as a parameter.
Is there a way to not have the DAC fieldname hard-coded, and instead (maybe using a 'typeof' call?) use the results of the table query to set that field name - like the following?
pf = new PXDataFieldAssign<typeof("xTACProjectTask.dueDate")>(someValue);
or, using my query result:
pf = new PXDataFieldAssign<typeof(query.value)>(someValue);
with query.value being the value in the table holding the DAC field name?
You can create it using Type.GetType and Activator.CreateInstance. Please see the example below:
string typeName = "PX.Objects.IN.InventoryItem+descr,PX.Objects";
Type typeArgument = Type.GetType(typeName);
Type genericClass = typeof(PXDataFieldAssign<>);
Type constructedClass = genericClass.MakeGenericType(typeArgument);
object created = Activator.CreateInstance(constructedClass,new object[] { "Test Description" });
You will get the below wrapped into object in the created

Find distinct values from column of datatable in c# and store distinct values in variables

i want to find distinct values from a column of datatable in c# and also want to store all these distinct values in variables
DataTable dtable = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * from clubbb ", con);
da.Fill(dtable, "clubbb");
int toto = bdtable.AsEnumerable().Distinct().Count();
You need to implement the interface IEqualityComparer<DataRow> methods to provide the way the Distinct method will use to know whether 2 rows are duplicate or not. This can be achieved with a class like this:
public class CustomComparer : IEqualityComparer<DataRow>
{
public bool Equals(DataRow x, DataRow y)
{
// your custom equality logic here
}
public int GetHashCode(DataRow obj)
{
// return hash code depending on your distinct criteria
}
}
Then change the call you made:
int toto = bdtable.AsEnumerable().Distinct(new CustomComparer()).Count();
I had similar problem, and in my case I needed to know distinct values of specific column, so I passed the name of this column to the custom comparer I implemented, so that GetHashCode will return identical hash codes for duplicate values.
You can read more here: https://msdn.microsoft.com/en-us/library/ms132151(v=vs.110).aspx
Hope this helps :)

Adding detectable Nullable values to CsvHelper

I was wondering if CsvHelper by Josh Close has anything in the configuration I am missing to translate values to null. I am a huge fan of this library, but I always thought there should be some sort of configuration to let it know what values represent NULL in your file. An example would be a column with the value "NA", "EMPTY", "NULL", etc. I am sure I could create my own TypeConverter, but I was hoping there would be an easier option to set somewhere in a config as this tends to be fairly common with files I encounter.
Is there a configuration setting to do this relatively easily?
I found the TypeConversion in the CsvHelper.TypeConversion namespace but am not sure where to apply something like this or an example of the correct usage:
new NullableConverter(typeof(string)).ConvertFromString(new TypeConverterOptions(), "NA")
I am also using the latest version 2.2.2
Thank you!
I think some time in the last seven years and thirteen versions since this question was asked the options for doing this without a custom type map class expanded, e.g.:
csvReader.Context.TypeConverterOptionsCache.GetOptions<string>().NullValues.Add("NULL");
csvReader.Context.TypeConverterOptionsCache.GetOptions<DateTime?>().NullValues.AddRange(new[] { "NULL", "0" });
csvReader.Context.TypeConverterOptionsCache.GetOptions<int?>().NullValues.Add("NULL");
csvReader.Context.TypeConverterOptionsCache.GetOptions<bool>().BooleanFalseValues.Add("0");
csvReader.Context.TypeConverterOptionsCache.GetOptions<bool>().BooleanTrueValues.Add("1");
CsvHelper can absolutely handle nullable types. You do not need to roll your own TypeConverter if a blank column is considered null. For my examples I am assuming you are using user-defined fluent mappings.
The first thing you need to do is construct a CsvHelper.TypeConverter object for your Nullable types. Note that I'm going to use int since strings allow null values by default.
public class MyClassMap : CsvClassMap<MyClass>
{
public override CreateMap()
{
CsvHelper.TypeConversion.NullableConverter intNullableConverter = new CsvHelper.TypeConversion.NullableConverter(typeof(int?));
Map(m => m.number).Index(2).TypeConverter(intNullableConverter);
}
}
Next is setting the attribute on your CsvReader object to allow blank columns & auto-trim your fields. Personally like to do this by creating a CsvConfiguration object with all of my settings prior to constructing my CsvReader object.
CsvConfiguration csvConfig = new CsvConfiguration();
csvConfig.RegisterClassMap<MyClassMap>();
csvConfig.WillThrowOnMissingField = false;
csvConfig.TrimFields = true;
Then you can call myReader = new CsvReader(stream, csvConfig) to build the CsvReader object.
IF you need to have defined values for null such as "NA" == null then you will need to roll your own CsvHelper.TypeConversion class. I recommend that you extend the NullableConverter class to do this and override both the constructor and ConvertFromString method. Using blank values as null is really your best bet though.
I used "ConvertUsing"...
public class RecordMap : CsvHelper.Configuration.ClassMap<Record>
{
public RecordMap()
{
AutoMap();
Map(m => m.TransactionDate).ConvertUsing( NullDateTimeParser );
Map(m => m.DepositDate).ConvertUsing( NullDateTimeParser );
}
public DateTime? NullDateTimeParser(IReaderRow row)
{
//"CurrentIndex" is a bit of a misnomer here - it's the index of the LAST GetField call so we need to +1
//https://github.com/JoshClose/CsvHelper/issues/1168
var rawValue = row.GetField(row.Context.CurrentIndex+1);
if (rawValue == "NULL")
return null;
else
return DateTime.Parse(rawValue);
}
}

How to add individual elements of an object in an Arraylist through a for loop?

I am trying to add all elements of an object into ArrayList. elements of the object are of different type.
e.g. object Employee having attributes like emp_id,name,address,DOB.
I want to store each attribute as an object in an ArrayList. Like,
ArrayList[1] = Employee.emp_id
ArrayList[2] = Employee.name
ArrayList[3] = Employee.address
I want to do it dynamically. Like, in future more attributes are added in this object, without doing a manual work. Is there a way to create an array List?
ArrayList must be of the same type. You can have an ArrayList of type in which you can do what you are doing, since all objects in Java extend Object. If you are trying to store different Object types in an arraylist, however, this is not possible.
You may know that first part, just was a little unclear in your post.
Here's how to do it with objects using reflection:
//make sure you import java.lang.reflect.*
public void addMyFields(Employee e){
ArrayList<Object> list = new ArrayList();
for (Field field : emp.getClass().getDeclaredFields())
{
field.setAccessible(true);
list.add(field.get(emp);
}
}

Automapper: Mapping a property value of an object to a string

Using Automapper, how do you handle the mapping of a property value on an object to an instance of a string. Basically I have a list of Role objects and I want to use Automapper to map the content of each "name" property to a corresponding list of string (so I just end up with a list of strings). I'm sure it has an obvious answer, but I can't find the mapping that I need to add to "CreateMap" to get it to work.
An example of the relevant code is shown below:
public class Role
{
public Guid Id{get;set;}
public string Name{get;set;}
...
...
}
// What goes in here?
Mapper.CreateMap<Role, string>().ForMember(....);
var allRoles = Mapper.Map<IList<Role>, IList<string>>(roles);
I love Automapper (and use it in a number of projects), but wouldn't this be easier with a simple LINQ statement?
var allRoles = from r in roles select r.Name
The AutoMapper way of accomplishing this:
Mapper.CreateMap<Role, String>().ConvertUsing(r => r.Name);

Resources