Files
BeWoPlaner/Shared/Extensions/ObjectExtensions.cs
2025-03-28 10:05:29 +01:00

90 lines
2.4 KiB
C#

using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace BS.Shared.Extensions
{
public static class ObjectExtensions
{
public static bool EqualsNullCheck(this object pObject, object otherObject)
{
return pObject == null ? otherObject == null : pObject.Equals(otherObject);
}
public static object GetPropertyValue(this object pObject, string pPropertyName)
{
PropertyInfo pPropInfo = pObject.GetType().GetProperty(pPropertyName);
return pPropInfo == null ? null : pPropInfo.GetValue(pObject, null);
}
public static void SetPropertyValue(this object pObject, string pPropertyName, object value)
{
PropertyInfo pPropInfo = pObject.GetType().GetProperty(pPropertyName);
pPropInfo?.SetValue(pObject, value, null);
}
public static string ToStringNullCheck(this object pObject)
{
return pObject == null ? string.Empty : pObject.ToString();
}
public static IDictionary<string, string> ToKeyValue(this object metaToken)
{
if (metaToken == null)
{
return null;
}
JToken token = metaToken as JToken;
if (token == null)
{
return ToKeyValue(JObject.FromObject(metaToken));
}
if (token.HasValues)
{
var contentData = new Dictionary<string, string>();
foreach (var child in token.Children().ToList())
{
var childContent = child.ToKeyValue();
if (childContent != null)
{
contentData = contentData.Concat(childContent)
.ToDictionary(k => k.Key, v => v.Value);
}
}
return contentData;
}
var jValue = token as JValue;
if (jValue?.Value == null)
{
return null;
}
var value = jValue?.Type == JTokenType.Date ?
jValue?.ToString("o", CultureInfo.InvariantCulture) :
jValue?.ToString(CultureInfo.InvariantCulture);
return new Dictionary<string, string> { { token.Path, value } };
}
public static NameValueCollection ToNameValueCollection(this object obj)
{
var coll = new NameValueCollection();
var keyvalues = obj.ToKeyValue();
foreach (var kv in keyvalues)
{
coll.Add(kv.Key, kv.Value);
}
return coll;
}
}
}