/// <summary> /// Convert a single value according to it's data type in Model class /// </summary> /// <param name="obj">It is an instance of Model class </param> /// <param name="prop">Property to which we want to convert and store</param> /// <param name="item">Variable having actual data which needs to be converted</param> private void AddSingleProperty(object obj, PropertyInfo prop, KeyValueWork item) { try { // Check is Property is Nullable or not if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>)) { if (!string.IsNullOrWhiteSpace(item.Value)) { // Get the actual property var type = Nullable.GetUnderlyingType(prop.PropertyType); if (type == typeof(Guid)) { var value = Guid.Parse(item.Value); prop.SetValue(obj, value, null); } else { prop.SetValue(obj, Convert.ChangeType(item.Value, prop.PropertyType.GetGenericArguments()[0]), null); } } } else { // Set value for non-nullable property prop.SetValue(obj, Convert.ChangeType(item.Value, prop.PropertyType), null); } this.kvps.Remove(item.SourceKvp); } catch (Exception e) { this.dictionaryErrors.Add(prop.Name, $"Please provide a valid input for {prop.Name}"); } }
public void SetPropertyValues(object obj, object parentObj = null, PropertyInfo parentProp = null) { //Recursively set PropertyInfo array for object hierarchy PropertyInfo[] props = obj.GetType().GetProperties(); //Set KV Work List for real iteration process so that kvps is not in iteration and //its items from kvps can be removed after each iteration List <KeyValuePair <string, string> > kvpsWork; foreach (var prop in props) { //Refresh KV Work list from refreshed base kvps list after processing each property kvpsWork = new List <KeyValuePair <string, string> >(kvps); //Check and process property encompassing complex object recursively if (prop.PropertyType.IsClass && prop.PropertyType.FullName != "System.String") { RecurseNestedObj(obj, prop); } else { foreach (var item in kvpsWork) { //Ignore any bracket in a name key var key = item.Key; var keyParts = Regex.Split(key, RexBrackets); if (keyParts.Length > 1) { key = keyParts[keyParts.Length - 1]; } if (key == prop.Name) { //Populate KeyValueWork and pass it for adding property to object var kvw = new KeyValueWork() { Key = item.Key, Value = item.Value, SourceKvp = item }; AddSingleProperty(obj, prop, kvw); break; } } } } //Add property of this object to parent object if (parentObj != null) { parentProp.SetValue(parentObj, obj, null); } }
/// <summary> /// Sets the property value from received data in API to instance of Model class /// </summary> /// <param name="obj">Instance of Model class to which data needs to be store</param> public void SetPropertyValues(object obj) { // Recursively set PropertyInfo array for object hierarchy PropertyInfo[] props = obj.GetType().GetProperties(); // Set KV Work List for real iteration process so that kvps is not in iteration and // its items from kvps can be removed after each iteration List <KeyValuePair <string, string> > kvpsWork = new List <KeyValuePair <string, string> >(this.kvps); this.CheckForMandatoryField(props, this.kvps); foreach (var item in kvpsWork) { var key = item.Key; PropertyInfo prop = props.FirstOrDefault(x => x.Name.ToLower() == key.ToLower()); if (prop == null) { this.dictionaryErrors.Add(key, $"{key} is not a valid parameter."); continue; } if (key.ToLower() == prop.Name.ToLower()) { // Populate KeyValueWork and pass it for adding property to object var kvw = new KeyValueWork() { Key = item.Key, Value = item.Value, SourceKvp = item }; this.AddSingleProperty(obj, prop, kvw); } } if (this.dictionaryErrors.Count > 0) { throw new Exception(); } }
private void AddSingleProperty(object obj, PropertyInfo prop, KeyValueWork item) { if (prop.PropertyType.IsEnum) { var enumValues = prop.PropertyType.GetEnumValues(); object enumValue = null; bool isFound = false; //Try to match enum item name first for (int i = 0; i < enumValues.Length; i++) { if (item.Value.ToLower() == enumValues.GetValue(i).ToString().ToLower()) { enumValue = enumValues.GetValue(i); isFound = true; break; } } //Try to match enum default underlying int value if not matched with enum item name if (!isFound) { for (int i = 0; i < enumValues.Length; i++) { if (item.Value == i.ToString()) { enumValue = i; break; } } } prop.SetValue(obj, enumValue, null); } else { //Set value for non-enum terminal property prop.SetValue(obj, Convert.ChangeType(item.Value, prop.PropertyType), null); } kvps.Remove(item.SourceKvp); }
public void SetPropertyValues(object obj, object parentObj = null, PropertyInfo parentProp = null) { //Recursively set PropertyInfo array for object hierarchy PropertyInfo[] props = obj.GetType().GetProperties(); //Set KV Work List for real iteration process so that kvps is not in iteration and //its items from kvps can be removed after each iteration List<KeyValuePair<string, string>> kvpsWork; foreach (var prop in props) { //Refresh KV Work list from refreshed base kvps list after processing each property kvpsWork = new List<KeyValuePair<string, string>>(kvps); if (!prop.PropertyType.IsClass || prop.PropertyType.FullName == "System.String") { //For single or teminal properties. foreach (var item in kvpsWork) { //Ignore any bracket in a name key var key = item.Key; var keyParts = Regex.Split(key, RexBrackets); if (keyParts.Length > 1) key = keyParts[keyParts.Length - 1]; if (key == prop.Name) { //Populate KeyValueWork and pass it for adding property to object var kvw = new KeyValueWork() { Key = item.Key, Value = item.Value, SourceKvp = item }; AddSingleProperty(obj, prop, kvw); break; } } } else if (prop.PropertyType.IsClass) { //Check if List<string> or string[] type and assign string value directly to list or array item. if (prop.ToString().Contains("[System.String]") || prop.ToString().Contains("System.String[]")) { var strList = new List<string>(); foreach (var item in kvpsWork) { //Remove any brackets and enclosure from Key. var itemKey = Regex.Replace(item.Key, RexBrackets, ""); if (itemKey == prop.Name) { strList.Add(item.Value); kvps.Remove(item); } } //Add list to parent property. if (prop.PropertyType.IsGenericType) prop.SetValue(obj, strList); else if (prop.PropertyType.IsArray) prop.SetValue(obj, strList.ToArray()); } else { //Check and process property encompassing complex object recursively RecurseNestedObj(obj, prop); } } } //Add property of this object to parent object if (parentObj != null) { parentProp.SetValue(parentObj, obj, null); } }
private void SetPropertyValuesForList(object obj, object parentObj = null, PropertyInfo parentProp = null, string pParentName = "", string pParentObjIndex = "") { //Get props for type of object item in collection PropertyInfo[] props = obj.GetType().GetProperties(); //KV Work For each object item in collection List<KeyValueWork> kvwsGroup = new List<KeyValueWork>(); //KV Work for collection List<List<KeyValueWork>> kvwsGroups = new List<List<KeyValueWork>>(); Regex regex; Match match; bool isGroupAdded = false; string lastIndex = ""; foreach (var item in kvps) { //Passed parentObj and parentPropName are for List, whereas obj is instance of type for List if (item.Key.Contains(parentProp.Name)) { //Get data only from parent-parent for linked child KV Work if (pParentName != "" & pParentObjIndex != "") { regex = new Regex(pParentName + RexSearchBracket); match = regex.Match(item.Key); if (match.Groups[1].Value != pParentObjIndex) break; } //Get parts from current KV Work regex = new Regex(parentProp.Name + RexSearchBracket); match = regex.Match(item.Key); var brackets = match.Value.Replace(parentProp.Name, ""); var objIdx = match.Groups[1].Value; //Point to start next idx and save last kvwsGroup data to kvwsGroups if (lastIndex != "" && objIdx != lastIndex) { kvwsGroups.Add(kvwsGroup); isGroupAdded = true; kvwsGroup = new List<KeyValueWork>(); } //Get parts array from Key var keyParts = item.Key.Split(new string[] { brackets }, StringSplitOptions.RemoveEmptyEntries); //Populate KV Work var kvw = new KeyValueWork() { ObjIndex = objIdx, ParentName = parentProp.Name, //Get last part from prefixed name Key = keyParts[keyParts.Length - 1], Value = item.Value, SourceKvp = item }; //add KV Work to kvwsGroup list kvwsGroup.Add(kvw); lastIndex = objIdx; isGroupAdded = false; } } //Handle the last kvwsgroup item if not added to final kvwsGroups List. if (kvwsGroup.Count > 0 && isGroupAdded == false) kvwsGroups.Add(kvwsGroup); //Initiate List or Array IList listObj = null; Array arrayObj = null; if (parentProp.PropertyType.IsGenericType || parentProp.PropertyType.BaseType.IsGenericType) { listObj = (IList)Activator.CreateInstance(parentProp.PropertyType); } else if (parentProp.PropertyType.IsArray) { arrayObj = Array.CreateInstance(parentProp.PropertyType.GetElementType(), kvwsGroups.Count); } int idx = 0; foreach (var group in kvwsGroups) { //Initiate object with type of collection item object tempObj = null; tempObj = Activator.CreateInstance(obj.GetType()); //Iterate through properties of object model. foreach (var prop in props) { if (!prop.PropertyType.IsClass || prop.PropertyType.FullName == "System.String") { //Assign terminal property to object foreach (var item in group) { if (item.Key == prop.Name) { AddSingleProperty(tempObj, prop, item); break; } } } else if (prop.PropertyType.IsClass) { //Check if List<string> or string[] type and assign string value directly to list or array item. if (prop.ToString().Contains("[System.String]") || prop.ToString().Contains("System.String[]")) { //Match passed current processing object. var tempProps = tempObj.GetType().GetProperties(); //Iterate through current processing object properties. foreach (var tempProp in tempProps) { if (tempProp.Name == prop.Name) { var strList = new List<string>(); //Iterate through passed data items. foreach (var item in group) { //Remove any brackets and enclosure from Key. var itemKey = Regex.Replace(item.Key, RexBrackets, ""); if (itemKey == tempProp.Name) { strList.Add(item.Value); kvps.Remove(item.SourceKvp); } } //Add list to parent property. if (prop.PropertyType.IsGenericType) tempProp.SetValue(tempObj, strList); else if (prop.PropertyType.IsArray) tempProp.SetValue(tempObj, strList.ToArray()); } } } //Check and process nested objects in collection recursively //Pass ObjIndex for child KV Work items only for this parent object else { RecurseNestedObj(tempObj, prop, pParentName: group[0].ParentName, pParentObjIndex: group[0].ObjIndex); } } } //Add populated object to List or Array if (listObj != null) { listObj.Add(tempObj); } else if (arrayObj != null) { arrayObj.SetValue(tempObj, idx); idx++; } } //Add property for List or Array into parent object if (listObj != null) { parentProp.SetValue(parentObj, listObj, null); } else if (arrayObj != null) { parentProp.SetValue(parentObj, arrayObj, null); } }
private void AddSingleProperty(object obj, PropertyInfo prop, KeyValueWork item) { if (prop.PropertyType.IsEnum) { var enumValues = prop.PropertyType.GetEnumValues(); object enumValue = null; bool isFound = false; //Try to match enum item name first for (int i = 0; i < enumValues.Length; i++) { if (item.Value.ToLower() == enumValues.GetValue(i).ToString().ToLower()) { enumValue = enumValues.GetValue(i); isFound = true; break; } } //Try to match enum default underlying int value if not matched with enum item name if(!isFound) { for (int i = 0; i < enumValues.Length; i++) { if (item.Value == i.ToString()) { enumValue = i; break; } } } prop.SetValue(obj, enumValue, null); } else { //Set value for non-enum terminal property prop.SetValue(obj, Convert.ChangeType(item.Value, prop.PropertyType), null); } kvps.Remove(item.SourceKvp); }
public void SetPropertyValuesForList(object obj, object parentObj = null, PropertyInfo parentProp = null, string pParentName = "", string pParentObjIndex = "") { //Get props for type of object item in collection PropertyInfo[] props = obj.GetType().GetProperties(); //KV Work For each object item in collection List <KeyValueWork> kvwsGroup = new List <KeyValueWork>(); //KV Work for collection List <List <KeyValueWork> > kvwsGroups = new List <List <KeyValueWork> >(); Regex regex; Match match; bool isGroupAdded = false; string lastIndex = ""; foreach (var item in kvps) { //Passed parentObj and parentPropName are for List, whereas obj is instance of type for List if (item.Key.Contains(parentProp.Name)) { //Get data only from parent-parent for linked child KV Work if (pParentName != "" & pParentObjIndex != "") { regex = new Regex(pParentName + RexSearchBracket); match = regex.Match(item.Key); if (match.Groups[1].Value != pParentObjIndex) { break; } } //Get parts from current KV Work regex = new Regex(parentProp.Name + RexSearchBracket); match = regex.Match(item.Key); var brackets = match.Value.Replace(parentProp.Name, ""); var objIdx = match.Groups[1].Value; //Point to start next idx and save last kvwsGroup data to kvwsGroups if (lastIndex != "" && objIdx != lastIndex) { kvwsGroups.Add(kvwsGroup); isGroupAdded = true; kvwsGroup = new List <KeyValueWork>(); } //Get parts array from Key var keyParts = item.Key.Split(new string[] { brackets }, StringSplitOptions.RemoveEmptyEntries); //Populate KV Work var kvw = new KeyValueWork() { ObjIndex = objIdx, ParentName = parentProp.Name, //Get last part from prefixed name Key = keyParts[keyParts.Length - 1], Value = item.Value, SourceKvp = item }; //add KV Work to kvwsGroup list kvwsGroup.Add(kvw); lastIndex = objIdx; isGroupAdded = false; } } //Handle the last kvwsgroup item if not added to final kvwsGroups List. if (kvwsGroup.Count > 0 && isGroupAdded == false) { kvwsGroups.Add(kvwsGroup); } //Initiate List or Array IList listObj = null; Array arrayObj = null; if (parentProp.PropertyType.IsGenericType || parentProp.PropertyType.BaseType.IsGenericType) { listObj = (IList)Activator.CreateInstance(parentProp.PropertyType); } else if (parentProp.PropertyType.IsArray) { arrayObj = Array.CreateInstance(parentProp.PropertyType.GetElementType(), kvwsGroups.Count); } int idx = 0; foreach (var group in kvwsGroups) { //Initiate object with type of collection item var tempObj = Activator.CreateInstance(obj.GetType()); foreach (var prop in props) { //Check and process nested objects in collection recursively //Pass ObjIndex for child KV Work items only for this parent object if (prop.PropertyType.IsClass && prop.PropertyType.FullName != "System.String") { RecurseNestedObj(tempObj, prop, pParentName: group[0].ParentName, pParentObjIndex: group[0].ObjIndex); } else { //Assign terminal property to object foreach (var item in group) { if (item.Key == prop.Name) { AddSingleProperty(tempObj, prop, item); break; } } } } //Add populated object to List or Array if (listObj != null) { listObj.Add(tempObj); } else if (arrayObj != null) { arrayObj.SetValue(tempObj, idx); idx++; } } //Add property for List or Array into parent object if (listObj != null) { parentProp.SetValue(parentObj, listObj, null); } else if (arrayObj != null) { parentProp.SetValue(parentObj, arrayObj, null); } }
public void SetPropertyValues(object obj, object parentObj = null, PropertyInfo parentProp = null) { //Recursively set PropertyInfo array for object hierarchy PropertyInfo[] props = obj.GetType().GetProperties(); //Set KV Work List for real iteration process so that kvps is not in iteration and //its items from kvps can be removed after each iteration List <KeyValuePair <string, string> > kvpsWork; foreach (var prop in props) { //Refresh KV Work list from refreshed base kvps list after processing each property kvpsWork = new List <KeyValuePair <string, string> >(kvps); if (!prop.PropertyType.IsClass || prop.PropertyType.FullName == "System.String") { //For single or teminal properties. foreach (var item in kvpsWork) { //Ignore any bracket in a name key var key = item.Key; var keyParts = Regex.Split(key, RexBrackets); if (keyParts.Length > 1) { key = keyParts[keyParts.Length - 1]; } if (key == prop.Name) { //Populate KeyValueWork and pass it for adding property to object var kvw = new KeyValueWork() { Key = item.Key, Value = item.Value, SourceKvp = item }; AddSingleProperty(obj, prop, kvw); break; } } } else if (prop.PropertyType.IsClass) { //Check if List<string> or string[] type and assign string value directly to list or array item. if (prop.ToString().Contains("[System.String]") || prop.ToString().Contains("System.String[]")) { var strList = new List <string>(); foreach (var item in kvpsWork) { //Remove any brackets and enclosure from Key. var itemKey = Regex.Replace(item.Key, RexBrackets, ""); if (itemKey == prop.Name) { strList.Add(item.Value); kvps.Remove(item); } } //Add list to parent property. if (prop.PropertyType.IsGenericType) { prop.SetValue(obj, strList); } else if (prop.PropertyType.IsArray) { prop.SetValue(obj, strList.ToArray()); } } else { //Check and process property encompassing complex object recursively RecurseNestedObj(obj, prop); } } } //Add property of this object to parent object if (parentObj != null) { parentProp.SetValue(parentObj, obj, null); } }
public void SetPropertyValues(object obj, object parentObj = null, PropertyInfo parentProp = null) { //Recursively set PropertyInfo array for object hierarchy PropertyInfo[] props = obj.GetType().GetProperties(); //Set KV Work List for real iteration process so that kvps is not in iteration and //its items from kvps can be removed after each iteration List<KeyValuePair<string, string>> kvpsWork; foreach (var prop in props) { //Refresh KV Work list from refreshed base kvps list after processing each property kvpsWork = new List<KeyValuePair<string, string>>(kvps); //Check and process property encompassing complex object recursively if (prop.PropertyType.IsClass && prop.PropertyType.FullName != "System.String") { RecurseNestedObj(obj, prop); } else { foreach (var item in kvpsWork) { //Ignore any bracket in a name key var key = item.Key; var keyParts = Regex.Split(key, RexBrackets); if (keyParts.Length > 1) key = keyParts[keyParts.Length - 1]; if (key == prop.Name) { //Populate KeyValueWork and pass it for adding property to object var kvw = new KeyValueWork() { Key = item.Key, Value = item.Value, SourceKvp = item }; AddSingleProperty(obj, prop, kvw); break; } } } } //Add property of this object to parent object if (parentObj != null) { parentProp.SetValue(parentObj, obj, null); } }
//Change by: Zhicheng Su private void AddSingleProperty(object obj, PropertyInfo prop, KeyValueWork item) { if (prop.PropertyType.IsEnum) { var enumValues = prop.PropertyType.GetEnumValues(); object enumValue = null; bool isFound = false; //Try to match enum item name first for (int i = 0; i < enumValues.Length; i++) { if (item.Value.ToLower() == enumValues.GetValue(i).ToString().ToLower()) { enumValue = enumValues.GetValue(i); isFound = true; break; } } //Try to match enum default underlying int value if not matched with enum item name if (!isFound) { for (int i = 0; i < enumValues.Length; i++) { if (item.Value == i.ToString()) { enumValue = i; break; } } } prop.SetValue(obj, enumValue, null); } else { Type t = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType; var value = item.Value == null ? null : TypeDescriptor.GetConverter(t).ConvertFromInvariantString(item.Value); //Type t = prop.PropertyType; //var value=Util.ChangeType<typeof(t)>(item.Value); //Set value for non-enum terminal property prop.SetValue(obj, value);//Convert.ChangeType(item.Value, prop.PropertyType), null); } kvps.Remove(item.SourceKvp); }