{"id":59,"date":"2024-05-29T23:39:20","date_gmt":"2024-05-29T23:39:20","guid":{"rendered":"https:\/\/mystifying-liskov.77-68-127-141.plesk.page\/?p=59"},"modified":"2024-05-29T23:39:20","modified_gmt":"2024-05-29T23:39:20","slug":"baseobject-cs","status":"publish","type":"post","link":"https:\/\/mystifying-liskov.77-68-127-141.plesk.page\/?p=59","title":{"rendered":"BaseObject.cs"},"content":{"rendered":"\n<pre class=\"wp-block-code\"><code>using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Reflection;\nusing System.Runtime.Serialization;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace WooCommerceNET.Base\n{\n    &#91;DataContract]\n    public class JsonObject\n    {\n        &#91;IgnoreDataMember]\n        public static CultureInfo Culture { get; set; }\n\n        &#91;OnSerializing]\n        void OnSerializing(StreamingContext ctx)\n        {\n            foreach (PropertyInfo pi in GetType().GetRuntimeProperties())\n            {\n                PropertyInfo objValue = GetType().GetRuntimeProperties().FindByName(pi.Name + \"Value\");\n                if (objValue != null &amp;&amp; pi.GetValue(this) != null)\n                {\n                    if (pi.PropertyType == typeof(decimal?))\n                    {\n                        if (GetType().FullName.StartsWith(\"WooCommerceNET.WooCommerce.v1\") ||\n                            GetType().FullName.StartsWith(\"WooCommerceNET.WooCommerce.v2\") ||\n                            GetType().FullName.StartsWith(\"WooCommerceNET.WooCommerce.v3\") ||\n                            GetType().GetTypeInfo().BaseType.FullName.StartsWith(\"WooCommerceNET.WooCommerce.v1\") ||\n                            GetType().GetTypeInfo().BaseType.FullName.StartsWith(\"WooCommerceNET.WooCommerce.v2\") ||\n                            GetType().GetTypeInfo().BaseType.FullName.StartsWith(\"WooCommerceNET.WooCommerce.v3\"))\n                            objValue.SetValue(this, (pi.GetValue(this) as decimal?).Value.ToString(Culture));\n                        else\n                            objValue.SetValue(this, decimal.Parse(pi.GetValue(this).ToString(), Culture));\n                    }\n                    else if (pi.PropertyType == typeof(int?))\n                    {\n                        objValue.SetValue(this, int.Parse(pi.GetValue(this).ToString(), Culture));\n                    }\n                    else if (pi.PropertyType == typeof(DateTime?))\n                    {\n                        objValue.SetValue(this, ((DateTime?)pi.GetValue(this)).Value.ToString(\"yyyy-MM-ddTHH:mm:ss\"));\n                    }\n                }\n            }\n        }\n\n        &#91;OnDeserialized]\n        void OnDeserialized(StreamingContext ctx)\n        {\n            foreach (PropertyInfo pi in GetType().GetRuntimeProperties())\n            {\n                PropertyInfo objValue = GetType().GetRuntimeProperties().FindByName(pi.Name + \"Value\");\n\n                if (objValue != null)\n                {\n                    if (pi.PropertyType == typeof(decimal?))\n                    {\n                        object value = objValue.GetValue(this);\n\n                        if (!(value == null || value.ToString() == string.Empty))\n                            pi.SetValue(this, decimal.Parse(value.ToString(), Culture));\n                    }\n                    else if (pi.PropertyType == typeof(int?))\n                    {\n                        object value = objValue.GetValue(this);\n\n                        if (!(value == null || value.ToString() == string.Empty))\n                            pi.SetValue(this, int.Parse(value.ToString(), Culture));\n                    }\n                    else if (pi.PropertyType == typeof(DateTime?))\n                    {\n                        object value = objValue.GetValue(this);\n\n                        if (!(value == null || value.ToString() == string.Empty))\n                            pi.SetValue(this, DateTime.Parse(value.ToString()));\n                    }\n                }\n            }\n        }\n\n\n        \/\/&#91;OnDeserializing]\n        \/\/void tset(StreamingContext ctx)\n        \/\/{\n        \/\/    if (GetType().Name.Contains(\"ProductMeta\"))\n        \/\/        foreach (PropertyInfo pi in GetType().GetRuntimeProperties())\n        \/\/        {\n\n        \/\/        }\n        \/\/}\n    }\n\n    \/\/public class MyCustomerResolver : DataContractResolver\n    \/\/{\n    \/\/    public override bool TryResolveType(Type dataContractType, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)\n    \/\/    {\n    \/\/        if (dataContractType == typeof(string))\n    \/\/        {\n    \/\/            XmlDictionary dictionary = new XmlDictionary();\n    \/\/            typeName = dictionary.Add(\"SomeCustomer\");\n    \/\/            typeNamespace = dictionary.Add(\"http:\/\/tempuri.com\");\n    \/\/            return true;\n    \/\/        }\n    \/\/        else\n    \/\/        {\n    \/\/            return knownTypeResolver.TryResolveType(dataContractType, declaredType, null, out typeName, out typeNamespace);\n    \/\/        }\n    \/\/    }\n\n    \/\/    public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver)\n    \/\/    {\n    \/\/        throw new NotImplementedException();\n    \/\/    }\n    \/\/}\n\n    public class BatchObject&lt;T>\n    {\n        &#91;DataMember(EmitDefaultValue = false)]\n        public List&lt;T> create { get; set; }\n\n        &#91;DataMember(EmitDefaultValue = false)]\n        public List&lt;T> update { get; set; }\n\n        &#91;DataMember(EmitDefaultValue = false)]\n        public List&lt;ulong> delete { get; set; }\n\n        &#91;IgnoreDataMember]\n        public List&lt;T> DeletedItems { get; set; }\n    }\n\n    public class WCItem&lt;T>\n    {\n        public string APIEndpoint { get; protected set; }\n        public RestAPI API { get; protected set; }\n\n        public WCItem(RestAPI api)\n        {\n            API = api;\n            if(typeof(T).BaseType.GetRuntimeProperty(\"Endpoint\") == null)\n                APIEndpoint = typeof(T).GetRuntimeProperty(\"Endpoint\").GetValue(null).ToString();\n            else\n                APIEndpoint = typeof(T).BaseType.GetRuntimeProperty(\"Endpoint\").GetValue(null).ToString();\n        }\n\n        public virtual async Task&lt;T> Get(ulong id, Dictionary&lt;string, string> parms = null)\n        {\n            return API.DeserializeJSon&lt;T>(await API.GetRestful(APIEndpoint + \"\/\" + id.ToString(), parms).ConfigureAwait(false));\n        }\n\n        public virtual async Task&lt;List&lt;T>> GetAll(Dictionary&lt;string, string> parms = null)\n        {\n            return API.DeserializeJSon&lt;List&lt;T>>(await API.GetRestful(APIEndpoint, parms).ConfigureAwait(false));\n        }\n\n        public virtual async Task&lt;T> Add(T item, Dictionary&lt;string, string> parms = null)\n        {\n            return API.DeserializeJSon&lt;T>(await API.PostRestful(APIEndpoint, item, parms).ConfigureAwait(false));\n        }\n\n        &#91;Obsolete(\"AddRange method is obsolete, please use UpdateRange for batch Add, Update, Delete.\")]\n        public async Task&lt;BatchObject&lt;T>> AddRange(BatchObject&lt;T> items, Dictionary&lt;string, string> parms = null)\n        {\n            return API.DeserializeJSon&lt;BatchObject&lt;T>>(await API.PostRestful(APIEndpoint + \"\/batch\", items, parms).ConfigureAwait(false));\n        }\n\n        public virtual async Task&lt;T> Update(ulong id, T item, Dictionary&lt;string, string> parms = null)\n        {\n            return API.DeserializeJSon&lt;T>(await API.PostRestful(APIEndpoint + \"\/\" + id.ToString(), item, parms).ConfigureAwait(false));\n        }\n\n        public virtual async Task&lt;T> UpdateWithNull(ulong id, object item, Dictionary&lt;string, string> parms = null)\n        {\n            if (API.GetType().Name == \"RestAPI\")\n            {\n                StringBuilder json = new StringBuilder();\n                json.Append(\"{\");\n                foreach (var prop in item.GetType().GetRuntimeProperties())\n                {\n                    if (prop.GetValue(item).ToString() == \"\")\n                        json.Append($\"\\\"{prop.Name}\\\": \\\"\\\", \");\n                    else\n                        json.Append($\"\\\"{prop.Name}\\\": \\\"{prop.GetValue(item)}\\\", \");\n                }\n\n                if (json.Length > 1)\n                    json.Remove(json.Length - 2, 1);\n\n                json.Append(\"}\");\n\n                return API.DeserializeJSon&lt;T>(await API.PostRestful(APIEndpoint + \"\/\" + id.ToString(), json.ToString(), parms).ConfigureAwait(false));\n            }\n            else\n                return API.DeserializeJSon&lt;T>(await API.PostRestful(APIEndpoint + \"\/\" + id.ToString(), item, parms).ConfigureAwait(false));\n        }\n\n        public virtual async Task&lt;BatchObject&lt;T>> UpdateRange(BatchObject&lt;T> items, Dictionary&lt;string, string> parms = null)\n        {\n            string json = await UpdateRangeRaw(items, parms);\n\n            if (items.delete == null || items.delete.Count == 0)\n                return API.DeserializeJSon&lt;BatchObject&lt;T>>(json);\n            else\n            {\n                BatchObject&lt;T> batchResult = new BatchObject&lt;T>();\n\n                if ((items.create == null || items.create.Count == 0) &amp;&amp; (items.update == null || items.update.Count == 0))\n                {\n                    batchResult.DeletedItems = API.DeserializeJSon&lt;List&lt;T>>(json.Substring(json.IndexOf(\"&#91;\")).TrimEnd('}'));\n                }\n                else\n                {\n                    var pos = json.LastIndexOf(\"\\\"delete\\\":&#91;\");\n                    if (pos != -1)\n                    {\n                        batchResult = API.DeserializeJSon&lt;BatchObject&lt;T>>(json.Substring(0, pos - 1) + \"}\");\n                        batchResult.DeletedItems = API.DeserializeJSon&lt;List&lt;T>>(json.Substring(pos + 9).TrimEnd('}'));\n                    }\n                    else\n                        batchResult = API.DeserializeJSon&lt;BatchObject&lt;T>>(json);\n                }\n\n                return batchResult;\n            }\n        }\n\n        public virtual async Task&lt;string> UpdateRangeRaw(BatchObject&lt;T> items, Dictionary&lt;string, string> parms = null)\n        {\n            return await API.PostRestful(APIEndpoint + \"\/batch\", items, parms).ConfigureAwait(false);\n        }\n\n        public virtual async Task&lt;T> Delete(ulong id, bool force = false, Dictionary&lt;string, string> parms = null)\n        {\n            if (force)\n            {\n                if (parms == null)\n                    parms = new Dictionary&lt;string, string>();\n\n                if (!parms.ContainsKey(\"force\"))\n                    parms.Add(\"force\", \"true\");\n            }\n\n            return API.DeserializeJSon&lt;T>(await API.DeleteRestful(APIEndpoint + \"\/\" + id.ToString(), parms).ConfigureAwait(false));\n        }\n\n        &#91;Obsolete(\"DeleteRange method is obsolete, please use UpdateRange for batch Add, Update, Delete.\")]\n        public async Task&lt;string> DeleteRange(BatchObject&lt;T> items, Dictionary&lt;string, string> parms = null)\n        {\n            return await API.PostRestful(APIEndpoint + \"\/batch\", items, parms).ConfigureAwait(false);\n        }\n    }\n\n    public class WCSubItem&lt;T>\n    {\n        public string APIEndpoint { get; protected set; }\n        public string APIParentEndpoint { get; protected set; }\n        public RestAPI API { get; protected set; }\n\n        public WCSubItem(RestAPI api, string parentEndpoint)\n        {\n            API = api;\n            if (typeof(T).BaseType.FullName.Contains(\"v2\"))\n                APIEndpoint = typeof(T).BaseType.GetRuntimeProperty(\"Endpoint\").GetValue(null).ToString();\n            else\n                APIEndpoint = typeof(T).GetRuntimeProperty(\"Endpoint\").GetValue(null).ToString();\n\n            APIParentEndpoint = parentEndpoint;\n        }\n\n        public virtual async Task&lt;T> Get(ulong id, ulong parentId, Dictionary&lt;string, string> parms = null)\n        {\n            return API.DeserializeJSon&lt;T>(await API.GetRestful(APIParentEndpoint + \"\/\" + parentId.ToString() + \"\/\" + APIEndpoint + \"\/\" + id.ToString(), parms).ConfigureAwait(false));\n        }\n\n        public virtual async Task&lt;List&lt;T>> GetAll(object parentId, Dictionary&lt;string, string> parms = null)\n        {\n            return API.DeserializeJSon&lt;List&lt;T>>(await API.GetRestful(APIParentEndpoint + \"\/\" + parentId.ToString() + \"\/\" + APIEndpoint, parms).ConfigureAwait(false));\n        }\n\n        public virtual async Task&lt;T> Add(T item, ulong parentId, Dictionary&lt;string, string> parms = null)\n        {\n            return API.DeserializeJSon&lt;T>(await API.PostRestful(APIParentEndpoint + \"\/\" + parentId.ToString() + \"\/\" + APIEndpoint, item, parms).ConfigureAwait(false));\n        }\n\n        public virtual async Task&lt;T> Update(ulong id, T item, ulong parentId, Dictionary&lt;string, string> parms = null)\n        {\n            return API.DeserializeJSon&lt;T>(await API.PostRestful(APIParentEndpoint + \"\/\" + parentId.ToString() + \"\/\" + APIEndpoint + \"\/\" + id.ToString(), item, parms).ConfigureAwait(false));\n        }\n\n        public virtual async Task&lt;T> UpdateWithNull(ulong id, ulong parentId, object item, Dictionary&lt;string, string> parms = null)\n        {\n            if (API.GetType().Name == \"RestAPI\")\n            {\n                StringBuilder json = new StringBuilder();\n                json.Append(\"{\");\n                foreach (var prop in item.GetType().GetProperties())\n                {\n                    if (prop.GetValue(item).ToString() == \"\")\n                        json.Append($\"\\\"{prop.Name}\\\": \\\"\\\", \");\n                    else\n                        json.Append($\"\\\"{prop.Name}\\\": \\\"{prop.GetValue(item)}\\\", \");\n                }\n\n                if (json.Length > 1)\n                    json.Remove(json.Length - 2, 1);\n\n                json.Append(\"}\");\n\n                return API.DeserializeJSon&lt;T>(await API.PostRestful(APIParentEndpoint + \"\/\" + parentId.ToString() + \"\/\" + APIEndpoint + \"\/\" + id.ToString(), json.ToString(), parms).ConfigureAwait(false));\n            }\n            else\n                return API.DeserializeJSon&lt;T>(await API.PostRestful(APIParentEndpoint + \"\/\" + parentId.ToString() + \"\/\" + APIEndpoint + \"\/\" + id.ToString(), item, parms).ConfigureAwait(false));\n        }\n\n        public virtual async Task&lt;BatchObject&lt;T>> UpdateRange(ulong parentId, BatchObject&lt;T> items, Dictionary&lt;string, string> parms = null)\n        {\n            string json = await UpdateRangeRaw(parentId, items, parms);\n\n            if (items.delete == null || items.delete.Count == 0)\n                return API.DeserializeJSon&lt;BatchObject&lt;T>>(json);\n            else\n            {\n                BatchObject&lt;T> batchResult = new BatchObject&lt;T>();\n\n                if ((items.create == null || items.create.Count == 0) &amp;&amp; (items.update == null || items.update.Count == 0))\n                {\n                    batchResult.DeletedItems = API.DeserializeJSon&lt;List&lt;T>>(json.Substring(json.IndexOf(\"&#91;\")).TrimEnd('}'));\n                }\n                else\n                {\n                    var pos = json.LastIndexOf(\"\\\"delete\\\":&#91;\");\n                    if (pos != -1)\n                    {\n                        batchResult = API.DeserializeJSon&lt;BatchObject&lt;T>>(json.Substring(0, pos - 1) + \"}\");\n                        batchResult.DeletedItems = API.DeserializeJSon&lt;List&lt;T>>(json.Substring(pos + 9).TrimEnd('}'));\n                    }\n                    else\n                        batchResult = API.DeserializeJSon&lt;BatchObject&lt;T>>(json);\n                }\n\n                return batchResult;\n            }\n        }<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-59","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/mystifying-liskov.77-68-127-141.plesk.page\/index.php?rest_route=\/wp\/v2\/posts\/59","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/mystifying-liskov.77-68-127-141.plesk.page\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mystifying-liskov.77-68-127-141.plesk.page\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mystifying-liskov.77-68-127-141.plesk.page\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mystifying-liskov.77-68-127-141.plesk.page\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=59"}],"version-history":[{"count":1,"href":"https:\/\/mystifying-liskov.77-68-127-141.plesk.page\/index.php?rest_route=\/wp\/v2\/posts\/59\/revisions"}],"predecessor-version":[{"id":60,"href":"https:\/\/mystifying-liskov.77-68-127-141.plesk.page\/index.php?rest_route=\/wp\/v2\/posts\/59\/revisions\/60"}],"wp:attachment":[{"href":"https:\/\/mystifying-liskov.77-68-127-141.plesk.page\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=59"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mystifying-liskov.77-68-127-141.plesk.page\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=59"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mystifying-liskov.77-68-127-141.plesk.page\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=59"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}