/// <summary>
		/// 
		/// </summary>
		/// <param name="root"></param>
		/// <param name="reader"></param>
		/// <param name="prefix"></param>
		public void PopulateTree(CompositeNode root, IDataReader reader, String prefix)
		{
			string[] fields = GetFields(reader);

			int[] indexesToSkip = FindDuplicateFields(fields);
			
			IndexedNode indexNode = new IndexedNode(prefix);
			
			int row = 0;

			while(reader.Read())
			{
				CompositeNode node = new CompositeNode(row.ToString());

				for(int i=0; i<reader.FieldCount; i++)
				{
					// Is in the skip list?
					if (Array.IndexOf(indexesToSkip, i) >= 0) continue;
					
					// Is null?
					if (reader.IsDBNull(i)) continue;
					
					Type fieldType = reader.GetFieldType(i);
					
					node.AddChildNode(new LeafNode(fieldType, fields[i], reader.GetValue(i)));
				}

				indexNode.AddChildNode(node);
			
				row++;
			}
			
			root.AddChildNode(indexNode);
		}
示例#2
0
		public CompositeNode BuildNode(XDocument doc)
		{
			var rootNode = new CompositeNode("root");
			rootNode.AddChildNode(ProcessElement(doc.Root));
			return rootNode;

		}
		public bool CanBindParameter(Type desiredType, String paramName, CompositeNode treeRoot)
		{
			bool canConvert;

			Node childNode = treeRoot.GetChildNode(paramName);

			if (childNode != null)
			{
				canConvert = true;
			}
			else if (desiredType == typeof (DateTime))
			{
				TrySpecialDateTimeBinding(desiredType, treeRoot, paramName, out canConvert);
			}
			else if (desiredType == typeof(DateTimeOffset))
			{
				TrySpecialDateTimeOffsetBinding(desiredType, treeRoot, paramName, out canConvert);
			}
			else
			{
				canConvert = false;
			}

			return canConvert;
		}
示例#4
0
        private object ConvertToSimpleValue(Type desiredType, string key, CompositeNode parent, out bool conversionSucceeded)
        {
            conversionSucceeded = false;

            Node childNode = parent.GetChildNode(key);

            if (childNode == null && IsDateTimeType(desiredType))
            {
                return(TrySpecialDateTimeBinding(desiredType, parent, key, out conversionSucceeded));
            }

            if (childNode == null && IsDateTimeOffsetType(desiredType))
            {
                return(TrySpecialDateTimeOffsetBinding(desiredType, parent, key, out conversionSucceeded));
            }

            if (childNode == null)
            {
                return(null);
            }

            if (childNode.NodeType == NodeType.Leaf)
            {
                return(ConvertLeafNode(desiredType, (LeafNode)childNode, out conversionSucceeded));
            }

            throw new BindingException("Could not convert param as the node related " +
                                       "to the param is not a leaf node. Param {0} parent node: {1}", key, parent.Name);
        }
示例#5
0
        private object TrySpecialDateTimeBinding(Type desiredType, CompositeNode treeRoot,
                                                 String paramName, out bool conversionSucceeded)
        {
            string dateUtc = TryGetDateWithUTCFormat(treeRoot, paramName, out conversionSucceeded);

            if (dateUtc != null)
            {
                conversionSucceeded = true;

                //DateTime dt = DateTime.Parse(dateUtc);

                if (desiredType.Name == "NullableDateTime")
                {
                    TypeConverter typeConverter = TypeDescriptor.GetConverter(desiredType);

                    return(typeConverter.ConvertFrom(dateUtc));
                }
                else
                {
                    return(DateTime.Parse(dateUtc));
                }
            }

            conversionSucceeded = false;
            return(null);
        }
示例#6
0
        public bool CanBindParameter(Type desiredType, String paramName, CompositeNode treeRoot)
        {
            bool canConvert;

            Node childNode = treeRoot.GetChildNode(paramName);

            if (childNode != null)
            {
                canConvert = true;
            }
            else if (desiredType == typeof(DateTime))
            {
                TrySpecialDateTimeBinding(desiredType, treeRoot, paramName, out canConvert);
            }
            else if (desiredType == typeof(DateTimeOffset))
            {
                TrySpecialDateTimeOffsetBinding(desiredType, treeRoot, paramName, out canConvert);
            }
            else
            {
                canConvert = false;
            }

            return(canConvert);
        }
示例#7
0
		public void PopulateTree(CompositeNode root, NameValueCollection nameValueCollection)
		{
			foreach (String key in nameValueCollection.Keys)
			{
				if (key == null) continue;
				string singleKeyName = NormalizeKey(key);
				String[] values = nameValueCollection.GetValues(key);

				if (values == null) continue;

				if (values.Length == 1 && key.EndsWith("[]"))
				{
					if (values[0] == string.Empty)
					{
						ProcessNode(root, typeof (String[]), singleKeyName, new string[0]);
					}
					else
					{
						values = values[0].Split(',');
						ProcessNode(root, typeof (String[]), singleKeyName, values);
					}
				}
				else if (values.Length == 1)
				{
					ProcessNode(root, typeof (String), key, values[0]);
				}
				else
				{
					ProcessNode(root, typeof (String[]), singleKeyName, values);
				}
			}
		}
示例#8
0
        public object BindParameter(Type desiredType, String paramName, CompositeNode treeRoot)
        {
            bool   conversionSucceeded;
            object result;

            try
            {
                if (desiredType.IsArray)
                {
                    Node childNode = treeRoot.GetChildNode(paramName);

                    result = ConvertToArray(desiredType, paramName, childNode, out conversionSucceeded);
                }
                else
                {
                    result = ConvertToSimpleValue(desiredType, paramName, treeRoot, out conversionSucceeded);
                }
            }
            catch (Exception ex)
            {
                // Something unexpected during convertion
                // throw new exception with paramName specified

                throw new BindingException(
                          "Exception converting param '" + paramName + "' to " + desiredType + ". Check inner exception for details", ex);
            }

            return(result);
        }
示例#9
0
        public object BindObject(Type targetType, string prefix, string excludedProperties, string allowedProperties,
                                 CompositeNode treeRoot)
        {
            if (targetType == null)
            {
                throw new ArgumentNullException("targetType");
            }
            if (prefix == null)
            {
                throw new ArgumentNullException("prefix");
            }
            if (treeRoot == null)
            {
                throw new ArgumentNullException("treeRoot");
            }

            errors        = new ArrayList();
            instanceStack = new Stack();
            prefixStack   = new Stack <string>();

            excludedPropertyList = CreateNormalizedList(excludedProperties);
            allowedPropertyList  = CreateNormalizedList(allowedProperties);

            return(InternalBindObject(targetType, prefix, treeRoot.GetChildNode(prefix)));
        }
示例#10
0
		public Node ProcessElement(XElement startEl)
		{
			if (IsComplex(startEl))
			{
				CompositeNode top = new CompositeNode(startEl.Name.LocalName);
				foreach (var attr in startEl.Attributes())
				{
					var leaf = new LeafNode(typeof(String), attr.Name.LocalName, attr.Value);
					top.AddChildNode(leaf);
				}
				foreach (var childEl in startEl.Elements())
				{
					var childNode = ProcessElement(childEl);
					top.AddChildNode(childNode);
				}

				return top;
			}
			else
			{
				LeafNode top = new LeafNode(typeof(String), "", "");
				return top;
			}

			
		}
示例#11
0
        public CompositeNode BuildSourceNode(NameValueCollection nameValueCollection)
        {
            var root = new CompositeNode("root");

            PopulateTree(root, nameValueCollection);

            return(root);
        }
		private static CompositeNode GetParamsNode(int expectedValue)
		{
			CompositeNode paramsNode = new CompositeNode("root");
			IndexedNode listNode = new IndexedNode("myList");
			paramsNode.AddChildNode(listNode);
			listNode.AddChildNode(new LeafNode(typeof(int), "", expectedValue));
			return paramsNode;
		}
        /// <summary>
        ///
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="prefix"></param>
        /// <returns></returns>
        public CompositeNode BuildSourceNode(IDataReader reader, String prefix)
        {
            var root = new CompositeNode("root");

            PopulateTree(root, reader, prefix);

            return(root);
        }
		/// <summary>
		/// 
		/// </summary>
		/// <param name="reader"></param>
		/// <param name="prefix"></param>
		/// <returns></returns>
		public CompositeNode BuildSourceNode(IDataReader reader, String prefix)
		{
			CompositeNode root = new CompositeNode("root");
			
			PopulateTree(root, reader, prefix);
			
			return root;
		}
示例#15
0
		public CompositeNode BuildSourceNode(NameValueCollection nameValueCollection)
		{
			var root = new CompositeNode("root");

			PopulateTree(root, nameValueCollection);

			return root;
		}
示例#16
0
		public void PopulateTree(CompositeNode root, HttpFileCollection fileCollection)
		{
			foreach (String key in fileCollection.Keys)
			{
				if (key == null) continue;

				HttpPostedFile value = fileCollection.Get(key);

				if (value == null) continue;

				ProcessNode(root, typeof (HttpPostedFile), key, value);
			}
		}
示例#17
0
        private IndexedNode GetOrCreateIndexedNode(CompositeNode parent, string nodeName)
        {
            Node node = parent.GetChildNode(nodeName);

            if (node != null && node.NodeType != NodeType.Indexed)
            {
                throw new BindingException("Attempt to create or obtain an indexed node " +
                                           "named {0}, but a node with the same exists with the type {1}", nodeName, node.NodeType);
            }

            if (node == null)
            {
                node = new IndexedNode(nodeName);
                parent.AddChildNode(node);
            }

            return((IndexedNode)node);
        }
示例#18
0
        public void PopulateTree(CompositeNode root, HttpFileCollection fileCollection)
        {
            foreach (String key in fileCollection.Keys)
            {
                if (key == null)
                {
                    continue;
                }

                HttpPostedFile value = fileCollection.Get(key);

                if (value == null)
                {
                    continue;
                }

                ProcessNode(root, typeof(HttpPostedFile), key, value);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="root"></param>
        /// <param name="reader"></param>
        /// <param name="prefix"></param>
        public void PopulateTree(CompositeNode root, IDataReader reader, String prefix)
        {
            string[] fields = GetFields(reader);

            int[] indexesToSkip = FindDuplicateFields(fields);

            var indexNode = new IndexedNode(prefix);

            int row = 0;

            while (reader.Read())
            {
                var node = new CompositeNode(row.ToString());

                for (int i = 0; i < reader.FieldCount; i++)
                {
                    // Is in the skip list?
                    if (Array.IndexOf(indexesToSkip, i) >= 0)
                    {
                        continue;
                    }

                    // Is null?
                    if (reader.IsDBNull(i))
                    {
                        continue;
                    }

                    Type fieldType = reader.GetFieldType(i);

                    node.AddChildNode(new LeafNode(fieldType, fields[i], reader.GetValue(i)));
                }

                indexNode.AddChildNode(node);

                row++;
            }

            root.AddChildNode(indexNode);
        }
示例#20
0
        protected bool CheckForValidationFailures(object instance, Type instanceType,
                                                  PropertyInfo prop, CompositeNode node,
                                                  string name, string prefix,
                                                  ErrorSummary summary)
        {
            object value = null;

            if (validator == null)
            {
                return(false);
            }

            IValidator[] validators = validator.GetValidators(instanceType, prop);

            if (validators.Length != 0)
            {
                Node valNode = node.GetChildNode(name);

                if (valNode != null && valNode.NodeType == NodeType.Leaf)
                {
                    value = ((LeafNode)valNode).Value;
                }

                if (value == null && IsDateTimeType(prop.PropertyType))
                {
                    bool conversionSucceeded;
                    value = TryGetDateWithUTCFormat(node, name, out conversionSucceeded);
                }

                if (value == null && valNode == null)
                {
                    // Value was not present on the data source. Skip validation
                    return(false);
                }
            }

            return(CheckForValidationFailures(instance, instanceType, prop, value, name, prefix, summary));
        }
示例#21
0
        public void PopulateTree(CompositeNode root, NameValueCollection nameValueCollection)
        {
            foreach (String key in nameValueCollection.Keys)
            {
                if (key == null)
                {
                    continue;
                }
                string   singleKeyName = NormalizeKey(key);
                String[] values        = nameValueCollection.GetValues(key);

                if (values == null)
                {
                    continue;
                }

                if (values.Length == 1 && key.EndsWith("[]"))
                {
                    if (values[0] == string.Empty)
                    {
                        ProcessNode(root, typeof(String[]), singleKeyName, new string[0]);
                    }
                    else
                    {
                        values = values[0].Split(',');
                        ProcessNode(root, typeof(String[]), singleKeyName, values);
                    }
                }
                else if (values.Length == 1)
                {
                    ProcessNode(root, typeof(String), key, values[0]);
                }
                else
                {
                    ProcessNode(root, typeof(String[]), singleKeyName, values);
                }
            }
        }
示例#22
0
        private string TryGetDateWithUTCFormat(CompositeNode treeRoot, string paramName, out bool conversionSucceeded)
        {
            // YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)
            string fullDateTime = "";

            conversionSucceeded = false;

            Node dayNode   = treeRoot.GetChildNode(paramName + "day");
            Node monthNode = treeRoot.GetChildNode(paramName + "month");
            Node yearNode  = treeRoot.GetChildNode(paramName + "year");

            Node hourNode   = treeRoot.GetChildNode(paramName + "hour");
            Node minuteNode = treeRoot.GetChildNode(paramName + "minute");
            Node secondNode = treeRoot.GetChildNode(paramName + "second");

            if (dayNode != null)
            {
                var day   = (int)RelaxedConvertLeafNode(typeof(int), dayNode, 0);
                var month = (int)RelaxedConvertLeafNode(typeof(int), monthNode, 0);
                var year  = (int)RelaxedConvertLeafNode(typeof(int), yearNode, 0);

                fullDateTime        = string.Format("{0:0000}-{1:00}-{2:00}", year, month, day);
                conversionSucceeded = true;
            }

            if (hourNode != null)
            {
                var hour   = (int)RelaxedConvertLeafNode(typeof(int), hourNode, 0);
                var minute = (int)RelaxedConvertLeafNode(typeof(int), minuteNode, 0);
                var second = (int)RelaxedConvertLeafNode(typeof(int), secondNode, 0);

                fullDateTime       += string.Format("T{0:00}:{1:00}:{2:00}", hour, minute, second);
                conversionSucceeded = true;
            }

            return(fullDateTime == "" ? null : fullDateTime);
        }
示例#23
0
        public void BindObjectInstance(object instance, string prefix, string excludedProperties, string allowedProperties,
                                       CompositeNode treeRoot)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }
            if (prefix == null)
            {
                throw new ArgumentNullException("prefix");
            }
            if (treeRoot == null)
            {
                throw new ArgumentNullException("treeRoot");
            }

            errors        = new ArrayList();
            instanceStack = new Stack();
            prefixStack   = new Stack <string>();

            excludedPropertyList = CreateNormalizedList(excludedProperties);
            allowedPropertyList  = CreateNormalizedList(allowedProperties);

            if (instance != null)
            {
                var instanceType = instance.GetType();
                if (IsGenericList(instanceType))
                {
                    bool success;
                    var  elemType = instanceType.GetGenericArguments()[0];
                    ConvertToGenericList((IList)instance, elemType, prefix, treeRoot.GetChildNode(prefix), out success);
                }
            }

            InternalRecursiveBindObjectInstance(instance, prefix, treeRoot.GetChildNode(prefix));
        }
示例#24
0
		private bool IsPropertyExpected(PropertyInfo prop, CompositeNode node)
		{
			var propId = string.Format("{0}.{1}", node.FullName, prop.Name);

			if (expectCollPropertiesList != null)
			{
				return Array.BinarySearch(expectCollPropertiesList, propId, CaseInsensitiveComparer.Default) >= 0;
			}

			return false;
		}
示例#25
0
		public object BindObject(Type targetType, string prefix, string exclude, string allow, string expect,
								 CompositeNode treeRoot)
		{
			expectCollPropertiesList = CreateNormalizedList(expect);

			return BindObject(targetType, prefix, exclude, allow, treeRoot);
		}
示例#26
0
		private string TryGetDateWithUTCFormat(CompositeNode treeRoot, string paramName, out bool conversionSucceeded)
		{
			// YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)
			string fullDateTime = "";
			conversionSucceeded = false;

			Node dayNode = treeRoot.GetChildNode(paramName + "day");
			Node monthNode = treeRoot.GetChildNode(paramName + "month");
			Node yearNode = treeRoot.GetChildNode(paramName + "year");

			Node hourNode = treeRoot.GetChildNode(paramName + "hour");
			Node minuteNode = treeRoot.GetChildNode(paramName + "minute");
			Node secondNode = treeRoot.GetChildNode(paramName + "second");

			if (dayNode != null)
			{
				int day = (int) RelaxedConvertLeafNode(typeof(int), dayNode, 0);
				int month = (int) RelaxedConvertLeafNode(typeof(int), monthNode, 0);
				int year = (int) RelaxedConvertLeafNode(typeof(int), yearNode, 0);

				fullDateTime = string.Format("{0:0000}-{1:00}-{2:00}", year, month, day);
				conversionSucceeded = true;
			}

			if (hourNode != null)
			{
				int hour = (int) RelaxedConvertLeafNode(typeof(int), hourNode, 0);
				int minute = (int) RelaxedConvertLeafNode(typeof(int), minuteNode, 0);
				int second = (int) RelaxedConvertLeafNode(typeof(int), secondNode, 0);

				fullDateTime += string.Format("T{0:00}:{1:00}:{2:00}", hour, minute, second);
				conversionSucceeded = true;
			}

			return fullDateTime == "" ? null : fullDateTime;
		}
示例#27
0
		protected virtual void BeforeBindingProperty(object instance, PropertyInfo prop, string prefix, CompositeNode node)
		{
		}
示例#28
0
		protected void InternalRecursiveBindObjectInstance(object instance, String prefix, CompositeNode node)
		{
			if (node == null || instance == null)
			{
				return;
			}

			BeforeBinding(instance, prefix, node);

			if (PerformCustomBinding(instance, prefix, node))
			{
				return;
			}

			PushInstance(instance, prefix);

			ErrorSummary summary = new ErrorSummary();

			validationErrorSummaryPerInstance[instance] = summary;

			Type instanceType = instance.GetType();

			PropertyInfo[] props = instanceType.GetProperties(PropertiesBindingFlags);

			string nodeFullName = node.FullName;

			foreach(PropertyInfo prop in props)
			{
				if (ShouldIgnoreProperty(prop, nodeFullName))
				{
					continue;
				}

				Type propType = prop.PropertyType;
				String paramName = prop.Name;

				String translatedParamName = Translate(instanceType, paramName);

				if (translatedParamName == null)
				{
					continue;
				}

				bool isSimpleProperty = IsSimpleProperty(propType);

				// There are some caveats by running the validators here. 
				// We should follow the validator's execution order...
				if (isSimpleProperty)
				{
					if (CheckForValidationFailures(instance, instanceType, prop, node, translatedParamName, prefix, summary))
					{
						continue;
					}
				}

				BeforeBindingProperty(instance, prop, prefix, node);

				try
				{
					bool conversionSucceeded;

					if (isSimpleProperty)
					{
						object value = ConvertToSimpleValue(propType, translatedParamName, node, out conversionSucceeded);

						if (conversionSucceeded)
						{
							SetPropertyValue(instance, prop, value);
						}
					}
					else
					{
						// if the property is an object, we look if it is already instanciated
						object value = prop.GetValue(instance, null);

						Node nestedNode = node.GetChildNode(paramName);

						if (nestedNode != null)
						{
							if (ShouldRecreateInstance(value, propType, paramName, nestedNode))
							{
								value = InternalBindObject(propType, paramName, nestedNode, out conversionSucceeded);

								if (conversionSucceeded)
								{
									SetPropertyValue(instance, prop, value);
								}
							}
							else
							{
								InternalRecursiveBindObjectInstance(value, paramName, nestedNode);
							}
						}

						CheckForValidationFailures(instance, instanceType, prop, value, translatedParamName, prefix, summary);
					}
				}
				catch(Exception ex)
				{
					errors.Add(new DataBindError(prefix, prop.Name, ex));
				}
			}

			PopInstance(instance, prefix);

			AfterBinding(instance, prefix, node);
		}
示例#29
0
		public void BindObjectInstance(object instance, string prefix, CompositeNode treeRoot)
		{
			BindObjectInstance(instance, prefix, null, null, treeRoot);
		}
示例#30
0
		public object BindObject(Type targetType, string prefix, CompositeNode treeRoot)
		{
			return BindObject(targetType, prefix, null, null, treeRoot);
		}
示例#31
0
 protected virtual void BeforeBindingProperty(object instance, PropertyInfo prop, string prefix, CompositeNode node)
 {
 }
示例#32
0
        protected void ProcessNode(CompositeNode node, Type type, String name, object value)
        {
            if (name == null || name == String.Empty)
            {
                // Ignore
                return;
            }
            if (name[0] == '.' || name[0] == '[' || name[0] == ']')
            {
                AddLeafNode(node, type, name, value);
                return;
            }

            int dotIndex          = name.IndexOf('.');
            int startBracketIndex = name.IndexOf('[');

            if (dotIndex != -1 && (startBracketIndex == -1 || dotIndex < startBracketIndex))
            {
                // Child node

                String childNodeName = name.Substring(0, dotIndex);

                CompositeNode newNode = GetOrCreateCompositeNode(node, childNodeName);

                ProcessNode(newNode, type, name.Substring(dotIndex + 1), value);
            }
            else if (startBracketIndex != -1)
            {
                // Indexed node

                int endBracket = name.IndexOf(']');

                if (endBracket == -1)
                {
                    // TODO: Something is wrong
                }

                String enclosed = name.Substring(startBracketIndex + 1, endBracket - startBracketIndex - 1);

                if (enclosed == null || enclosed == String.Empty)
                {
                    // TODO: Something is wrong
                }

                String indexedNodeName = name.Substring(0, startBracketIndex);

                CompositeNode newNode = GetOrCreateIndexedNode(node, indexedNodeName);

                if (endBracket + 1 == name.Length)                 // entries like emails[0] = value
                {
                    AddLeafNode(newNode, type, value);
                }
                else
                {
                    name = name.Substring(endBracket + 2);                     // entries like customer[0].name = value

                    newNode = GetOrCreateCompositeNode(newNode, enclosed);

                    ProcessNode(newNode, type, name, value);
                }
            }
            else
            {
                AddLeafNode(node, type, name, value);
            }
        }
		public void BindObjectInstance(object instance, CompositeNode treeRoot)
		{
			BindObjectInstance(instance, "", null, null, treeRoot);
		}
示例#34
0
 private void AddLeafNode(CompositeNode parent, Type type, object value)
 {
     AddLeafNode(parent, type, String.Empty, value);
 }
示例#35
0
		public object BindParameter(Type desiredType, String paramName, CompositeNode treeRoot)
		{
			bool conversionSucceeded;
			object result;

			try
			{
				if (desiredType.IsArray)
				{
					Node childNode = treeRoot.GetChildNode(paramName);

					result = ConvertToArray(desiredType, paramName, childNode, out conversionSucceeded);
				}
				else
				{
					result = ConvertToSimpleValue(desiredType, paramName, treeRoot, out conversionSucceeded);
				}
			}
			catch(Exception ex)
			{
				// Something unexpected during convertion
				// throw new exception with paramName specified

				throw new BindingException(
					"Exception converting param '" + paramName + "' to " + desiredType + ". Check inner exception for details", ex);
			}

			return result;
		}
示例#36
0
        protected void InternalRecursiveBindObjectInstance(object instance, String prefix, CompositeNode node)
        {
            if (node == null || instance == null)
            {
                return;
            }

            BeforeBinding(instance, prefix, node);

            if (PerformCustomBinding(instance, prefix, node))
            {
                return;
            }

            PushInstance(instance, prefix);

            var summary = new ErrorSummary();

            validationErrorSummaryPerInstance[instance] = summary;

            Type instanceType = instance.GetType();

            PropertyInfo[] props = instanceType.GetProperties(PropertiesBindingFlags);

            string nodeFullName = node.FullName;

            foreach (PropertyInfo prop in props)
            {
                if (ShouldIgnoreProperty(string.Format("{0}.{1}", nodeFullName, prop.Name)))
                {
                    continue;
                }

                Type   propType  = prop.PropertyType;
                String paramName = prop.Name;

                String translatedParamName = Translate(instanceType, paramName);

                if (translatedParamName == null)
                {
                    continue;
                }

                bool isSimpleProperty = IsSimpleProperty(propType);

                if (isSimpleProperty && prop.CanWrite == false)
                {
                    continue;
                }

                BeforeBindingProperty(instance, prop, prefix, node);

                try
                {
                    bool conversionSucceeded;

                    if (isSimpleProperty)
                    {
                        object value = ConvertToSimpleValue(propType, translatedParamName, node, out conversionSucceeded);

                        if (conversionSucceeded)
                        {
                            SetPropertyValue(instance, prop, value);
                        }
                    }
                    else
                    {
                        // if the property is an object, we look if it is already instantiated
                        Node nestedNode = node.GetChildNode(paramName);

                        if (nestedNode != null)
                        {
                            object value = prop.GetValue(instance, null);

                            if (ShouldRecreateInstance(value, propType, paramName, nestedNode))
                            {
                                value = InternalBindObject(propType, paramName, nestedNode, out conversionSucceeded);

                                if (conversionSucceeded)
                                {
                                    SetPropertyValue(instance, prop, value);
                                }
                            }
                            else
                            {
                                InternalRecursiveBindObjectInstance(value, paramName, nestedNode);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    errors.Add(new DataBindError(prefix, prop.Name, ex));
                }
            }

            CheckForValidationFailures(instance, prefix, node, summary);

            PopInstance(instance, prefix);

            AfterBinding(instance, prefix, node);
        }
示例#37
0
		public object BindObject(Type targetType, string prefix, string excludedProperties, string allowedProperties,
		                         CompositeNode treeRoot)
		{
			if (targetType == null)
			{
				throw new ArgumentNullException("targetType");
			}
			if (prefix == null)
			{
				throw new ArgumentNullException("prefix");
			}
			if (treeRoot == null)
			{
				throw new ArgumentNullException("treeRoot");
			}

			errors = new ArrayList();
			instanceStack = new Stack();
			prefixStack = new Stack<string>();

			excludedPropertyList = CreateNormalizedList(excludedProperties);
			allowedPropertyList = CreateNormalizedList(allowedProperties);

			return InternalBindObject(targetType, prefix, treeRoot.GetChildNode(prefix));
		}
示例#38
0
		private void AddLeafNode(CompositeNode parent, Type type, String nodeName, object value)
		{
			parent.AddChildNode(new LeafNode(type, nodeName, value));
		}
示例#39
0
		public void BindObjectInstance(object instance, string prefix, string excludedProperties, string allowedProperties,
		                               CompositeNode treeRoot)
		{
			if (instance == null)
			{
				throw new ArgumentNullException("instance");
			}
			if (prefix == null)
			{
				throw new ArgumentNullException("prefix");
			}
			if (treeRoot == null)
			{
				throw new ArgumentNullException("treeRoot");
			}

			errors = new ArrayList();
			instanceStack = new Stack();
			prefixStack = new Stack<string>();

			excludedPropertyList = CreateNormalizedList(excludedProperties);
			allowedPropertyList = CreateNormalizedList(allowedProperties);

			InternalRecursiveBindObjectInstance(instance, prefix, treeRoot.GetChildNode(prefix));
		}
示例#40
0
		private IndexedNode GetOrCreateIndexedNode(CompositeNode parent, string nodeName)
		{
			Node node = parent.GetChildNode(nodeName);

			if (node != null && node.NodeType != NodeType.Indexed)
			{
				throw new BindingException("Attempt to create or obtain an indexed node " +
				                           "named {0}, but a node with the same exists with the type {1}", nodeName, node.NodeType);
			}

			if (node == null)
			{
				node = new IndexedNode(nodeName);
				parent.AddChildNode(node);
			}

			return (IndexedNode) node;
		}
示例#41
0
		protected bool CheckForValidationFailures(object instance, Type instanceType,
		                                          PropertyInfo prop, CompositeNode node,
		                                          string name, string prefix,
		                                          ErrorSummary summary)
		{
			object value = null;

			if (validator == null)
			{
				return false;
			}

			IValidator[] validators = validator.GetValidators(instanceType, prop);

			if (validators.Length != 0)
			{
				Node valNode = node.GetChildNode(name);

				if (valNode != null && valNode.NodeType == NodeType.Leaf)
				{
					value = ((LeafNode)valNode).Value;
				}

				if (value == null && IsDateTimeType(prop.PropertyType))
				{
					bool conversionSucceeded;
					value = TryGetDateWithUTCFormat(node, name, out conversionSucceeded);
				}

				if (value == null && valNode == null)
				{
					// Value was not present on the data source. Skip validation
					return false;
				}
			}

			return CheckForValidationFailures(instance, instanceType, prop, value, name, prefix, summary);
		}
示例#42
0
 public void BindObjectInstance(object instance, string prefix, CompositeNode treeRoot)
 {
     BindObjectInstance(instance, prefix, null, null, treeRoot);
 }
示例#43
0
		private object ConvertToSimpleValue(Type desiredType, string key, CompositeNode parent, out bool conversionSucceeded)
		{
			conversionSucceeded = false;

			Node childNode = parent.GetChildNode(key);

			if (childNode == null && IsDateTimeType(desiredType))
			{
				return TrySpecialDateTimeBinding(desiredType, parent, key, out conversionSucceeded);
			}
			else if (childNode == null)
			{
				return null;
			}
			else if (childNode.NodeType == NodeType.Leaf)
			{
				return ConvertLeafNode(desiredType, (LeafNode) childNode, out conversionSucceeded);
			}
			else
			{
				throw new BindingException("Could not convert param as the node related " +
				                           "to the param is not a leaf node. Param {0} parent node: {1}", key, parent.Name);
			}
		}
示例#44
0
 public object BindObject(Type targetType, string prefix, CompositeNode treeRoot)
 {
     return(BindObject(targetType, prefix, null, null, treeRoot));
 }
示例#45
0
		private object TrySpecialDateTimeBinding(Type desiredType, CompositeNode treeRoot,
		                                         String paramName, out bool conversionSucceeded)
		{
			string dateUtc = TryGetDateWithUTCFormat(treeRoot, paramName, out conversionSucceeded);

			if (dateUtc != null)
			{
				conversionSucceeded = true;

				DateTime dt = DateTime.Parse(dateUtc);

				if (desiredType.Name == "NullableDateTime")
				{
					TypeConverter typeConverter = TypeDescriptor.GetConverter(desiredType);

					return typeConverter.ConvertFrom(dateUtc);
				}
				else
				{
					return DateTime.Parse(dateUtc);
				}
			}

			conversionSucceeded = false;
			return null;
		}
示例#46
0
		protected void ProcessNode(CompositeNode node, Type type, String name, object value)
		{
			if (name == null || name == String.Empty)
			{
				// Ignore
				return;
			}
			if (name[0] == '.' || name[0] == '[' || name[0] == ']')
			{
				AddLeafNode(node, type, name, value);
				return;
			}

			int dotIndex = name.IndexOf('.');
			int startBracketIndex = name.IndexOf('[');

			if (dotIndex != -1 && (startBracketIndex == -1 || dotIndex < startBracketIndex))
			{
				// Child node

				String childNodeName = name.Substring(0, dotIndex);

				CompositeNode newNode = GetOrCreateCompositeNode(node, childNodeName);

				ProcessNode(newNode, type, name.Substring(dotIndex + 1), value);
			}
			else if (startBracketIndex != -1)
			{
				// Indexed node

				int endBracket = name.IndexOf(']');

				if (endBracket == -1)
				{
					// TODO: Something is wrong
				}

				String enclosed = name.Substring(startBracketIndex + 1, endBracket - startBracketIndex - 1);

				if (enclosed == null || enclosed == String.Empty)
				{
					// TODO: Something is wrong
				}

				String indexedNodeName = name.Substring(0, startBracketIndex);

				CompositeNode newNode = GetOrCreateIndexedNode(node, indexedNodeName);

				if (endBracket + 1 == name.Length) // entries like emails[0] = value
				{
					AddLeafNode(newNode, type, value);
				}
				else
				{
					name = name.Substring(endBracket + 2); // entries like customer[0].name = value

					newNode = GetOrCreateCompositeNode(newNode, enclosed);

					ProcessNode(newNode, type, name, value);
				}
			}
			else
			{
				AddLeafNode(node, type, name, value);
			}
		}
示例#47
0
		protected override void BeforeBindingProperty(object instance, PropertyInfo prop, string prefix,
													  CompositeNode node)
		{
			base.BeforeBindingProperty(instance, prop, prefix, node);

			if (IsPropertyExpected(prop, node))
			{
				ClearExpectedCollectionProperties(instance, prop);
			}
		}
示例#48
0
		public bool CanBindObject(Type targetType, String prefix, CompositeNode treeRoot)
		{
			Node childNode = treeRoot.GetChildNode(prefix);

			return childNode != null;
		}
示例#49
0
		private object ObtainPrimaryKeyValue(ActiveRecordModel model, CompositeNode node, String prefix,
											 out PrimaryKeyModel pkModel)
		{
			pkModel = ObtainPrimaryKey(model);

			var pkPropName = pkModel.Property.Name;

			var idNode = node.GetChildNode(pkPropName);

			if (idNode == null) return null;

			if (idNode != null && idNode.NodeType != NodeType.Leaf)
			{
				throw new BindingException("Expecting leaf node to contain id for ActiveRecord class. " +
										   "Prefix: {0} PK Property Name: {1}", prefix, pkPropName);
			}

			var lNode = (LeafNode) idNode;

			if (lNode == null)
			{
				throw new BindingException("ARDataBinder autoload failed as element {0} " +
										   "doesn't have a primary key {1} value", prefix, pkPropName);
			}

			bool conversionSuc;

			return Converter.Convert(pkModel.Property.PropertyType, lNode.ValueType, lNode.Value, out conversionSuc);
		}
示例#50
0
 private void AddLeafNode(CompositeNode parent, Type type, String nodeName, object value)
 {
     parent.AddChildNode(new LeafNode(type, nodeName, value));
 }
示例#51
0
		private void AddLeafNode(CompositeNode parent, Type type, object value)
		{
			AddLeafNode(parent, type, String.Empty, value);
		}
示例#52
0
        public bool CanBindObject(Type targetType, String prefix, CompositeNode treeRoot)
        {
            Node childNode = treeRoot.GetChildNode(prefix);

            return(childNode != null);
        }