-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExtensions.cs
116 lines (92 loc) · 3.29 KB
/
Extensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
using OpenSRS.NET.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace OpenSRS.NET
{
internal static class Extensions
{
public static T ParseEnum<T>(string text, bool ignoreCase = false)
where T : Enum
{
return (T)Enum.Parse(typeof(T), text, ignoreCase);
}
public static string GetValueOrDefault(this IDictionary<string, string> dic, string key)
{
if (!dic.TryGetValue(key, out var value))
return "";
return value;
}
internal static string CalculateMD5Hash(string input)
{
// step 1, calculate MD5 hash from input
var md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = Encoding.ASCII.GetBytes(input);
#pragma warning disable CA1850 // Prefer static 'HashData' method over 'ComputeHash' due to multi-target
byte[] hash = md5.ComputeHash(inputBytes);
#pragma warning restore CA1850 // Prefer static 'HashData' method over 'ComputeHash' due to multi-target
// step 2, convert byte array to hex string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString().ToLower();
}
internal static Dictionary<string, object> ObjectToDictionary(object instance)
{
var properties = instance.GetType().GetTypeInfo().GetProperties();
var dic = new Dictionary<string, object>(properties.Length);
foreach (var property in properties)
{
var prop = property.GetValue(instance, null);
if (prop == null)
continue;
dic[property.Name] = prop;
}
return dic;
}
internal static XElement ToDtAssoc(object parameters)
{
return ToDtAssoc(ObjectToDictionary(parameters));
}
internal static XElement ToDtAssoc(Dictionary<string, object> parameters)
{
var rootEl = new XElement("dt_assoc");
foreach (var item in parameters)
{
if (item.Value != null)
{
rootEl.Add(new XElement("item", new XAttribute("key", item.Key), item.Value));
}
}
return rootEl;
}
internal static XElement ToDtArray(string[] items)
{
var element = new XElement("dt_array");
int i = 0;
foreach (var item in items)
{
element.Add(new XElement("item", new XAttribute("key", i.ToString()), item));
i++;
}
return element;
}
internal static XElement ToDtArray(IEnumerable<IDtEl> items)
{
var arrayEl = new XElement("dt_array");
int i = 0;
foreach (var item in items)
{
arrayEl.Add(new XElement("item", new XAttribute("key", i.ToString()), item.ToDtAssoc()));
i++;
}
return arrayEl;
}
}
}