Metaprograming in C# : Automatic ToString Method - c#

I have some classes which only serve to contain data. For example
public class EntityAdresse : IEntityADRESSE
{
public string Name1 { get; set; }
public string Strasse { get; set; }
public string Plz { get; set; }
public string Ort { get; set; }
public string NatelD { get; set; }
public string Mail { get; set; }
public int Id_anrede { get; set; }
public string Telefon { get; set; }
public int Id_adr { get; set; }
public int Cis_adr { get; set; }
}
This represents a address. Like I said, it only contains data. No Methods (I know the interface doesn't make sense here...)
Now I need to implement ToString for all this Entity-Classes and there are a lot of them.
My question is: Is there a metaprograming feature in C# which generates this tostring methods automaticaly? I don't want to write boiler plate code for every which of these classes.
Alternatively I could also write a perl or python script to generate the code. But I prefer doing it in C# directly.

Generally, you need to obtain all property values of your class and combine them into a single string. This can be done using the following approach:
public override string ToString()
{
PropertyDescriptorCollection coll = TypeDescriptor.GetProperties(this);
StringBuilder builder = new StringBuilder();
foreach(PropertyDescriptor pd in coll)
{
builder.Append(string.Format("{0} : {1}", pd.Name , pd.GetValue(this).ToString()));
}
return builder.ToString();
}

The feature is called reflection. A simplest example would be:
public class EntityBase
{
public override string ToString()
{
StringBuilder sb = new StringBuilder();
foreach ( var property in this.GetType().GetProperties() )
{
sb.Append( property.GetValue( this, null ) );
}
return sb.ToString();
}
}
public class TheEntity : EntityBase
{
public string Foo { get; set; }
public string Bar { get; set; }
}
Please finetune it to fulfill your requirements.
As you can see the idea is to have a single implementation in a base class so that all descendands automatically inherit the same behavior.

A short version of what's already been said:
public override string ToString()
{
var propertyStrings = from prop in GetType().GetProperties()
select $"{prop.Name}={prop.GetValue(this)}";
return string.Join(", ", propertyStrings);
}

There isn't a feature built into the language to do this automatically, but you could write a library to do it using the Expression features in the framework to generate a function to do it.
You'd have a function like this:
Func<T,string> GenerateToString<T>()
And in your class you have something like this:
public class EntityAdresse : IEntityADRESSE
{
private static readonly Func<EntityAdresse,string> s_ToString=Generator.GenerateToString<EntityAdresse>();
public string Name1 { get; set; }
public string Strasse { get; set; }
public string Plz { get; set; }
public string Ort { get; set; }
public string NatelD { get; set; }
public string Mail { get; set; }
public int Id_anrede { get; set; }
public string Telefon { get; set; }
public int Id_adr { get; set; }
public int Cis_adr { get; set; }
public override ToString()
{
return s_ToString(this);
}
}
The challenge is writing GenerateToString. Using the Expression framework and reflection you'll be able to create a delegate that is as efficient as if you'd written the code by hand.
You could use reflection on it's own, but the performance hit will soon start to be an issue.

There is an open source framework StatePrinter for automatic ToString generation. It is very configurable so it should cater for your needs. The introspection code can be found at Introspection

Related

Linq dynamic Where clauses by string

i have some problem with universal method in C#, i have 4+ model classes like this:
public class Assortment{
public string Code { get; set; }
public string EANCode { get; set; }
public float Quantity { get; set; }
}
i want to create universal logic method liek this ->
public T GetItem<T>(int someInt, string expression) where T : class
{
return db.Set<T>().Where(expression).Select(x=>x);
}
is this posible?

Searching in json array

{
"medic":[
{
"ace":[
{
"name":"lisinopril",
"strength":"10 mg Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}
],
"anti":[
{
"name":"nitroglycerin",
"strength":"0.4 mg Sublingual Tab",
"dose":"1 tab",
"route":"SL",
"sig":"q15min PRN",
"pillCount":"#30",
"refills":"Refill 1"
}
],
"anticoag":[
{
"name":"warfarin sodium",
"strength":"3 mg Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}
],
}
]
}
class Program
{
static void Main(string[] args)
{
// ""reporttype"":""post"",
string jsonString = #"..."; //The above json
Console.WriteLine("Enter the Medication name in which you want to Find STRENGTH value :");
string medicname = Console.ReadLine();
var rootInstance = JsonConvert.DeserializeObject<Rootobject>(jsonString);
}
}
var result = rootInstance.medications[0].Where(x=>x.name == medicname ).Select(t => t.strength).ToList();
But when i run the above query, I get this below error:
'Medication' does not contain a definition for 'Where' and no accessible extension method 'Where' accepting a first argument of type 'Medication' could be found (are you missing a using directive or an assembly reference?)
I have added all necessary namespaces to my code.
and Here is my object class
public class Rootobject
{
public List<Medication> medications { get; set; }
}
public class Medication
{
public List<aceInhibitors> aceinhibitors { get ; set ; }
public List<anti> antianginal {get; set; }
public List<anticoag> anticoagulants {get; set; }
}
public class aceInhibitors
{
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("strength")]
public string strength { get; set; }
[JsonProperty("dose")]
public string dose { get; set; }
[JsonProperty("route")]
public string route { get; set; }
[JsonProperty("sig")]
public string sig { get; set; }
[JsonProperty("pillCount")]
public string pillCount { get; set; }
[JsonProperty("refills")]
public string refills { get; set; }
}
public class anti
{
public string name { get; set; }
public string strength { get; set; }
public string dose { get; set; }
public string route { get; set; }
public string sig { get; set; }
public string pillCount { get; set; }
public string refills { get; set; }
}
public class anticoag
{
public string name { get; set; }
public string strength { get; set; }
public string dose { get; set; }
public string route { get; set; }
public string sig { get; set; }
public string pillCount { get; set; }
public string refills { get; set; }
}
Your Medication object itself is not searchable. Instead it holds a bunch of list and each contains a different type (where all properties are the same). So maybe you should use some base class for the medicine and add another property to your Medication class. In that case you would have a class layout something like this:
public class Rootobject
{
public List<Medication> medications { get; set; }
}
public class Medication
{
public List<aceInhibitors> aceinhibitors { get; set; }
public List<antianginal> antianginal { get; set; }
public List<anticoagulants> anticoagulants { get; set; }
public List<betaBlocker> betablocker { get; set; }
public List<diuretic> diuretic { get; set; }
public List<Mineral> mineral { get; set; }
public IEnumerable<Medicine> Medicines => Enumerable.Empty<Medicine>()
.Concat(aceinhibitors)
.Concat(antianginal)
.Concat(anticoagulants)
.Concat(betablocker)
.Concat(diuretic)
.Concat(mineral);
}
public class Medicine
{
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("strength")]
public string strength { get; set; }
[JsonProperty("dose")]
public string dose { get; set; }
[JsonProperty("route")]
public string route { get; set; }
[JsonProperty("sig")]
public string sig { get; set; }
[JsonProperty("pillCount")]
public string pillCount { get; set; }
[JsonProperty("refills")]
public string refills { get; set; }
}
public class aceInhibitors : Medicine
{
}
public class antianginal : Medicine
{
}
public class anticoagulants : Medicine
{
}
public class betaBlocker : Medicine
{
}
public class diuretic : Medicine
{
}
public class Mineral : Medicine
{
}
And prepared with that you could now ask something like that:
var result = rootInstance.medications[0].Medicines
.Where(x => x.name == medicname)
.Select(t => t.strength)
.ToList();
If the model of the classes really matches your desires is up to you, but it should give you starting point.
If you want it more inline you could also do something like this:
public class Medication : IEnumerable<Medicine>
{
public List<aceInhibitors> aceinhibitors { get; set; }
public List<antianginal> antianginal { get; set; }
public List<anticoagulants> anticoagulants { get; set; }
public List<betaBlocker> betablocker { get; set; }
public List<diuretic> diuretic { get; set; }
public List<Mineral> mineral { get; set; }
public IEnumerator<Medicine> GetEnumerator()
{
return Enumerable.Empty<Medicine>()
.Concat(aceinhibitors)
.Concat(antianginal)
.Concat(anticoagulants)
.Concat(betablocker)
.Concat(diuretic)
.Concat(mineral)
.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
And in that case you could write something like this:
var result = rootInstance.medications[0]
.Where(x => x.name == medicname)
.Select(t => t.strength)
.ToList();
Your domain model is bit suboptimal as it was pointed out by Oliver. If you need to stick to this model, then you can do the following.
Introduce an interface for fields that are interesting from your query point of view:
public interface InterestingFields
{
string name { get; }
string strength { get; }
}
Each medication class can be easily adjusted to implement it, like:
public class Mineral: InterestingFields
{
public string name { get; set; }
public string strength { get; set; }
public string dose { get; set; }
public string route { get; set; }
public string sig { get; set; }
public string pillCount { get; set; }
public string refills { get; set; }
}
Make the properties of the Medication class queryable
var properties = typeof(Medication).GetProperties()
.Where(prop => prop.PropertyType.IsGenericType
&& prop.PropertyType.GetGenericTypeDefinition() == typeof(List<>)
&& typeof(InterestingFields).IsAssignableFrom(prop.PropertyType.GetGenericArguments()[0]))
.ToList();
I've used reflection where the property's type is a List<T> and T is assignable to InterestingFields
Go through the properties, retrieve the actual value and do the filtering based on that
var medication = rootInstance.medications[0];
var result = from property in properties
let collection = property.GetValue(medication) as IEnumerable<InterestingFields>
let element = collection?.ToArray().First()
where element?.name == medicname
select element.strength;
Console.WriteLine(result.First());
Proper design would lead to a separation from the data handling and the way that your data is stored. This way, it is easy to reuse the stored data for other handling, it is easier to unit test the data handling with test code, you can change the way that the data is stored, to for instance a CSV file, or XML, without having to change the data handling code.
So you need a class Medication:
class Medication
{
public string Name {get; set;}
public string Strength {get; set;}
public string Dose {get; set;}
... // etc.
}
Consider to change Dose and Strength to a numerical value.
Apparently you have stored all Medications somewhere. A proper software design would hide where it is stored, and what format it is stored in. All you know is, that you can store Medications in it, and fetch it back later, even after your program is restarted. Such a storage is often called a Repository:
class MedicationRepository
{
public IEnumerable<Medication> ReadMedications() {...}
}
The actual implementation is up to you. I think you'll use Nuget Package NewtonSoft Json for this. Maybe you also want methods to Add / Change / Remove Medications?
Consider to let the Repository class implement IEnumerable<Medication>, or even ICollection<Medication>, depending on what is most efficient in your case.
class MedicationRepository : IEnumerable<Medication>
{
public IEnumerator<Medication> GetEnumerator()
{
return this.ReadMedications().GetEnumerator();
}
...
}
Now that you've got a method to read all Medications, we can get back to your LINQ problem:
I need get input string from user(which is medication name in json) i need to check if input matches the name in medication and need to display corresponding strength value.
So you've got a procedure to read the medication name:
public string ReadMedicationName() {...}
And you want the Strength of all Medications with this name.
MedicationRepository medications = ...
string requestedMedicationName = this.ReadMedicationName();
string medicationStrength = medications
.Where(medication => medication.Name == requestedMedicationName)
.Select(medication => medication.Strength)
.FirstOrDefault();
In words: from all Medications, keep only those Medications that have a name that equals requestedMedicationName. If the name is unique, then there will be zero or one Medication left. From all remaining Medications, take only the value of property Strength, and take the first strength, or null if there is no Medication with this Name at all.
Can it be that there are several Medications with this name? Which one do you want in that case, just any Strength (= .FirstOrDefault()), all Strengths (= ToList())? In the latter case: how do you distinguish which Medication with this name contains which Strength? Consider to Select more properties in that case.
Conclusion
By separating the storage of the data and how you get the requested Medication Name from the data handling, it is easier to change the storage (to XML, to CSV, to a database), and it is easier to unit test the LINQ using specific test data.
Similarly: you've hidden how you get the name of the requested Medication: is it a DOS prompt? Did you read it from a file? Maybe you've changed it to a WinForms application and you read it from a Textbox, or a ComboBox. Because you separated, the LINQ doesn't have to change, and can be reused in several platforms.

Generate unique string key based on properties of object (cachekey)

I am simply trying to generate a unique cachekey that takes in the object type and property values
GetHashCode returns different results each time so that wont work, so I have to implement a solution but it has to be fast (I can go through the properties and and concat their values to a string but this might be slow and not the best way to go about it)
Nice To Have:
so if 2 different object types have the exact same properties and same values but they are different classes, they should be different cachekeys (chances of this happening are very slim but just in case)
Here is my code
public interface ICachableRequest
{
string GetCacheKey();
}
public class Object1 : ICachableRequest
{
public int IntValue1 { get; set; }
public double DoubleVal1 { get; set; }
public string StringVal1 { get; set; }
public string GetCacheKey()
{
throw new NotImplementedException();
}
}
public class Object2 : ICachableRequest
{
public int SomeIntValue1 { get; set; }
public double SomeOtherDoubleVal1 { get; set; }
public string MoreStringVal1 { get; set; }
public string MoreStringVal2 { get; set; }
public string MoreStringVal3 { get; set; }
public string MoreStringVal4 { get; set; }
public string GetCacheKey()
{
throw new NotImplementedException();
}
}

How can I refactor a simple class member to a more complex type?

I have a little class
public class ExcitingResults
{
public int A { get; set; }
public string B { get; set; }
public DateTime C { get; set; }
public string ComplexD
{
get { return SomeMethod("A", "B"); }
}
}
Currently I do some processing with results a List<ExcitingResults> that creates JSON or Excel files.
This processing relies strongly on the name of each property and the order that things appear in the output is defined by the order they appear in the class. Though in fact this is undefined behaviour and so could change if the compiler decides it wants things in a different order.
For this reason I would like to alter my class to something like this.
public class ExcitingResults
{
public column<int> A { get; set; }
public column<string> B { get; set; }
public column<DateTime> C { get; set; }
public column<string> ComplexD
{
get { return SomeMethod(A.Name, B.Name); }
}
}
public class column<T>
{
public T Value { get; set; }
public string Name { get; set; }
}
Clearly this is not a drop in replacement... is there some clever strategy I can take to make this change as painless as possible. Then in the future add complexity to the Column class such as order, friendly names and other attributes as they occur to me.
Or is this a crazy way forwards and I should be looking at another strategy to be able to add this extra information to the columns?
You could add property attributes, with the advantage that you don't touch the API of the class. For example, add the class:
[AttributeUsage(AttributeTargets.Property)]
public class ColumnAttribute : System.Attribute {
public string FriendlyName { get; set; }
public int Rank { get; set; }
}
You can now annotate your ExcitingResults class like this:
public class ExcitingResults {
[Column(FriendlyName = "A", Rank = 1)]
public int A { get; set; }
[Column(FriendlyName = "B", Rank = 4)]
public string B { get; set; }
[Column(FriendlyName = "C", Rank = 3)]
public DateTime C { get; set; }
[Column(FriendlyName = "D", Rank = 2)]
public string ComplexD {
get { return SomeMethod("A", "B"); }
}
}
Your processor class can then access the property attributes using reflection. For example, to print out an ExcitingResult's properties in order of Rank:
public static void Process(ExcitingResults result) {
var propertiesByRank = typeof(ExcitingResults)
.GetProperties()
.OrderBy(x => x.GetCustomAttribute<ColumnAttribute>().Rank);
foreach (var propertyInfo in propertiesByRank) {
var property = result.GetType().GetProperty(propertyInfo.Name);
var propertysFriendlyName = property.GetCustomAttribute<ColumnAttribute>().FriendlyName;
var propertysValue = property.GetValue(result, null);
Console.WriteLine($"{propertysFriendlyName} = {propertysValue}");
}
}
You'll want to do more error checking in your processing class, but you get the idea. See MSDN documentation and tutorial for more info.

C# template methods for template IEnumerable<T>. Is it possible?

Can anybody help me to solve this problem?
I have a base class:
public class BaseShowFilter {
public int TotalCount { get; set; }
public int FromNo { get; set; }
public int ShowCount { get; set; }
public string SortFieldName { get; set; }
public bool SortAsc { get; set; }
}
and a couple of ChildClasses from this base class. Then I have a few of other classes that store in (for example)
IEnumerable<OtherClassXXX> = ....
And I want to apply some filter to all of them using same method implemented in BaseShowFilter:
For example I need
dstList = srcList.Skip(this.FromNo-1).Take(this.ShowCount);
So I need implement in BaseShowFilter one function that will be accept in parameter IEnumerable and will return also IEnumerable
How can I write it? In pure C++ it will be simple as 1,2,3... but here I don't know how can it be done. Result may be something like this:
public class BaseShowFilter {
public int TotalCount { get; set; }
public int FromNo { get; set; }
public int ShowCount { get; set; }
public string SortFieldName { get; set; }
public bool SortAsc { get; set; }
public T FilterList<T>(T SrcList) where T :IEnumerable<> {
return srcList.Skip(this.FromNo-1).Take(this.ShowCount);
}
}
This is the usual way to do it:
public IEnumerable<T> FilterList<T>(IEnumerable<T> source)
{
return source.Skip(this.FromNo - 1).Take(this.ShowCount);
}

Categories

Resources