I am using CSOM to update some Task of a Project Server Project.
Which property has to be updated is not defined the code finds out dynamically what to update based on the property name as String.
For better understanding I wore a simplified version of my code
//fieldName = "ActualWorkTimeSpan"; value = "16:00:00";
private void Start(string fieldName, string value)
{
DraftTask draftTask = GetDraftTask();
Update(draftTask, fieldName, value);
PublishAndCheckin(draftTask);
}
private static void Update(DraftTask draftTask, string fieldName, string value)
{
// skip updating if field is Equal
if (GetPropValue(draftTask, fieldName).ToString() == value)
return;
// update of the task
SetPropValue(draftTask, fieldName, value);
}
private static object GetPropValue(object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null);
}
private static void SetPropValue(DraftTask src, string propName, object value)
{
src.GetType().GetProperty(propName).SetValue(src, value);
}
I can use GetPropValue()
without problem but for SetPropValue()
I would need the value to be in the right type.
In this case it would be "System.TimeSpan" for the property "ActualWorkTimeSpan". So I would need to convert the string "15:00:00" to TimeSpan.
It would be easy to do if it were TimeSpan every time, but I could be that the Field "Cost" is set to be updated.
Update(draftTask, "Cost", "500");
So my question is if it is Possible to find out what type the field has and than convert my value to the same type.
SetValue
takes anobject
type anyway. – Succeedref
keyword does, I suggest you go read up on that too. – SucceedSetValue
areobject
. I'm not sure what you are suggesting. – SucceedSetPropValue
takes parameterobject value
but this is always being called with a string. I suggest the method signature is changed if this is always going to be the case. – Garmanpublic TimeSpan ActualWorkTimeSpan
. If you call SetValue with a string on that property, it will fail at runtime without conversion. – Michaelemichaelinaobject
, or even make it generic. – Succeed"ActualWorkTimeSpan"
you used usenameof(DraftTask.ActualWorkTimeSpan)
learn.microsoft.com/en-us/dotnet/csharp/language-reference/… – SpermaryType
doesn't overrideToString
it will always compare the values based on the name of theType
, so objects will ALWAYS return as being unequal, unless the value is literally the name of theType
. – HarlanUpdate(ref draftTask, "ActualWorkTimeSpan", "15:00:00");
is just an example – Garman