private object Aggregate(object[] args, string name)
        {
            object result;
            string predicate = args.First().ToString();
            var    values    = args.Skip(1).ToArray();
            var    query     = (IQueryable <object>) this.Select(predicate, values);
            object firstItem = query.FirstOrDefault();

            if (firstItem == null)
            {
                result = new DynamicNull();
            }
            else
            {
                var types = from i in query
                            group i by i.GetType() into g
                                where g.Key != typeof(DynamicNull)
                            orderby g.Count() descending
                            select new { g, Instances = g.Count() };
                var dominantType = types.First().g.Key;
                //remove items that are not the dominant type
                //e.g. string,string,string,string,false[DynamicNull],string
                var itemsOfDominantTypeOnly = query.ToList();
                itemsOfDominantTypeOnly.RemoveAll(item => !item.GetType().IsAssignableFrom(dominantType));
                if (dominantType == typeof(string))
                {
                    throw new ArgumentException("Can only use aggregate methods on properties which are numeric");
                }
                else if (dominantType == typeof(int))
                {
                    List <int> data = (List <int>)itemsOfDominantTypeOnly.Cast <int>().ToList();
                    return(Aggregate <int>(data, name));
                }
                else if (dominantType == typeof(decimal))
                {
                    List <decimal> data = (List <decimal>)itemsOfDominantTypeOnly.Cast <decimal>().ToList();
                    return(Aggregate <decimal>(data, name));
                }
                else if (dominantType == typeof(bool))
                {
                    throw new ArgumentException("Can only use aggregate methods on properties which are numeric or datetime");
                }
                else if (dominantType == typeof(DateTime))
                {
                    if (name != "Min" || name != "Max")
                    {
                        throw new ArgumentException("Can only use aggregate min or max methods on properties which are datetime");
                    }
                    List <DateTime> data = (List <DateTime>)itemsOfDominantTypeOnly.Cast <DateTime>().ToList();
                    return(Aggregate <DateTime>(data, name));
                }
                else
                {
                    result = query.ToList();
                }
            }
            return(result);
        }
예제 #2
0
        private dynamic DocumentByIds(IPublishedStore store, params string[] ids)
        {
            var dNull = new DynamicNull();
            var nodes = ids.Select(eachId => DocumentById(eachId, store, dNull))
                        .Where(x => !TypeHelper.IsTypeAssignableFrom <DynamicNull>(x))
                        .Cast <DynamicPublishedContent>();

            return(new DynamicPublishedContentList(nodes));
        }
예제 #3
0
파일: IoOps.cs 프로젝트: ltwlf/IronSP
        public static MutableString /*!*/ Read(RubyIO /*!*/ self, DynamicNull bytes, [DefaultProtocol, Optional] MutableString buffer)
        {
            if (buffer == null)
            {
                buffer = MutableString.CreateBinary();
            }
            else
            {
                buffer.Clear();
            }

            self.AppendBytes(buffer, Int32.MaxValue);
            return(buffer);
        }
        public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
        {
            int index = (int)indexes[0];

            try
            {
                result = this.Items.ElementAt(index);
                return(true);
            }
            catch (IndexOutOfRangeException)
            {
                result = new DynamicNull();
                return(true);
            }
        }
        /// <summary>
        /// Checks if the object is DynamicXml or DynamicNull and ensures that we return the legacy class not the new one
        /// as we want this class to always ensure we're dealing with the legacy classes
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        internal static object ConvertToLegacy(object result)
        {
            if (result is Umbraco.Core.Dynamics.DynamicXml)
            {
                result = new DynamicXml(((Umbraco.Core.Dynamics.DynamicXml)result).BaseElement);
            }
            else if (result is Umbraco.Core.Dynamics.DynamicNull)
            {
                result = new DynamicNull();
            }
            else if (result is Umbraco.Core.Dynamics.DynamicDictionary)
            {
                result = new DynamicDictionary(((Umbraco.Core.Dynamics.DynamicDictionary)result).SourceItems);
            }

            return(result);
        }
예제 #6
0
		/// <summary>
		/// Checks if the object is DynamicXml or DynamicNull and ensures that we return the legacy class not the new one 
		/// as we want this class to always ensure we're dealing with the legacy classes
		/// </summary>
		/// <param name="result"></param>
		/// <returns></returns>
		internal static object ConvertToLegacy(object result)
		{
			if (result is Umbraco.Core.Dynamics.DynamicXml)
			{
                result = new DynamicXml(((Umbraco.Core.Dynamics.DynamicXml)result).BaseElement);
			}
			else if (result is Umbraco.Core.Dynamics.DynamicNull)
			{
				result = new DynamicNull();
			}
			else if (result is Umbraco.Core.Dynamics.DynamicDictionary)
			{
				result = new DynamicDictionary(((Umbraco.Core.Dynamics.DynamicDictionary) result).SourceItems);
			}
			
			return result;
		}
예제 #7
0
        /// <summary>
        /// Attempts to call a method on the dynamic object
        /// </summary>
        /// <param name="binder"></param>
        /// <param name="args"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            var attempt = DynamicInstanceHelper.TryInvokeMember(this, binder, args, new[]
            {
                typeof(DynamicPublishedContent)
            });

            if (attempt.Success)
            {
                result = attempt.Result.ObjectResult;

                //need to check the return type and possibly cast if result is from an extension method found
                if (attempt.Result.Reason == DynamicInstanceHelper.TryInvokeMemberSuccessReason.FoundExtensionMethod)
                {
                    //we don't need to cast if it is already DynamicPublishedContent
                    if (attempt.Result.ObjectResult != null && (!(attempt.Result.ObjectResult is DynamicPublishedContent)))
                    {
                        if (attempt.Result.ObjectResult is IPublishedContent)
                        {
                            result = new DynamicPublishedContent((IPublishedContent)attempt.Result.ObjectResult);
                        }
                        else if (attempt.Result.ObjectResult is IEnumerable <DynamicPublishedContent> )
                        {
                            result = new DynamicPublishedContentList((IEnumerable <DynamicPublishedContent>)attempt.Result.ObjectResult);
                        }
                        else if (attempt.Result.ObjectResult is IEnumerable <IPublishedContent> )
                        {
                            result = new DynamicPublishedContentList((IEnumerable <IPublishedContent>)attempt.Result.ObjectResult);
                        }
                    }
                }
                return(true);
            }

            //this is the result of an extension method execution gone wrong so we return dynamic null
            if (attempt.Result.Reason == DynamicInstanceHelper.TryInvokeMemberSuccessReason.FoundExtensionMethod &&
                attempt.Error != null && attempt.Error is TargetInvocationException)
            {
                result = new DynamicNull();
                return(true);
            }

            result = null;
            return(false);
        }
예제 #8
0
        /// <summary>
        /// Try to return an object based on the dynamic member accessor
        /// </summary>
        /// <param name="binder"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        /// <remarks>
        /// TODO: SD: This will alwasy return true so that no exceptions are generated, this is only because this is how the
        /// old DynamicNode worked, I'm not sure if this is the correct/expected functionality but I've left it like that.
        /// IMO I think this is incorrect and it would be better to throw an exception for something that is not supported!
        /// </remarks>
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (binder == null)
            {
                throw new ArgumentNullException("binder");
            }

            var name = binder.Name;

            //check the cache first!
            if (_cachedMemberOutput.TryGetValue(name, out result))
            {
                return(true);
            }

            //loop through each member match method and execute it.
            //If it is successful, cache the result and return it.
            foreach (var attempt in GetMemberMatchMethods()
                     .Select(m => m(binder))
                     .Where(attempt => attempt.Success))
            {
                result = attempt.Result;
                //cache the result so we don't have to re-process the whole thing
                _cachedMemberOutput.TryAdd(name, result);
                return(true);
            }

            //if property access, type lookup and member invoke all failed
            //at this point, we're going to return null
            //instead, we return a DynamicNull - see comments in that file
            //this will let things like Model.ChildItem work and return nothing instead of crashing

            //.Where explictly checks for this type
            //and will make it false
            //which means backwards equality (&& property != true) will pass
            //forwwards equality (&& property or && property == true) will fail
            result = new DynamicNull();

            //alwasy return true if we haven't thrown an exception though I'm wondering if we return 'false' if .Net throws an exception for us??
            return(true);
        }
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            var property = Source.FirstOrDefault(s => s.Key.Equals(binder.Name));

			if (property != null)
			{
				switch (property.Type)
				{
					case "contentPicker":
						result = Repository.FindById(int.Parse(property.Value));
						break;
					case "mediaCurrent":
						result = Repository.FindMediaById(int.Parse(property.Value));
						break;
					default:
						result = property.Value;
						break;
				}
			}
			else
				result = new DynamicNull();

            return true;
        }
예제 #10
0
 public static MutableString Gets(RubyScope /*!*/ scope, object self, DynamicNull separator)
 {
     return(RubyIOOps.Gets(scope, scope.RubyContext.InputProvider.GetOrResetCurrentStream(), separator));
 }
예제 #11
0
 public static MutableString /*!*/ Read(RubyContext /*!*/ context, DynamicNull bytes, [DefaultProtocol, Optional] MutableString buffer)
 {
     return(RubyIOOps.Read(context.InputProvider.GetOrResetCurrentStream(), bytes, buffer));
 }
예제 #12
0
        private bool ConvertPropertyValueByDataType(ref object result, string name, Guid dataType)
        {
            //the resulting property is a string, but to support some of the nice linq stuff in .Where
            //we should really check some more types
            string sResult = string.Format("{0}", result).Trim();

            //boolean
            if (dataType == DATATYPE_YESNO_GUID)
            {
                bool parseResult;
                if (string.IsNullOrEmpty(string.Format("{0}", result)))
                {
                    result = false;
                    return true;
                }
                if (Boolean.TryParse(sResult.Replace("1", "true").Replace("0", "false"), out parseResult))
                {
                    result = parseResult;
                    return true;
                }
            }

            ////integer
            ////this will eat csv strings, so only do it if the decimal also includes a decimal seperator (according to the current culture)
            //if (dataType == DATATYPE_INTEGER_GUID)
            //{
            //    int iResult = 0;
            //    if (int.TryParse(sResult, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.CurrentCulture, out iResult))
            //    {
            //        result = iResult;
            //        return true;
            //    }
            //}

            //this will eat csv strings, so only do it if the decimal also includes a decimal seperator (according to the current culture)
            if (sResult.Contains(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator))
            {
                //decimal
                decimal dResult = 0;
                if (decimal.TryParse(sResult, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.CurrentCulture, out dResult))
                {
                    result = dResult;
                    return true;
                }
            }
            if (dataType == DATATYPE_DATETIMEPICKER_GUID || dataType == DATATYPE_DATEPICKER_GUID)
            {
                //date
                DateTime dtResult = DateTime.MinValue;
                if (DateTime.TryParse(string.Format("{0}", result), out dtResult))
                {
                    result = dtResult;
                    return true;
                }
                else
                {
                    result = new DynamicNull();
                    return true;
                }
            }

            // Rich text editor (return IHtmlString so devs doesn't need to decode html
            if (dataType == DATATYPE_TINYMCE_GUID)
            {
                result = new HtmlString(result.ToString());
                return true;
            }


            if (string.Equals("true", sResult, StringComparison.CurrentCultureIgnoreCase))
            {
                result = true;
                return true;
            }
            if (string.Equals("false", sResult, StringComparison.CurrentCultureIgnoreCase))
            {
                result = false;
                return true;
            }

            if (result != null)
            {
                //a really rough check to see if this may be valid xml
                if (sResult.StartsWith("<") && sResult.EndsWith(">") && sResult.Contains("/"))
                {
                    try
                    {
                        XElement e = XElement.Parse(DynamicXml.StripDashesInElementOrAttributeNames(sResult), LoadOptions.None);
                        if (e != null)
                        {
                            //check that the document element is not one of the disallowed elements
                            //allows RTE to still return as html if it's valid xhtml
                            string documentElement = e.Name.LocalName;
                            if (!UmbracoSettings.NotDynamicXmlDocumentElements.Any(tag =>
                                string.Equals(tag, documentElement, StringComparison.CurrentCultureIgnoreCase)))
                            {
                                result = new DynamicXml(e);
                                return true;
                            }
                            else
                            {
                                //we will just return this as a string
                                return true;
                            }
                        }
                    }
                    catch (Exception)
                    {
                        //we will just return this as a string
                        return true;
                    }

                }
            }

            return true;
        }
예제 #13
0
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            try
            {
                //Property?
                result = typeof(DynamicNode).InvokeMember(binder.Name,
                                                  System.Reflection.BindingFlags.Instance |
                                                  System.Reflection.BindingFlags.Public |
                                                  System.Reflection.BindingFlags.GetProperty,
                                                  null,
                                                  this,
                                                  args);
                return true;
            }
            catch (MissingMethodException)
            {
                try
                {
                    //Static or Instance Method?
                    result = typeof(DynamicNode).InvokeMember(binder.Name,
                                                  System.Reflection.BindingFlags.Instance |
                                                  System.Reflection.BindingFlags.Public |
                                                  System.Reflection.BindingFlags.Static |
                                                  System.Reflection.BindingFlags.InvokeMethod,
                                                  null,
                                                  this,
                                                  args);
                    return true;
                }
                catch (MissingMethodException)
                {
                    try
                    {
                        result = ExecuteExtensionMethod(args, binder.Name, false);
                        return true;
                    }
                    catch (TargetInvocationException)
                    {
                        result = new DynamicNull();
                        return true;
                    }

                    catch
                    {
                        result = null;
                        return false;
                    }

                }


            }
            catch
            {
                result = null;
                return false;
            }

        }
예제 #14
0
		/// <summary>
		/// Attempts to call a method on the dynamic object
		/// </summary>
		/// <param name="binder"></param>
		/// <param name="args"></param>
		/// <param name="result"></param>
		/// <returns></returns>
		public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
		{
			//TODO: We MUST cache the result here, it is very expensive to keep finding extension methods!

			try
			{
				//Property?
				result = typeof(DynamicPublishedContent).InvokeMember(binder.Name,
												  System.Reflection.BindingFlags.Instance |
												  System.Reflection.BindingFlags.Public |
												  System.Reflection.BindingFlags.GetProperty,
												  null,
												  this,
												  args);
				return true;
			}
			catch (MissingMethodException)
			{
				try
				{
					//Static or Instance Method?
					result = typeof(DynamicPublishedContent).InvokeMember(binder.Name,
												  System.Reflection.BindingFlags.Instance |
												  System.Reflection.BindingFlags.Public |
												  System.Reflection.BindingFlags.Static |
												  System.Reflection.BindingFlags.InvokeMethod,
												  null,
												  this,
												  args);
					return true;
				}
				catch (MissingMethodException)
				{
					try
					{
						result = ExecuteExtensionMethod(args, binder.Name);
						return true;
					}
					catch (TargetInvocationException)
					{
						result = new DynamicNull();
						return true;
					}

					catch
					{
						//TODO: LOg this!

						result = null;
						return false;
					}

				}


			}
			catch
			{
				result = null;
				return false;
			}

		}
 public HtmlString StripHtml(DynamicNull html)
 {
     return(new HtmlString(string.Empty));
 }
 public dynamic MediaById(DynamicNull Id)
 {
     return(new DynamicNull());
 }
 public IHtmlString Truncate(DynamicNull html, int length, bool addElipsis)
 {
     return(new HtmlString(string.Empty));
 }
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            //TODO: Nowhere here are we checking if args is the correct length!

            //NOTE: For many of these we could actually leave them out since we are executing custom extension methods and because
            // we implement IEnumerable<T> they will execute just fine, however, to do that will be quite a bit slower than checking here.

            var firstArg = args.FirstOrDefault();

            //this is to check for 'DocumentTypeAlias' vs 'NodeTypeAlias' for compatibility
            if (firstArg != null && firstArg.ToString().InvariantStartsWith("NodeTypeAlias"))
            {
                firstArg = "DocumentTypeAlias" + firstArg.ToString().Substring("NodeTypeAlias".Length);
            }

            var name = binder.Name;

            if (name == "Single")
            {
                string predicate = firstArg == null ? "" : firstArg.ToString();
                var    values    = predicate.IsNullOrWhiteSpace() ? new object[] {} : args.Skip(1).ToArray();
                var    single    = this.Single <DynamicPublishedContent>(predicate, values);
                result = new DynamicPublishedContent(single);
                return(true);
            }
            if (name == "SingleOrDefault")
            {
                string predicate = firstArg == null ? "" : firstArg.ToString();
                var    values    = predicate.IsNullOrWhiteSpace() ? new object[] { } : args.Skip(1).ToArray();
                var    single    = this.SingleOrDefault <DynamicPublishedContent>(predicate, values);
                if (single == null)
                {
                    result = new DynamicNull();
                }
                else
                {
                    result = new DynamicPublishedContent(single);
                }
                return(true);
            }
            if (name == "First")
            {
                string predicate = firstArg == null ? "" : firstArg.ToString();
                var    values    = predicate.IsNullOrWhiteSpace() ? new object[] { } : args.Skip(1).ToArray();
                var    first     = this.First <DynamicPublishedContent>(predicate, values);
                result = new DynamicPublishedContent(first);
                return(true);
            }
            if (name == "FirstOrDefault")
            {
                string predicate = firstArg == null ? "" : firstArg.ToString();
                var    values    = predicate.IsNullOrWhiteSpace() ? new object[] { } : args.Skip(1).ToArray();
                var    first     = this.FirstOrDefault <DynamicPublishedContent>(predicate, values);
                if (first == null)
                {
                    result = new DynamicNull();
                }
                else
                {
                    result = new DynamicPublishedContent(first);
                }
                return(true);
            }
            if (name == "Last")
            {
                string predicate = firstArg == null ? "" : firstArg.ToString();
                var    values    = predicate.IsNullOrWhiteSpace() ? new object[] { } : args.Skip(1).ToArray();
                var    last      = this.Last <DynamicPublishedContent>(predicate, values);
                result = new DynamicPublishedContent(last);
                return(true);
            }
            if (name == "LastOrDefault")
            {
                string predicate = firstArg == null ? "" : firstArg.ToString();
                var    values    = predicate.IsNullOrWhiteSpace() ? new object[] { } : args.Skip(1).ToArray();
                var    last      = this.LastOrDefault <DynamicPublishedContent>(predicate, values);
                if (last == null)
                {
                    result = new DynamicNull();
                }
                else
                {
                    result = new DynamicPublishedContent(last);
                }
                return(true);
            }
            if (name == "Where")
            {
                string predicate = firstArg.ToString();
                var    values    = args.Skip(1).ToArray();
                //TODO: We are pre-resolving the where into a ToList() here which will have performance impacts if there where clauses
                // are nested! We should somehow support an QueryableDocumentList!
                result = new DynamicPublishedContentList(this.Where <DynamicPublishedContent>(predicate, values).ToList());
                return(true);
            }
            if (name == "OrderBy")
            {
                //TODO: We are pre-resolving the where into a ToList() here which will have performance impacts if there where clauses
                // are nested! We should somehow support an QueryableDocumentList!
                result = new DynamicPublishedContentList(this.OrderBy <DynamicPublishedContent>(firstArg.ToString()).ToList());
                return(true);
            }
            if (name == "Take")
            {
                result = new DynamicPublishedContentList(this.Take <DynamicPublishedContent>((int)firstArg));
                return(true);
            }
            if (name == "Skip")
            {
                result = new DynamicPublishedContentList(this.Skip <DynamicPublishedContent>((int)firstArg));
                return(true);
            }
            if (name == "InGroupsOf")
            {
                int groupSize = 0;
                if (int.TryParse(firstArg.ToString(), out groupSize))
                {
                    result = InGroupsOf(groupSize);
                    return(true);
                }
                result = new DynamicNull();
                return(true);
            }
            if (name == "GroupedInto")
            {
                int groupCount = 0;
                if (int.TryParse(firstArg.ToString(), out groupCount))
                {
                    result = GroupedInto(groupCount);
                    return(true);
                }
                result = new DynamicNull();
                return(true);
            }
            if (name == "GroupBy")
            {
                result = GroupBy(firstArg.ToString());
                return(true);
            }
            if (name == "Average" || name == "Min" || name == "Max" || name == "Sum")
            {
                result = Aggregate(args, name);
                return(true);
            }
            if (name == "Union")
            {
                if ((firstArg as IEnumerable <DynamicPublishedContent>) != null)
                {
                    result = new DynamicPublishedContentList(this.Items.Union(firstArg as IEnumerable <DynamicPublishedContent>));
                    return(true);
                }
                if ((firstArg as DynamicPublishedContentList) != null)
                {
                    result = new DynamicPublishedContentList(this.Items.Union((firstArg as DynamicPublishedContentList).Items));
                    return(true);
                }
            }
            if (name == "Except")
            {
                if ((firstArg as IEnumerable <DynamicPublishedContent>) != null)
                {
                    result = new DynamicPublishedContentList(this.Items.Except(firstArg as IEnumerable <DynamicPublishedContent>, new DynamicPublishedContentIdEqualityComparer()));
                    return(true);
                }
            }
            if (name == "Intersect")
            {
                if ((firstArg as IEnumerable <DynamicPublishedContent>) != null)
                {
                    result = new DynamicPublishedContentList(this.Items.Intersect(firstArg as IEnumerable <DynamicPublishedContent>, new DynamicPublishedContentIdEqualityComparer()));
                    return(true);
                }
            }
            if (name == "Distinct")
            {
                result = new DynamicPublishedContentList(this.Items.Distinct(new DynamicPublishedContentIdEqualityComparer()));
                return(true);
            }
            if (name == "Pluck" || name == "Select")
            {
                result = Pluck(args);
                return(true);
            }

            //ok, now lets try to match by member, property, extensino method
            var attempt = DynamicInstanceHelper.TryInvokeMember(this, binder, args, new[]
            {
                typeof(IEnumerable <DynamicPublishedContent>),
                typeof(DynamicPublishedContentList)
            });

            if (attempt.Success)
            {
                result = attempt.Result.ObjectResult;

                //need to check the return type and possibly cast if result is from an extension method found
                if (attempt.Result.Reason == DynamicInstanceHelper.TryInvokeMemberSuccessReason.FoundExtensionMethod)
                {
                    //we don't need to cast if the result is already DynamicPublishedContentList
                    if (attempt.Result.ObjectResult != null && (!(attempt.Result.ObjectResult is DynamicPublishedContentList)))
                    {
                        if (attempt.Result.ObjectResult is IPublishedContent)
                        {
                            result = new DynamicPublishedContent((IPublishedContent)attempt.Result.ObjectResult);
                        }
                        else if (attempt.Result.ObjectResult is IEnumerable <DynamicPublishedContent> )
                        {
                            result = new DynamicPublishedContentList((IEnumerable <DynamicPublishedContent>)attempt.Result.ObjectResult);
                        }
                        else if (attempt.Result.ObjectResult is IEnumerable <IPublishedContent> )
                        {
                            result = new DynamicPublishedContentList((IEnumerable <IPublishedContent>)attempt.Result.ObjectResult);
                        }
                    }
                }
                return(true);
            }

            //this is the result of an extension method execution gone wrong so we return dynamic null
            if (attempt.Result.Reason == DynamicInstanceHelper.TryInvokeMemberSuccessReason.FoundExtensionMethod &&
                attempt.Error != null && attempt.Error is TargetInvocationException)
            {
                result = new DynamicNull();
                return(true);
            }

            result = null;
            return(false);
        }
 public HtmlString StripHtml(DynamicNull html, params string[] tags)
 {
     return(new HtmlString(string.Empty));
 }
예제 #20
0
 public static int __hash__(DynamicNull self) {
     return NoneHashCode;
 }
예제 #21
0
 public static string __repr__(DynamicNull self) {
     return "None";
 }
예제 #22
0
 public static MutableString ToJson(DynamicNull self, [Optional] GeneratorState state, [Optional] Int32 depth)
 {
     return(Generator.ToJson(self));
 }
예제 #23
0
 public static object Cycle(CallSiteStorage <EachSite> /*!*/ each, BlockParam block, object self, DynamicNull iterations)
 {
     return((block != null) ? Cycle(each, block, self, Int32.MaxValue) : GetCycleEnumerator(each, block, self, Int32.MaxValue));
 }
예제 #24
0
 public static MutableString ToJson(DynamicNull self)
 {
     return(JSON_NULL);
 }
예제 #25
0
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
			var name = binder.Name;

			//check the cache first!
            if (_cachedMemberOutput.TryGetValue(binder.Name, out result))
			{
				return true;
			}

            result = null; //this will never be returned

            if (name.InvariantEquals("ChildrenAsList") || name.InvariantEquals("Children"))
            {
                result = GetChildrenAsList;
				//cache the result so we don't have to re-process the whole thing
                _cachedMemberOutput.TryAdd(binder.Name, result);
                return true;
            }
            if (binder.Name.InvariantEquals("parentId"))
            {
                var parent = n.Parent;
                if (parent == null)
                {
                    throw new InvalidOperationException(string.Format("The node {0} does not have a parent", Id));
                }
                result = parent.Id;
                _cachedMemberOutput.TryAdd(binder.Name, result);
                return true;
            }

            bool propertyExists = false;
            if (n != null)
            {
                bool recursive = false;
                if (name.StartsWith("_"))
                {
                    name = name.Substring(1, name.Length - 1);
                    recursive = true;
                }
                    
                PropertyResult prop;
                if (!_cachedProperties.TryGetValue(binder.Name, out prop))
                {
                    prop = n.GetProperty(name, recursive, out propertyExists);
                    // check for nicer support of Pascal Casing EVEN if alias is camelCasing:
                    if (prop == null && name.Substring(0, 1).ToUpper() == name.Substring(0, 1) && !propertyExists)
                    {
                        prop = n.GetProperty(name.Substring(0, 1).ToLower() + name.Substring((1)), recursive, out propertyExists);
                    }
                }
                    
                if (prop != null)
                {
                    if (TryGetPropertyData(prop, out result))
                    {
                        //cache the result so we don't have to re-process the whole thing
                        _cachedMemberOutput.TryAdd(binder.Name, result);
                        return true;
                    }
                }

                //check if the alias is that of a child type

                var typeChildren = n.ChildrenAsList;
                if (typeChildren != null)
                {

	                var filteredTypeChildren = typeChildren
		                .Where(x => x.NodeTypeAlias.InvariantEquals(name) || x.NodeTypeAlias.MakePluralName().InvariantEquals(binder.Name))
		                .ToArray();
                    if (filteredTypeChildren.Any())
                    {
                        result = new DynamicNodeList(filteredTypeChildren);
						//cache the result so we don't have to re-process the whole thing
                        _cachedMemberOutput.TryAdd(binder.Name, result);
                        return true;
                    }

                }

                //lookup the property using reflection

                result = GetReflectedProperty(binder.Name);

                if (result != null)
                {
                    _cachedMemberOutput.TryAdd(binder.Name, result);
                    return true;
                }

            }

            //if property access, type lookup and member invoke all failed
            //at this point, we're going to return null
            //instead, we return a DynamicNull - see comments in that file
            //this will let things like Model.ChildItem work and return nothing instead of crashing
            if (!propertyExists && result == null)
            {
                //.Where explictly checks for this type
                //and will make it false
                //which means backwards equality (&& property != true) will pass
                //forwwards equality (&& property or && property == true) will fail
                result = new DynamicNull();
                return true;
            }
            return true;
        }
예제 #26
0
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {

            var name = binder.Name;
            result = null; //this will never be returned

            if (name == "ChildrenAsList" || name == "Children")
            {
                result = GetChildrenAsList;
                return true;
            }
            bool propertyExists = false;
            if (n != null)
            {
                bool recursive = false;
                if (name.StartsWith("_"))
                {
                    name = name.Substring(1, name.Length - 1);
                    recursive = true;
                }
                var data = n.GetProperty(name, recursive, out propertyExists);
                // check for nicer support of Pascal Casing EVEN if alias is camelCasing:
                if (data == null && name.Substring(0, 1).ToUpper() == name.Substring(0, 1) && !propertyExists)
                {
                    data = n.GetProperty(name.Substring(0, 1).ToLower() + name.Substring((1)), recursive, out propertyExists);
                }

                if (data != null)
                {
                    result = data.Value;
                    //special casing for true/false properties
                    //int/decimal are handled by ConvertPropertyValueByDataType
                    //fallback is stringT
                    if (n.NodeTypeAlias == null && data.Alias == null)
                    {
                        throw new ArgumentNullException("No node alias or property alias available. Unable to look up the datatype of the property you are trying to fetch.");
                    }

                    //contextAlias is the node which the property data was returned from
                    //Guid dataType = ContentType.GetDataType(data.ContextAlias, data.Alias);					
                	var dataType = GetDataType(data.ContextAlias, data.Alias);
                    
                    var staticMapping = UmbracoSettings.RazorDataTypeModelStaticMapping.FirstOrDefault(mapping =>
                    {
                        return mapping.Applies(dataType, data.ContextAlias, data.Alias);
                    });
                    if (staticMapping != null)
                    {

                        Type dataTypeType = Type.GetType(staticMapping.TypeName);
                        if (dataTypeType != null)
                        {
                            object instance = null;
                            if (TryCreateInstanceRazorDataTypeModel(dataType, dataTypeType, data.Value, out instance))
                            {
                                result = instance;
                                return true;
                            }
                            else
                            {
								LogHelper.Warn<DynamicNode>(string.Format("Failed to create the instance of the model binder"));                            
                            }
                        }
                        else
                        {
							LogHelper.Warn<DynamicNode>(string.Format("staticMapping type name {0} came back as null from Type.GetType; check the casing, assembly presence, assembly framework version, namespace", staticMapping.TypeName));                            
                        }
                    }
                    
                    if (RazorDataTypeModelTypes != null && RazorDataTypeModelTypes.Any(model => model.Key.Item1 == dataType) && dataType != Guid.Empty)
                    {
                        var razorDataTypeModelDefinition = RazorDataTypeModelTypes.Where(model => model.Key.Item1 == dataType).OrderByDescending(model => model.Key.Item2).FirstOrDefault();
                        if (!(razorDataTypeModelDefinition.Equals(default(KeyValuePair<System.Tuple<Guid, int>, Type>))))
                        {
                            Type dataTypeType = razorDataTypeModelDefinition.Value;
                            object instance = null;
                            if (TryCreateInstanceRazorDataTypeModel(dataType, dataTypeType, data.Value, out instance))
                            {
                                result = instance;
                                return true;
                            }
                            else
                            {
								LogHelper.Warn<DynamicNode>(string.Format("Failed to create the instance of the model binder"));
                            }
                        }
                        else
                        {
							LogHelper.Warn<DynamicNode>(string.Format("Could not get the dataTypeType for the RazorDataTypeModel"));                            
                        }
                    }
                    else
                    {
						//NOTE: Do we really want to log this? I'm not sure.
						//if (RazorDataTypeModelTypes == null)
						//{
						//    HttpContext.Current.Trace.Write(string.Format("RazorDataTypeModelTypes is null, probably an exception while building the cache, falling back to ConvertPropertyValueByDataType", dataType));
						//}
						//else
						//{
						//    HttpContext.Current.Trace.Write(string.Format("GUID {0} does not have a DataTypeModel, falling back to ConvertPropertyValueByDataType", dataType));
						//}

                    }

                    //convert the string value to a known type
                    return ConvertPropertyValueByDataType(ref result, name, dataType);

                }

                //check if the alias is that of a child type

                var typeChildren = n.ChildrenAsList;
                if (typeChildren != null)
                {
                    var filteredTypeChildren = typeChildren.Where(x =>
                    {
                        List<string> ancestorAliases = GetAncestorOrSelfNodeTypeAlias(x);
                        if (ancestorAliases == null)
                        {
                            return false;
                        }
                        return ancestorAliases.Any(alias => alias == name || MakePluralName(alias) == name);
                    });
                    if (filteredTypeChildren.Any())
                    {
                        result = new DynamicNodeList(filteredTypeChildren);
                        return true;
                    }

                }

                try
                {
                    result = n.GetType().InvokeMember(binder.Name,
                                                      System.Reflection.BindingFlags.GetProperty |
                                                      System.Reflection.BindingFlags.Instance |
                                                      System.Reflection.BindingFlags.Public,
                                                      null,
                                                      n,
                                                      null);
                    return true;
                }
                catch
                {
                    //result = null;
                    //return false;
                }
            }

            //if property access, type lookup and member invoke all failed
            //at this point, we're going to return null
            //instead, we return a DynamicNull - see comments in that file
            //this will let things like Model.ChildItem work and return nothing instead of crashing
            if (!propertyExists && result == null)
            {
                //.Where explictly checks for this type
                //and will make it false
                //which means backwards equality (&& property != true) will pass
                //forwwards equality (&& property or && property == true) will fail
                result = new DynamicNull();
                return true;
            }
            return true;
        }
예제 #27
0
 public static object Each(RubyContext /*!*/ context, BlockParam block, object self, DynamicNull separator)
 {
     RubyIOOps.Each(context, block, context.InputProvider.GetOrResetCurrentStream(), separator);
     return(self);
 }
예제 #28
0
 public static MutableString /*!*/ SystemRead(StringIO /*!*/ self, [Optional] DynamicNull bytes)
 {
     return(Read(self, null, true));
 }
예제 #29
0
 public static RubyArray /*!*/ ReadLines(RubyContext /*!*/ context, object self, DynamicNull separator)
 {
     return(RubyIOOps.ReadLines(context, context.InputProvider.GetOrResetCurrentStream(), separator));
 }
예제 #30
0
 public static MutableString /*!*/ SystemRead(StringIO /*!*/ self, DynamicNull bytes, [DefaultProtocol, NotNull] MutableString buffer)
 {
     return(Read(self, buffer, true));
 }
예제 #31
0
 public static bool op_Implicit(DynamicNull self)
 {
     Debug.Assert(self == null);
     return(false);
 }
예제 #32
0
 public static MutableString Gets(RubyScope /*!*/ scope, StringIO /*!*/ self, DynamicNull separator)
 {
     return(Gets(scope, self, null, -1));
 }
 public IHtmlString Truncate(DynamicNull html, int length)
 {
     return(new HtmlString(string.Empty));
 }
예제 #34
0
 public static MutableString /*!*/ ReadLine(RubyScope /*!*/ scope, StringIO /*!*/ self, DynamicNull separator)
 {
     return(ReadLine(scope, self, null, -1));
 }
 public IHtmlString Truncate(DynamicNull html, int length, bool addElipsis, bool treatTagsAsContent)
 {
     return(new HtmlString(string.Empty));
 }
예제 #36
0
 public static RubyArray /*!*/ ReadLines(RubyContext /*!*/ context, StringIO /*!*/ self, DynamicNull separator)
 {
     return(ReadLines(self, null, -1));
 }
 public HtmlString StripHtml(DynamicNull html, List <string> tags)
 {
     return(new HtmlString(string.Empty));
 }
예제 #38
0
 public static object EachLine(RubyContext /*!*/ context, BlockParam block, StringIO /*!*/ self, DynamicNull separator)
 {
     return(EachLine(block, self, null, -1));
 }
 public dynamic NodeById(DynamicNull Id)
 {
     return(new DynamicNull());
 }
예제 #40
0
		/// <summary>
		/// Try to return an object based on the dynamic member accessor
		/// </summary>
		/// <param name="binder"></param>
		/// <param name="result"></param>
		/// <returns></returns>
		/// <remarks>
		/// TODO: SD: This will alwasy return true so that no exceptions are generated, this is only because this is how the 
		/// old DynamicNode worked, I'm not sure if this is the correct/expected functionality but I've left it like that.
		/// IMO I think this is incorrect and it would be better to throw an exception for something that is not supported!
		/// </remarks>
		public override bool TryGetMember(GetMemberBinder binder, out object result)
		{
			if (binder == null) throw new ArgumentNullException("binder");

			var name = binder.Name;

			//check the cache first!
			if (_cachedMemberOutput.TryGetValue(name, out result))
			{
				return true;
			}
			
			//loop through each member match method and execute it. 
			//If it is successful, cache the result and return it.
			foreach (var attempt in GetMemberMatchMethods()
				.Select(m => m(binder))
				.Where(attempt => attempt.Success))
			{
				result = attempt.Result;
				//cache the result so we don't have to re-process the whole thing
				_cachedMemberOutput.TryAdd(name, result);
				return true;
			}

			//if property access, type lookup and member invoke all failed
			//at this point, we're going to return null
			//instead, we return a DynamicNull - see comments in that file
			//this will let things like Model.ChildItem work and return nothing instead of crashing

			//.Where explictly checks for this type
			//and will make it false
			//which means backwards equality (&& property != true) will pass
			//forwwards equality (&& property or && property == true) will fail
			result = new DynamicNull();

			//alwasy return true if we haven't thrown an exception though I'm wondering if we return 'false' if .Net throws an exception for us??
			return true;
		}