private List<Dissimilarity> LoadDissimilarities()
        {
            ReflectionTools _rct = new ReflectionTools();
            List<Dissimilarity> _result = _rct.GetDissimilarities();

            Dissimilarities = _result;
            return _result;
        }
Example #2
0
    public void SavePredictions(PredictorTrainingContext ctx)
    {
        using (HeavyProfiler.Log("SavePredictions"))
        {
            var p             = ctx.Predictor.ToLite();
            var outputColumn  = AssertOnlyOutput(ctx.Predictor);
            var isCategorical = outputColumn.Encoding.Is(DefaultColumnEncodings.OneHot);

            var keys = !ctx.Predictor.MainQuery.GroupResults ? null : ctx.Predictor.MainQuery.Columns.Where(c => !(c.Token.Token is AggregateToken)).ToList();
            var key0 = keys?.ElementAtOrDefault(0);
            var key1 = keys?.ElementAtOrDefault(1);
            var key2 = keys?.ElementAtOrDefault(2);

            using (HeavyProfiler.Log("Delete Old Predictions"))
            {
                ctx.ReportProgress($"Deleting old {typeof(PredictSimpleResultEntity).NicePluralName()}");
                {
                    var query      = Database.Query <PredictSimpleResultEntity>().Where(a => a.Predictor.Is(p));
                    int chunkSize  = 5000;
                    var totalCount = query.Count();
                    var deleted    = 0;
                    while (totalCount - deleted > 0)
                    {
                        int num = query.OrderBy(a => a.Id).Take(chunkSize).UnsafeDelete();
                        deleted += num;
                        ctx.ReportProgress($"Deleting old {typeof(PredictSimpleResultEntity).NicePluralName()}", deleted / (decimal)totalCount);
                    }
                }
            }

            using (HeavyProfiler.Log("SavePredictions"))
            {
                ctx.ReportProgress($"Creating {typeof(PredictSimpleResultEntity).NicePluralName()}");
                {
                    var dictionary = ctx.ToPredictDictionaries();
                    var toInsert   = new List <PredictSimpleResultEntity>();

                    var pc      = PredictorPredictLogic.CreatePredictContext(ctx.Predictor);
                    int grIndex = 0;
                    foreach (var gr in dictionary.Chunk(PredictionBatchSize))
                    {
                        using (HeavyProfiler.LogNoStackTrace("Group"))
                        {
                            ctx.ReportProgress($"Creating {typeof(PredictSimpleResultEntity).NicePluralName()}", (grIndex++ *PredictionBatchSize) / (decimal)dictionary.Count);

                            var inputs = gr.Select(a => a.Value).ToList();

                            var outputs = pc.Algorithm.PredictMultiple(pc, inputs);

                            using (HeavyProfiler.LogNoStackTrace("Create SimpleResults"))
                            {
                                for (int i = 0; i < inputs.Count; i++)
                                {
                                    PredictDictionary input  = inputs[i];
                                    PredictDictionary output = outputs[i];

                                    object?inValue  = input.MainQueryValues.GetOrThrow(outputColumn);
                                    object?outValue = output.MainQueryValues.GetOrThrow(outputColumn);

                                    toInsert.Add(new PredictSimpleResultEntity
                                    {
                                        Predictor         = p,
                                        Target            = ctx.Predictor.MainQuery.GroupResults ? null : input.Entity,
                                        Type              = ctx.Validation.Contains(gr[i].Key) ? PredictionSet.Validation : PredictionSet.Training,
                                        Key0              = key0 == null ? null : input.MainQueryValues.GetOrThrow(key0)?.ToString(),
                                        Key1              = key1 == null ? null : input.MainQueryValues.GetOrThrow(key1)?.ToString(),
                                        Key2              = key2 == null ? null : input.MainQueryValues.GetOrThrow(key2)?.ToString(),
                                        OriginalValue     = isCategorical ? null : ReflectionTools.ChangeType <double?>(inValue),
                                        OriginalCategory  = isCategorical ? inValue?.ToString() : null,
                                        PredictedValue    = isCategorical ? null : ReflectionTools.ChangeType <double?>(outValue),
                                        PredictedCategory = isCategorical ? outValue?.ToString() : null,
                                    });
                                }
                            }
                        }
                    }

                    ctx.Predictor.RegressionTraining       = isCategorical ? null : GetRegressionStats(toInsert.Where(a => a.Type == PredictionSet.Training).ToList());
                    ctx.Predictor.RegressionValidation     = isCategorical ? null : GetRegressionStats(toInsert.Where(a => a.Type == PredictionSet.Validation).ToList());
                    ctx.Predictor.ClassificationTraining   = !isCategorical ? null : GetClassificationStats(toInsert.Where(a => a.Type == PredictionSet.Training).ToList());
                    ctx.Predictor.ClassificationValidation = !isCategorical ? null : GetClassificationStats(toInsert.Where(a => a.Type == PredictionSet.Validation).ToList());

                    using (OperationLogic.AllowSave <PredictorEntity>())
                        ctx.Predictor.Save();

                    if (SaveAllResults)
                    {
                        var groups = toInsert.Chunk(PredictionBatchSize).ToList();
                        foreach (var iter in groups.Iterate())
                        {
                            ctx.ReportProgress($"Inserting {typeof(PredictSimpleResultEntity).NicePluralName()}", iter.Position / (decimal)groups.Count);
                            iter.Value.BulkInsert();
                        }
                    }
                }
            }
        }
    }
        //original method serialized
        MethodInfo GetOriginal()
        {
            var type = ReflectionTools.GetType(_baseInfo.Split('|')[0]);

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

            var name           = _baseInfo.Split('|')[1];
            var paramTypeNames = string.IsNullOrEmpty(_paramsInfo)? null : _paramsInfo.Split('|');
            var parameterTypes = paramTypeNames == null? new Type[0] : paramTypeNames.Select(n => ReflectionTools.GetType(n)).ToArray();

            var method = type.RTGetMethod(name, parameterTypes);

            if (!string.IsNullOrEmpty(_returnInfo))              //it might be in case of older serialzations
            {
                var returnType = ReflectionTools.GetType(_returnInfo);
                if (method != null && returnType != method.ReturnType)
                {
                    method = null;
                }
            }

            return(method);
        }
Example #4
0
        //...
        fsResult Internal_Deserialize(Type overrideConverterType, fsData data, Type storageType, ref object result, out List <fsObjectProcessor> processors)
        {
            //$ref encountered. Do before inheritance.
            if (IsObjectReference(data))
            {
                int refId = int.Parse(data.AsDictionary[KEY_OBJECT_REFERENCE].AsString);
                result     = _references.GetReferenceObject(refId);
                processors = GetProcessors(result.GetType());
                return(fsResult.Success);
            }

            var deserializeResult = fsResult.Success;

            // We wait until here to actually Invoke_OnBeforeDeserialize because we do not
            // have the correct set of processors to invoke until *after* we have resolved
            // the proper type to use for deserialization.
            processors = GetProcessors(storageType);
            Invoke_OnBeforeDeserialize(processors, storageType, ref data);

            var objectType = storageType;

            // If the serialized state contains type information, then we need to make sure to update our
            // objectType and data to the proper values so that when we construct an object instance later
            // and run deserialization we run it on the proper type.
            // $type
            if (IsTypeSpecified(data))
            {
                var typeNameData = data.AsDictionary[KEY_INSTANCE_TYPE];

                do
                {
                    if (!typeNameData.IsString)
                    {
                        deserializeResult.AddMessage(string.Format("{0} value must be a string", KEY_INSTANCE_TYPE));
                        break;
                    }

                    var typeName = typeNameData.AsString;
                    var type     = ReflectionTools.GetType(typeName, storageType);

                    if (type == null)
                    {
                        deserializeResult.AddMessage(string.Format("{0} type can not be resolved", typeName));
                        break;
                    }

                    if (!storageType.IsAssignableFrom(type))
                    {
                        deserializeResult.AddMessage(string.Format("Ignoring type specifier. Field or type {0} can't hold and instance of type {1}", storageType, type));
                        break;
                    }

                    objectType = type;
                } while (false);
            }

            var converter = GetConverter(objectType, overrideConverterType);

            if (converter == null)
            {
                return(fsResult.Warn(string.Format("No Converter available for {0}", objectType)));
            }

            // Construct an object instance if we don't have one already using actual objectType
            if (ReferenceEquals(result, null) || result.GetType() != objectType)
            {
                result = converter.CreateInstance(data, objectType);
            }

            // invoke callback with storageType
            Invoke_OnBeforeDeserializeAfterInstanceCreation(processors, storageType, result, ref data);

            // $id
            if (IsObjectDefinition(data))
            {
                var sourceId = int.Parse(data.AsDictionary[KEY_OBJECT_DEFINITION].AsString);
                _references.AddReferenceWithId(sourceId, result);
            }

            // $content
            if (IsWrappedData(data))
            {
                data = data.AsDictionary[KEY_CONTENT];
            }

            // must pass actual objectType instead of storageType
            return(deserializeResult += converter.TryDeserialize(data, ref result, objectType));
        }
Example #5
0
        public override MList <S> GetValue(MappingContext <MList <S> > ctx)
        {
            using (HeavyProfiler.LogNoStackTrace("GetValue", () => "MListMapping<{0}>".FormatWith(typeof(S).TypeName())))
            {
                if (ctx.Empty())
                {
                    return(ctx.None());
                }

                IMListPrivate <S> mlistPriv = ctx.Value;

                var dic = mlistPriv == null ? new Dictionary <PrimaryKey, MList <S> .RowIdElement>() :
                          mlistPriv.InnerList.Where(a => a.RowId.HasValue).ToDictionary(a => a.RowId.Value, a => a);

                var newList = new List <MList <S> .RowIdElement>();
                foreach (MappingContext <S> itemCtx in GenerateItemContexts(ctx))
                {
                    Debug.Assert(!itemCtx.Empty());

                    string rowIdString = itemCtx.Inputs.TryGetC(EntityListBaseKeys.RowId);

                    if (rowIdString.HasText())
                    {
                        var rowId = new PrimaryKey((IComparable)ReflectionTools.Parse(rowIdString, GetRowIdType(ctx)));

                        var oldValue = dic.GetOrThrow(rowId, "No RowID {0} found");

                        itemCtx.Value = oldValue.Element;
                        itemCtx.Value = ElementMapping(itemCtx);

                        ctx.AddChild(itemCtx);

                        if (itemCtx.Value != null)
                        {
                            var val = itemCtx.SupressChange ? oldValue.Element : itemCtx.Value;

                            if (oldValue.Element.Equals(val))
                            {
                                newList.Add(new MList <S> .RowIdElement(val, rowId, oldValue.OldIndex));
                            }
                            else
                            {
                                newList.Add(new MList <S> .RowIdElement(val));
                            }
                        }
                    }
                    else
                    {
                        itemCtx.Value = ElementMapping(itemCtx);
                        ctx.AddChild(itemCtx);
                        if (itemCtx.Value != null && !itemCtx.SupressChange)
                        {
                            newList.Add(new MList <S> .RowIdElement(itemCtx.Value));
                        }
                    }
                }

                if (!AreEqual(newList, mlistPriv == null ? null : mlistPriv.InnerList))
                {
                    Signum.Web.Mapping.AssertCanChange(ctx.PropertyRoute);

                    if (ctx.Value == null)
                    {
                        mlistPriv = ctx.Value = new MList <S>();
                    }

                    var added   = newList.Select(a => a.Element).Except(mlistPriv.InnerList.Select(a => a.Element)).ToList();
                    var removed = mlistPriv.InnerList.Select(a => a.Element).Except(newList.Select(a => a.Element)).ToList();

                    mlistPriv.InnerList.Clear();
                    mlistPriv.InnerList.AddRange(newList);
                    mlistPriv.InnerListModified(added, removed);
                }

                return(ctx.Value);
            }
        }
Example #6
0
        ///Generates AOT classes file out of preferred types list
        public static void GenerateAOTClasses(string path, Type[] targetTypes)
        {
            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            var spoofTypes = defaultSpoofTypes;

            spoofTypes.AddRange(targetTypes.Where(t => t.IsValueType && !spoofTypes.Contains(t)));
            spoofTypes = spoofTypes.Distinct().ToList();
            var types = ReflectionTools.GetAllTypes(true).Where(t => t.RTIsDefined(typeof(SpoofAOTAttribute), true)).Distinct();

            var nTypes   = 0;
            var nMethods = 0;

            var sb = new StringBuilder();

            sb.AppendLine("#pragma warning disable 0219, 0168, 0612");
            sb.AppendLine("namespace ParadoxNotion.Internal{");
            sb.AppendLine();
            sb.AppendLine("\t//Auto generated classes for AOT support, where using undeclared generic classes with value types is limited. These are not actualy used but rather just declared for the compiler");
            sb.AppendLine("\tpartial class AOTDummy{");
            sb.AppendLine();
            sb.AppendLine("\t\tobject o = null;");

            sb.AppendLine("\t\t///----------------------------------------------------------------------------------------------");

            //Generic Types
            foreach (var type in types)
            {
                if (!type.IsAbstract && type.IsGenericTypeDefinition && type.RTGetGenericArguments().Length == 1)
                {
                    var constrains = type.RTGetGenericArguments()[0].GetGenericParameterConstraints();

                    if (constrains.Length == 0 || constrains[0].IsValueType)
                    {
                        if (typeof(Delegate).IsAssignableFrom(type))
                        {
                            nTypes++;
                            sb.AppendLine(string.Format("\t\tvoid {0}()", type.FriendlyName(true).Replace(".", "_").Replace("<T>", "_Delegate")) + "{");
                            foreach (var spoofType in spoofTypes)
                            {
                                var a = type.FriendlyName(true).Replace("<T>", "<" + spoofType.FullName + ">").Replace("+", ".");
                                var b = "_" + type.FriendlyName(true).Replace(".", "_").Replace("<T>", "_" + spoofType.FullName.Replace(".", "_").Replace("+", "_"));
                                sb.AppendLine(string.Format("\t\t\t{0} {1};", a, b));
                            }
                            sb.AppendLine("\t\t}");
                        }
                        else
                        {
                            foreach (var spoofType in spoofTypes)
                            {
                                nTypes++;
                                var a = type.FriendlyName(true).Replace("<T>", "<" + spoofType.FullName + ">").Replace("+", ".");
                                var b = type.FriendlyName(true).Replace(".", "_").Replace("<T>", "_" + spoofType.FullName.Replace(".", "_").Replace("+", "_"));
                                sb.AppendLine(string.Format("\t\t{0} {1};", a, b));
                            }
                        }

                        sb.AppendLine();
                    }
                }
            }

            sb.AppendLine("\t\t///----------------------------------------------------------------------------------------------");

            //Generic Methods
            foreach (var type in types)
            {
                var index = 0;
                foreach (var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly))
                {
                    if (method.IsObsolete())
                    {
                        continue;
                    }

                    if (method.IsGenericMethodDefinition && method.RTGetGenericArguments().Length == 1)
                    {
                        var constrains = method.RTGetGenericArguments()[0].GetGenericParameterConstraints();

                        if (constrains.Length == 0 || constrains[0].IsValueType)
                        {
                            index++;

                            var decType = method.DeclaringType;
                            var varName = "_" + decType.FullName.Replace(".", "_");
                            sb.AppendLine(string.Format("\t\tvoid {0}_{1}_{2}()", decType.FullName.Replace(".", "_"), method.Name, index) + " {");
                            if (!method.IsStatic)
                            {
                                sb.AppendLine(string.Format("\t\t\t{0} {1} = default({2});", decType.FullName, varName, decType.FullName));
                            }

                            foreach (var spoofType in spoofTypes)
                            {
                                nMethods++;
                                var a            = method.IsStatic ? decType.FullName : varName;
                                var b            = method.Name;
                                var c            = spoofType.FullName.Replace("+", ".");
                                var paramsString = "";
                                var parameters   = method.GetParameters();
                                for (var i = 0; i < parameters.Length; i++)
                                {
                                    var parameter = parameters[i];
                                    var toString  = parameter.ParameterType.FullName;
                                    if (parameter.ParameterType.IsGenericParameter)
                                    {
                                        toString = spoofType.FullName;
                                    }
                                    if (parameter.ParameterType.IsGenericType)
                                    {
                                        toString = parameter.ParameterType.FriendlyName(true).Replace("<T>", "<" + spoofType.FullName + ">");
                                        toString = toString.Replace("[[T]]", "");
                                    }
                                    toString      = toString.Replace("+", ".");
                                    paramsString += string.Format("({0})o", toString);
                                    if (i < parameters.Length - 1)
                                    {
                                        paramsString += ", ";
                                    }
                                }
                                var d = paramsString;
                                sb.AppendLine(string.Format("\t\t\t{0}.{1}<{2}>( {3} );", a, b, c, d));
                            }

                            sb.AppendLine("\t\t}");
                            sb.AppendLine();
                        }
                    }
                }
            }

            sb.AppendLine("\t\t///----------------------------------------------------------------------------------------------");

            //custom stuff
            sb.AppendLine("\t\tvoid CustomSpoof(){");
            foreach (var spoofType in spoofTypes)
            {
                var sName = spoofType.FullName.Replace("+", ".");
                var fName = spoofType.FullName.Replace(".", "_").Replace("+", "_");
                foreach (var genericType in customGenericSpoof)
                {
                    nTypes++;
                    var a = genericType.FriendlyName(true).Replace("<T>", "<" + sName + ">");
                    var b = genericType.FriendlyName(true).Replace(".", "_").Replace("<T>", "_") + fName;
                    sb.AppendLine(string.Format("\t\t\t{0} {1};", a, b));
                }
                nTypes++;
                sb.AppendLine(string.Format("\t\t\tSystem.Collections.Generic.IDictionary<System.String, {0}> IDict_{1};", sName, fName));
                sb.AppendLine(string.Format("\t\t\tSystem.Collections.Generic.Dictionary<System.String, {0}> Dict_{1};", sName, fName));
                sb.AppendLine("\t\t\t///------");
            }
            sb.AppendLine("\t\t}");
            sb.AppendLine("\t}");
            sb.AppendLine("}");
            sb.AppendLine();
            sb.AppendLine(string.Format("//{0} Types | {1} Methods spoofed", nTypes, nMethods));
            sb.AppendLine("#pragma warning restore 0219, 0168, 0612");

            File.WriteAllText(path, sb.ToString());
        }
Example #7
0
 internal NetPropertyToken(QueryToken parent, Expression <Func <object> > pi, Func <string> displayName) :
     this(parent, ReflectionTools.GetPropertyInfo(pi), displayName)
 {
 }
        private List<Proximity> LoadProximities()
        {
            try
            {
                ReflectionTools _rct = new ReflectionTools();
                List<Proximity> _result = _rct.GetProximities();

                return _result;
            }
            catch (Exception _ex)
            {
                GeneralTools.Tools.WriteToLog(_ex);
                return new List<Proximity>();
            }
        }
Example #9
0
        //For generic automatic editors. Passing a MemberInfo will also check for attributes
        public static object GenericField(string name, object value, Type t, MemberInfo member = null, object instance = null)
        {
            if (t == null)
            {
                GUILayout.Label("NO TYPE PROVIDED!");
                return(value);
            }

            //Preliminary Hides
            if (typeof(Delegate).IsAssignableFrom(t))
            {
                return(value);
            }

            name = name.SplitCamelCase();

            //

            IEnumerable <Attribute> attributes = new Attribute[0];

            if (member != null)
            {
                //Hide class?
                if (t.GetCustomAttributes(typeof(HideInInspector), true).FirstOrDefault() != null)
                {
                    return(value);
                }

                attributes = member.GetCustomAttributes(true).Cast <Attribute>();

                //Hide field?
                if (attributes.Any(a => a is HideInInspector))
                {
                    return(value);
                }

                //Is required?
                if (attributes.Any(a => a is RequiredFieldAttribute))
                {
                    if ((value == null || value.Equals(null)) ||
                        (t == typeof(string) && string.IsNullOrEmpty((string)value)) ||
                        (typeof(BBParameter).IsAssignableFrom(t) && (value as BBParameter).isNull))
                    {
                        GUI.backgroundColor = lightRed;
                    }
                }
            }


            if (member != null)
            {
                var nameAtt = attributes.FirstOrDefault(a => a is NameAttribute) as NameAttribute;
                if (nameAtt != null)
                {
                    name = nameAtt.name;
                }

                if (instance != null)
                {
                    var showAtt = attributes.FirstOrDefault(a => a is ShowIfAttribute) as ShowIfAttribute;
                    if (showAtt != null)
                    {
                        var targetField = instance.GetType().GetField(showAtt.fieldName);
                        if (targetField == null || targetField.FieldType != typeof(bool))
                        {
                            GUILayout.Label(string.Format("[ShowIf] Error: bool \"{0}\" does not exist.", showAtt.fieldName));
                        }
                        else
                        {
                            if ((bool)targetField.GetValue(instance) != showAtt.show)
                            {
                                return(value);
                            }
                        }
                    }
                }
            }


            //Before everything check BBParameter
            if (typeof(BBParameter).IsAssignableFrom(t))
            {
                return(BBParameterField(name, (BBParameter)value, false, member));
            }


            //Cutstom object drawers
            var objectDrawer = GetCustomDrawer(t);

            if (objectDrawer != null && !(objectDrawer is NoDrawer))
            {
                return(objectDrawer.DrawGUI(name, value, member as FieldInfo, null, instance));
            }

            //Cutstom attribute drawers
            foreach (CustomDrawerAttribute att in attributes.OfType <CustomDrawerAttribute>())
            {
                var attributeDrawer = GetCustomDrawer(att.GetType());
                if (attributeDrawer != null && !(attributeDrawer is NoDrawer))
                {
                    return(attributeDrawer.DrawGUI(name, value, member as FieldInfo, att, instance));
                }
            }


            //Then check UnityObjects
            if (typeof(UnityObject).IsAssignableFrom(t))
            {
                if (t == typeof(Component) && (Component)value != null)
                {
                    return(ComponentField(name, (Component)value, typeof(Component)));
                }
                return(EditorGUILayout.ObjectField(name, (UnityObject)value, t, true));
            }

            //Force UnityObject field?
            if (member != null && attributes.Any(a => a is ForceObjectFieldAttribute))
            {
                return(EditorGUILayout.ObjectField(name, value as UnityObject, t, true));
            }

            //Restricted popup values?
            if (member != null)
            {
                var popAtt = attributes.FirstOrDefault(a => a is PopupFieldAttribute) as PopupFieldAttribute;
                if (popAtt != null)
                {
                    if (popAtt.staticPath != null)
                    {
                        try
                        {
                            var typeName  = popAtt.staticPath.Substring(0, popAtt.staticPath.LastIndexOf("."));
                            var type      = ReflectionTools.GetType(typeName);
                            var start     = popAtt.staticPath.LastIndexOf(".") + 1;
                            var end       = popAtt.staticPath.Length;
                            var propName  = popAtt.staticPath.Substring(start, end - start);
                            var prop      = type.GetProperty(propName, BindingFlags.Static | BindingFlags.Public);
                            var propValue = prop.GetValue(null, null);
                            var values    = ((IEnumerable)propValue).Cast <object>().ToList();
                            return(Popup <object>(name, value, values));
                        }
                        catch
                        {
                            EditorGUILayout.LabelField(name, "[PopupField] attribute error!");
                            return(value);
                        }
                    }
                    return(Popup <object>(name, value, popAtt.values.ToList()));
                }
            }


            //Check Type of Type
            if (t == typeof(Type))
            {
                return(Popup <Type>(name, (Type)value, UserTypePrefs.GetPreferedTypesList(typeof(object), false)));
            }

            //Check abstract
            if ((value != null && value.GetType().IsAbstract) || (value == null && t.IsAbstract))
            {
                EditorGUILayout.LabelField(name, string.Format("Abstract ({0})", t.FriendlyName()));
                return(value);
            }

            //Create instance for some types
            if (value == null && !t.IsAbstract && !t.IsInterface && (t.IsValueType || t.GetConstructor(Type.EmptyTypes) != null || t.IsArray))
            {
                if (t.IsArray)
                {
                    value = Array.CreateInstance(t.GetElementType(), 0);
                }
                else
                {
                    value = Activator.CreateInstance(t);
                }
            }



            //Check the rest
            //..............
            if (t == typeof(string))
            {
                if (member != null)
                {
                    if (attributes.Any(a => a is TagFieldAttribute))
                    {
                        return(EditorGUILayout.TagField(name, (string)value));
                    }
                    var areaAtt = attributes.FirstOrDefault(a => a is TextAreaFieldAttribute) as TextAreaFieldAttribute;
                    if (areaAtt != null)
                    {
                        GUILayout.Label(name);
                        var areaStyle = new GUIStyle(GUI.skin.GetStyle("TextArea"));
                        areaStyle.wordWrap = true;
                        var s = EditorGUILayout.TextArea((string)value, areaStyle, GUILayout.Height(areaAtt.height));
                        return(s);
                    }
                }

                return(EditorGUILayout.TextField(name, (string)value));
            }

            if (t == typeof(bool))
            {
                return(EditorGUILayout.Toggle(name, (bool)value));
            }

            if (t == typeof(int))
            {
                if (member != null)
                {
                    var sField = attributes.FirstOrDefault(a => a is SliderFieldAttribute) as SliderFieldAttribute;
                    if (sField != null)
                    {
                        return((int)EditorGUILayout.Slider(name, (int)value, (int)sField.left, (int)sField.right));
                    }
                    if (attributes.Any(a => a is LayerFieldAttribute))
                    {
                        return(EditorGUILayout.LayerField(name, (int)value));
                    }
                }

                return(EditorGUILayout.IntField(name, (int)value));
            }

            if (t == typeof(float))
            {
                if (member != null)
                {
                    var sField = attributes.FirstOrDefault(a => a is SliderFieldAttribute) as SliderFieldAttribute;
                    if (sField != null)
                    {
                        return(EditorGUILayout.Slider(name, (float)value, sField.left, sField.right));
                    }
                }
                return(EditorGUILayout.FloatField(name, (float)value));
            }

            if (t == typeof(byte))
            {
                return(Convert.ToByte(Mathf.Clamp(EditorGUILayout.IntField(name, (byte)value), 0, 255)));
            }

            if (t == typeof(Vector2))
            {
                return(EditorGUILayout.Vector2Field(name, (Vector2)value));
            }

            if (t == typeof(Vector3))
            {
                return(EditorGUILayout.Vector3Field(name, (Vector3)value));
            }

            if (t == typeof(Vector4))
            {
                return(EditorGUILayout.Vector4Field(name, (Vector4)value));
            }

            if (t == typeof(Quaternion))
            {
                var quat = (Quaternion)value;
                var vec4 = new Vector4(quat.x, quat.y, quat.z, quat.w);
                vec4 = EditorGUILayout.Vector4Field(name, vec4);
                return(new Quaternion(vec4.x, vec4.y, vec4.z, vec4.w));
            }

            if (t == typeof(Color))
            {
                return(EditorGUILayout.ColorField(name, (Color)value));
            }

            if (t == typeof(Rect))
            {
                return(EditorGUILayout.RectField(name, (Rect)value));
            }

            if (t == typeof(AnimationCurve))
            {
                return(EditorGUILayout.CurveField(name, (AnimationCurve)value));
            }

            if (t == typeof(Bounds))
            {
                return(EditorGUILayout.BoundsField(name, (Bounds)value));
            }

            if (t == typeof(LayerMask))
            {
                return(LayerMaskField(name, (LayerMask)value));
            }

            if (t.IsSubclassOf(typeof(System.Enum)))
            {
#if UNITY_5
                if (t.GetCustomAttributes(typeof(FlagsAttribute), true).FirstOrDefault() != null)
                {
                    return(EditorGUILayout.EnumMaskPopup(new GUIContent(name), (System.Enum)value));
                }
#endif
                return(EditorGUILayout.EnumPopup(name, (System.Enum)value));
            }

            if (typeof(IList).IsAssignableFrom(t))
            {
                return(ListEditor(name, (IList)value, t, instance));
            }

            if (typeof(IDictionary).IsAssignableFrom(t))
            {
                return(DictionaryEditor(name, (IDictionary)value, t, instance));
            }


            //show nested class members recursively
            if (value != null && !t.IsEnum && !t.IsInterface)
            {
                GUILayout.BeginVertical();
                EditorGUILayout.LabelField(name, t.FriendlyName());
                EditorGUI.indentLevel++;
                ShowAutoEditorGUI(value);
                EditorGUI.indentLevel--;
                GUILayout.EndVertical();
            }
            else
            {
                EditorGUILayout.LabelField(name, string.Format("({0})", t.FriendlyName()));
            }

            return(value);
        }
Example #10
0
 protected static string NicePropertyName <E, R>(Expression <Func <E, R> > property)
 {
     return(ReflectionTools.GetPropertyInfo(property).NiceName());
 }
Example #11
0
 public string?PropertyCheck(Expression <Func <object?> > property)
 {
     return(PropertyCheck(ReflectionTools.GetPropertyInfo(property).Name));
 }
Example #12
0
 public void Notify <T>(Expression <Func <T> > property)
 {
     NotifyPrivate(ReflectionTools.BasePropertyInfo(property).Name);
     NotifyError();
 }
        /// A simple reorderable list. Pass the list and a function to call for GUI. The callback comes with the current iterated element index in the list
        public static IList ReorderableList(IList list, ReorderableListOptions options, ReorderableListCallback GUICallback)
        {
            if (list == null)
            {
                return(null);
            }

            var listType = list.GetType();
            var argType  = listType.GetEnumerableElementType();

            if (argType == null)
            {
                return(list);
            }

            var e = Event.current;

            if (options.allowAdd)
            {
                var dropRefs = DragAndDrop.objectReferences;

                //Drag And Drop.
                if (dropRefs.Length > 0)
                {
                    if (dropRefs.Any(r => argType.IsAssignableFrom(r.GetType()) || (r.GetType() == typeof(GameObject) && typeof(Component).IsAssignableFrom(argType))))
                    {
                        var dropRect = GUILayoutUtility.GetRect(0, 20, GUILayout.ExpandWidth(true));
                        dropRect.xMin += 5;
                        dropRect.xMax -= 5;
                        Styles.Draw(dropRect, Styles.roundedBox);
                        GUI.Box(dropRect, "Drop Here to Enlist", Styles.centerLabel);
                        if (dropRect.Contains(e.mousePosition))
                        {
                            if (e.type == EventType.DragUpdated)
                            {
                                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                                e.Use();
                            }
                            if (e.type == EventType.DragPerform)
                            {
                                for (var i = 0; i < dropRefs.Length; i++)
                                {
                                    var dropRef     = dropRefs[i];
                                    var dropRefType = dropRef.GetType();
                                    if (argType.IsAssignableFrom(dropRefType))
                                    {
                                        UndoUtility.RecordObject(options.unityObjectContext, "Drag Add Item");
                                        list.Add(dropRef);
                                        GUI.changed = true;
                                        UndoUtility.SetDirty(options.unityObjectContext);
                                        continue;
                                    }
                                    if (dropRefType == typeof(GameObject) && typeof(Component).IsAssignableFrom(argType))
                                    {
                                        var componentToAdd = (dropRef as GameObject).GetComponent(argType);
                                        if (componentToAdd != null)
                                        {
                                            UndoUtility.RecordObject(options.unityObjectContext, "Drag Add Item");
                                            list.Add(componentToAdd);
                                            GUI.changed = true;
                                            UndoUtility.SetDirty(options.unityObjectContext);
                                        }
                                        continue;
                                    }
                                }
                                e.Use();
                            }
                        }
                    }
                }

                //Add new default element
                if (dropRefs.Length == 0)
                {
                    if (GUILayout.Button("Add Element"))
                    {
                        UndoUtility.RecordObject(options.unityObjectContext, "Add Item");
                        var o = argType.IsValueType ? argType.CreateObjectUninitialized() : null;
                        if (listType.IsArray)
                        {
                            list = ReflectionTools.Resize((System.Array)list, list.Count + 1);
                        }
                        else
                        {
                            list.Add(o);
                        }
                        GUI.changed = true;
                        UndoUtility.SetDirty(options.unityObjectContext);
                        return(list);
                    }
                }
            }

            if (list.Count == 0)
            {
                return(list);
            }

            for (var i = 0; i < list.Count; i++)
            {
                GUILayout.BeginHorizontal();
                GUILayout.Space(16);
                GUILayout.BeginVertical();
                GUICallback(i, pickedListIndex == i && pickedList == list);
                GUILayout.EndVertical();
                var lastRect = GUILayoutUtility.GetLastRect();
                var pickRect = Rect.MinMaxRect(lastRect.xMin - 16, lastRect.yMin, lastRect.xMin, lastRect.yMax);
                GUI.color = new Color(1, 1, 1, 0.5f);
                GUI.Label(pickRect, "☰", Styles.centerLabel);
                GUI.color = Color.white;
                if (options.customItemMenu != null)
                {
                    GUILayout.Space(18);
                    var buttonRect = Rect.MinMaxRect(lastRect.xMax, lastRect.yMin, lastRect.xMax + 22, lastRect.yMax + 1);
                    EditorGUIUtility.AddCursorRect(buttonRect, MouseCursor.Link);
                    GUI.color = EditorGUIUtility.isProSkin ? Color.white : Color.grey;
                    if (GUI.Button(buttonRect, Icons.gearPopupIcon, Styles.centerLabel))
                    {
                        UndoUtility.RecordObject(options.unityObjectContext, "Menu Item");
                        options.customItemMenu(i).ShowAsContext();
                        GUI.changed = true;
                        UndoUtility.SetDirty(options.unityObjectContext);
                    }
                    GUI.color = Color.white;
                }
                if (options.allowRemove)
                {
                    GUILayout.Space(20);
                    var buttonRect = Rect.MinMaxRect(lastRect.xMax + 2, lastRect.yMin, lastRect.xMax + 20, lastRect.yMax);
                    if (GUI.Button(buttonRect, "X"))
                    {
                        UndoUtility.RecordObject(options.unityObjectContext, "Remove Item");
                        if (listType.IsArray)
                        {
                            list = ReflectionTools.Resize((System.Array)list, list.Count - 1);
                        }
                        else
                        {
                            list.RemoveAt(i);
                        }
                        GUI.changed = true;
                        UndoUtility.SetDirty(options.unityObjectContext);
                    }
                }
                GUILayout.EndHorizontal();

                GUI.color           = Color.white;
                GUI.backgroundColor = Color.white;

                EditorGUIUtility.AddCursorRect(pickRect, MouseCursor.MoveArrow);
                var boundRect = GUILayoutUtility.GetLastRect();

                if (pickRect.Contains(e.mousePosition) && e.type == EventType.MouseDown)
                {
                    pickedList      = list;
                    pickedListIndex = i;
                    e.Use();
                }

                if (pickedList == list)
                {
                    if (pickedListIndex == i)
                    {
                        GUI.Box(boundRect, string.Empty);
                    }

                    if (pickedListIndex != -1 && pickedListIndex != i && boundRect.Contains(e.mousePosition))
                    {
                        var markRect = new Rect(boundRect.x, boundRect.y - 2, boundRect.width, 2);
                        if (pickedListIndex < i)
                        {
                            markRect.y = boundRect.yMax - 2;
                        }

                        GUI.DrawTexture(markRect, Texture2D.whiteTexture);
                        if (e.type == EventType.MouseUp)
                        {
                            UndoUtility.RecordObject(options.unityObjectContext, "Reorder Item");
                            var pickObj = list[pickedListIndex];
                            list.RemoveAt(pickedListIndex);
                            list.Insert(i, pickObj);
                            GUI.changed = true;
                            UndoUtility.SetDirty(options.unityObjectContext);
                            pickedList      = null;
                            pickedListIndex = -1;
                            e.Use();
                        }
                    }
                }
            }

            //just rest in case out of rect
            if (e.rawType == EventType.MouseUp)
            {
                if (list == pickedList)
                {
                    pickedList      = null;
                    pickedListIndex = -1;
                }
            }

            return(list);
        }
        ///Returns a function that can convert from source type to target type with given func as the current value
        public static ValueHandler <T> GetConverterFuncFromTo <T>(Type sourceType, Type targetType, ValueHandler <object> func)
        {
            //assignables or upcasting
            if (targetType.RTIsAssignableFrom(sourceType) || targetType.RTIsSubclassOf(sourceType))
            {
                return(() => { return (T)func(); });
            }

            //convertibles
            if (typeof(IConvertible).RTIsAssignableFrom(targetType) && typeof(IConvertible).RTIsAssignableFrom(sourceType))
            {
                return(() => { return (T)Convert.ChangeType(func(), targetType); });
            }

            //handles implicit/explicit and prety much everything else.
            //invoke done with reflection to support all platforms.
            UnaryExpression exp = null;

            if (ReflectionTools.CanConvert(sourceType, targetType, out exp))
            {
                return(() => { try { return (T)exp.Method.Invoke(null, new object[] { func() }); } catch { return default(T); } });
            }

            ///CUSTOM CONVENIENCE CONVERSIONS
            ///----------------------------------------------------------------------------------------------

            //from anything to string
            if (targetType == typeof(string))
            {
                return(() => { try { return (T)(object)(func().ToString()); } catch { return default(T); } });
            }

            //from anything to Type
            if (targetType == typeof(Type))
            {
                return(() => { try { return (T)(object)func().GetType(); } catch { return default(T); } });
            }

            //from convertible to Vector3
            if (targetType == typeof(Vector3) && typeof(IConvertible).RTIsAssignableFrom(sourceType))
            {
                return(() =>
                {
                    var f = (float)Convert.ChangeType(func(), typeof(float));
                    return (T)(object)new Vector3(f, f, f);
                });
            }

            ///----------------------------------------------------------------------------------------------

            //from component to Vector3 (position)
            if (targetType == typeof(Vector3) && typeof(Component).RTIsAssignableFrom(sourceType))
            {
                return(() => { try { return (T)(object)((func() as Component).transform.position); } catch { return default(T); } });
            }

            //from gameobject to Vector3 (position)
            if (targetType == typeof(Vector3) && sourceType == typeof(GameObject))
            {
                return(() => { try { return (T)(object)((func() as GameObject).transform.position); } catch { return default(T); } });
            }

            //from component to Quaternion (rotation)
            if (targetType == typeof(Quaternion) && typeof(Component).RTIsAssignableFrom(sourceType))
            {
                return(() => { try { return (T)(object)((func() as Component).transform.rotation); } catch { return default(T); } });
            }

            //from gameobject to Quaternion (rotation)
            if (targetType == typeof(Quaternion) && sourceType == typeof(GameObject))
            {
                return(() => { try { return (T)(object)((func() as GameObject).transform.rotation); } catch { return default(T); } });
            }

            ///----------------------------------------------------------------------------------------------

            //from component to component
            if (typeof(Component).RTIsAssignableFrom(targetType) && typeof(Component).RTIsAssignableFrom(sourceType))
            {
                return(() => { try { return (T)(object)((func() as Component).GetComponent(targetType)); } catch { return default(T); } });
            }

            //from gameobject to component
            if (typeof(Component).RTIsAssignableFrom(targetType) && sourceType == typeof(GameObject))
            {
                return(() => { try { return (T)(object)((func() as GameObject).GetComponent(targetType)); } catch { return default(T); } });
            }

            //from component to gameobject
            if (targetType == typeof(GameObject) && typeof(Component).RTIsAssignableFrom(sourceType))
            {
                return(() => { try { return (T)(object)((func() as Component).gameObject); } catch { return default(T); } });
            }

            ///----------------------------------------------------------------------------------------------

            //From IEnumerable to IEnumerable for Lists and Arrays
            if (typeof(IEnumerable).RTIsAssignableFrom(sourceType) && typeof(IEnumerable).RTIsAssignableFrom(targetType))
            {
                try
                {
                    var elementFrom = sourceType.RTIsArray()? sourceType.GetElementType() : sourceType.GetGenericArguments().Single();
                    var elementTo   = targetType.RTIsArray()? targetType.GetElementType() : targetType.GetGenericArguments().Single();
                    if (elementTo.RTIsAssignableFrom(elementFrom))
                    {
                        var listType = typeof(List <>).RTMakeGenericType(elementTo);
                        return(() =>
                        {
                            var list = (IList)System.Activator.CreateInstance(listType);
                            foreach (var o in (IEnumerable)func())
                            {
                                list.Add(o);
                            }
                            return (T)list;
                        });
                    }
                }
                catch { return(null); }
            }

            return(null);
        }
Example #15
0
 public Expression GetBinding(FieldInfo fi)
 {
     return(Bindings.SingleEx(fb => ReflectionTools.FieldEquals(fi, fb.FieldInfo)).Binding);
 }
        private void bt_Run_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (HasSelectedAlgorithm)
                {
                    string _Error = "";
                    if (!Enviroment.CanRunAlgorithm(out _Error, AlgorithmType.Ensemble))
                    {
                        MessageBox.Show(_Error, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                    ReflectionTools _rcet = new ReflectionTools();
                    ConsensusFunction _EnsembleAlg = ReflectionTools.GetInstance<ConsensusFunction>(Tree.Value.FullName);

                    foreach (CEDS.Property _p in Tree.Value.InProperties)
                    {
                        _rcet.SetProperty(Tree.Value.FullName, _EnsembleAlg, _p);
                    }

                    List<Structuring> _structuringsParams = GetSelectedStructurings();
                    if (_structuringsParams == null || _structuringsParams.Count == 0)
                    {
                        MessageBox.Show("You must select at least one Structuring to apply an Ensemble algorithm.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                    VisualUtils.SetGlobalInProperties(_rcet, _EnsembleAlg, Tree, _structuringsParams);

                    #region OLD CODE
                    //Structuring _structuring = _EnsembleAlg.BuildStructuring();

                    //PartitionInfo _partInfo = new PartitionInfo()
                    //{
                    //    AlgorithmName = this.tb_SelectEnsembleAlg.Text,
                    //    ConsensusFunction = _EnsembleAlg,
                    //    Partition = _structuring,
                    //    AlgorithmType = AlgorithmType.Ensemble,
                    //    Index = -1
                    //};
                    //this.uctrl_ListClusterAlgVisualizerEnsemble.AddPartitionInfo(_partInfo);


                    //if (NewStructuringEventHandler != null)
                    //{
                    //    NewStructuringEventHandler(this, new NewStructuringEventArgs(_partInfo));
                    //}
                    #endregion

                    Run _run = RunMethod;
                    _run.BeginInvoke(_EnsembleAlg, RunFinish, new DataThread() { ConsensusFunction = _EnsembleAlg, Run = _run });
                }
                else
                    MessageBox.Show("You must first select an Ensemble algorithm.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception _ex)
            {
                GeneralTools.Tools.WriteToLog(_ex);
            }
        }
Example #17
0
 public bool IsId()
 {
     return(this.PropertyInfo != null && ReflectionTools.PropertyEquals(this.PropertyInfo, piId));
 }
Example #18
0
        public static FluentInclude <T> WithVirtualMList <T, L>(this FluentInclude <T> fi,
                                                                Expression <Func <T, MList <L> > > mListField,
                                                                Expression <Func <L, Lite <T>?> > backReference,
                                                                Action <L, T>?onSave   = null,
                                                                Action <L, T>?onRemove = null,
                                                                bool?lazyRetrieve      = null,
                                                                bool?lazyDelete        = null) //To avoid StackOverflows
            where T : Entity
            where L : Entity
        {
            fi.SchemaBuilder.Include <L>();

            var mListPropertRoute = PropertyRoute.Construct(mListField);

            if (fi.SchemaBuilder.Settings.FieldAttribute <IgnoreAttribute>(mListPropertRoute) == null)
            {
                throw new InvalidOperationException($"The property {mListPropertRoute} should have an IgnoreAttribute to be used as Virtual MList");
            }

            RegisteredVirtualMLists.GetOrCreate(typeof(T)).Add(typeof(L), mListPropertRoute);

            var defLazyRetrieve = lazyRetrieve ?? (typeof(L) == typeof(T));
            var defLazyDelete   = lazyDelete ?? (typeof(L) == typeof(T));

            Func <T, MList <L> >  getMList = GetAccessor(mListField);
            Action <L, Lite <T> >?setter   = null;
            bool preserveOrder             = fi.SchemaBuilder.Settings.FieldAttributes(mListPropertRoute)
                                             .OfType <PreserveOrderAttribute>()
                                             .Any();

            if (preserveOrder && !typeof(ICanBeOrdered).IsAssignableFrom(typeof(L)))
            {
                throw new InvalidOperationException($"'{typeof(L).Name}' should implement '{nameof(ICanBeOrdered)}' because '{ReflectionTools.GetPropertyInfo(mListField).Name}' contains '[{nameof(PreserveOrderAttribute)}]'");
            }

            var sb = fi.SchemaBuilder;

            if (defLazyRetrieve)
            {
                sb.Schema.EntityEvents <T>().Retrieved += (T e, PostRetrievingContext ctx) =>
                {
                    if (ShouldAvoidMListType(typeof(L)))
                    {
                        return;
                    }

                    var mlist = getMList(e);

                    if (mlist == null)
                    {
                        return;
                    }

                    var query = Database.Query <L>()
                                .Where(line => backReference.Evaluate(line) == e.ToLite());

                    MList <L> newList = preserveOrder ?
                                        query.ToVirtualMListWithOrder() :
                                        query.ToVirtualMList();

                    mlist.AssignAndPostRetrieving(newList, ctx);
                };
            }

            if (preserveOrder)
            {
                sb.Schema.EntityEvents <T>().RegisterBinding <MList <L> >(mListField,
                                                                          shouldSet: () => !defLazyRetrieve && !VirtualMList.ShouldAvoidMListType(typeof(L)),
                                                                          valueExpression: (e, rowId) => Database.Query <L>().Where(line => backReference.Evaluate(line) == e.ToLite()).ExpandLite(line => backReference.Evaluate(line), ExpandLite.ToStringLazy).ToVirtualMListWithOrder(),
                                                                          valueFunction: (e, rowId, retriever) => Schema.Current.CacheController <L>() !.Enabled ?
                                                                          Schema.Current.CacheController <L>() !.RequestByBackReference <T>(retriever, backReference, e.ToLite()).ToVirtualMListWithOrder():
                                                                          Database.Query <L>().Where(line => backReference.Evaluate(line) == e.ToLite()).ExpandLite(line => backReference.Evaluate(line), ExpandLite.ToStringLazy).ToVirtualMListWithOrder()

                                                                          );
            }
            else
            {
                sb.Schema.EntityEvents <T>().RegisterBinding(mListField,
                                                             shouldSet: () => !defLazyRetrieve && !VirtualMList.ShouldAvoidMListType(typeof(L)),
                                                             valueExpression: (e, rowId) => Database.Query <L>().Where(line => backReference.Evaluate(line) == e.ToLite()).ExpandLite(line => backReference.Evaluate(line), ExpandLite.ToStringLazy).ToVirtualMList(),
                                                             valueFunction: (e, rowId, retriever) => Schema.Current.CacheController <L>() !.Enabled ?
                                                             Schema.Current.CacheController <L>() !.RequestByBackReference <T>(retriever, backReference, e.ToLite()).ToVirtualMList() :
                                                             Database.Query <L>().Where(line => backReference.Evaluate(line) == e.ToLite()).ExpandLite(line => backReference.Evaluate(line), ExpandLite.ToStringLazy).ToVirtualMList()
                                                             );
            }

            sb.Schema.EntityEvents <T>().PreSaving += (T e, PreSavingContext ctx) =>
            {
                if (VirtualMList.ShouldAvoidMListType(typeof(L)))
                {
                    return;
                }

                var mlist = getMList(e);
                if (mlist == null)
                {
                    return;
                }

                if (mlist.Count > 0)
                {
                    var graph = Saver.PreSaving(() => GraphExplorer.FromRoot(mlist).RemoveAllNodes(ctx.Graph));
                    GraphExplorer.PropagateModifications(graph.Inverse());
                    var errors = GraphExplorer.FullIntegrityCheck(graph);
                    if (errors != null)
                    {
#if DEBUG
                        var withEntites = errors.WithEntities(graph);
                        throw new IntegrityCheckException(withEntites);
#else
                        throw new IntegrityCheckException(errors);
#endif
                    }
                }

                if (mlist.IsGraphModified)
                {
                    e.SetSelfModified();
                }
            };

            sb.Schema.EntityEvents <T>().Saving += (T e) =>
            {
                if (VirtualMList.ShouldAvoidMListType(typeof(L)))
                {
                    return;
                }

                var mlist = getMList(e);
                if (mlist == null)
                {
                    return;
                }

                if (preserveOrder)
                {
                    mlist.ForEach((o, i) => ((ICanBeOrdered)o).Order = i);
                }

                if (GraphExplorer.IsGraphModified(mlist))
                {
                    e.SetModified();
                }
            };
            sb.Schema.EntityEvents <T>().Saved += (T e, SavedEventArgs args) =>
            {
                if (VirtualMList.ShouldAvoidMListType(typeof(L)))
                {
                    return;
                }

                var mlist = getMList(e);

                if (mlist != null && !GraphExplorer.IsGraphModified(mlist))
                {
                    return;
                }

                if (!(args.WasNew || ShouldConsiderNew(typeof(T))))
                {
                    var oldElements = mlist.EmptyIfNull().Where(line => !line.IsNew);
                    var query       = Database.Query <L>()
                                      .Where(p => backReference.Evaluate(p) == e.ToLite());

                    if (onRemove == null)
                    {
                        query.Where(p => !oldElements.Contains(p)).UnsafeDelete();
                    }
                    else
                    {
                        query.Where(p => !oldElements.Contains(p)).ToList().ForEach(line => onRemove !(line, e));
                    }
                }

                if (mlist != null)
                {
                    if (mlist.Any())
                    {
                        if (setter == null)
                        {
                            setter = CreateSetter(backReference);
                        }

                        mlist.ForEach(line => setter !(line, e.ToLite()));
                        if (onSave == null)
                        {
                            mlist.SaveList();
                        }
                        else
                        {
                            mlist.ForEach(line => { if (GraphExplorer.IsGraphModified(line))
                                                    {
                                                        onSave !(line, e);
                                                    }
                                          });
                        }

                        var priv = (IMListPrivate)mlist;
                        for (int i = 0; i < mlist.Count; i++)
                        {
                            if (priv.GetRowId(i) == null)
                            {
                                priv.SetRowId(i, mlist[i].Id);
                            }
                        }
                    }
                    mlist.SetCleanModified(false);
                }
            };


            sb.Schema.EntityEvents <T>().PreUnsafeDelete += query =>
            {
                if (VirtualMList.ShouldAvoidMListType(typeof(L)))
                {
                    return(null);
                }

                //You can do a VirtualMList to itself at the table level, but there should not be cycles inside the instances
                var toDelete = Database.Query <L>().Where(se => query.Any(e => backReference.Evaluate(se).Is(e)));
                if (defLazyDelete)
                {
                    if (toDelete.Any())
                    {
                        toDelete.UnsafeDelete();
                    }
                }
                else
                {
                    toDelete.UnsafeDelete();
                }
                return(null);
            };

            return(fi);
        }
Example #19
0
 public bool IsToStringProperty()
 {
     return(PropertyRouteType == PropertyRouteType.FieldOrProperty &&
            Parent.PropertyRouteType == PropertyRouteType.Root &&
            PropertyInfo != null && ReflectionTools.PropertyEquals(PropertyInfo, piToStringProperty));
 }
        public Expression GetViewId()
        {
            var field = ViewTable.GetViewPrimaryKey();

            return(this.Bindings.SingleEx(b => ReflectionTools.FieldEquals(b.FieldInfo, field.FieldInfo)).Binding);
        }
Example #21
0
    public static object?Eval(Expression expression)
    {
        switch (expression.NodeType)
        {
        case ExpressionType.Constant:
            return(((ConstantExpression)expression).Value);

        case ExpressionType.MemberAccess:
        {
            var me = (MemberExpression)expression;
            if (me.Expression == null)
            {
                return(GetStaticGetter(me.Member)());
            }
            else
            {
                return(GetInstanceGetter(me.Member)(Eval(me.Expression)));
            }
        }

        case ExpressionType.Convert:
        {
            var conv    = (UnaryExpression)expression;
            var operand = Eval(conv.Operand);

            if (conv.Method != null)
            {
                return(GetExtensionMethodCaller(conv.Method)(operand));
            }

            if (operand is IConvertible)
            {
                return(ReflectionTools.ChangeType(operand, conv.Type));
            }

            return(operand);
        }

        case ExpressionType.Call:
        {
            var call = (MethodCallExpression)expression;
            if (call.Method.IsStatic)
            {
                if (call.Arguments.Count == 0)
                {
                    return(GetStaticMethodCaller(call.Method)());
                }
                if (call.Arguments.Count == 1)
                {
                    return(GetExtensionMethodCaller(call.Method)(Eval(call.Arguments[0])));
                }
            }
            else
            {
                if (call.Arguments.Count == 0)
                {
                    return(GetInstanceMethodCaller(call.Method)(Eval(call.Object !)));
                }
            }
            break;
        }

        case ExpressionType.Equal:
        {
            var be = (BinaryExpression)expression;
            return(object.Equals(Eval(be.Left), Eval(be.Right)));
        }

        case ExpressionType.NotEqual:
        {
            var be = (BinaryExpression)expression;
            return(!object.Equals(Eval(be.Left), Eval(be.Right)));
        }
        }

        Delegate fn;

        using (HeavyProfiler.LogNoStackTrace("Comp"))
        {
            fn = Expression.Lambda(expression).Compile();
        }

        try
        {
            return(fn.DynamicInvoke(null));
        }
        catch (TargetInvocationException ex)
        {
            ex.InnerException !.PreserveStackTrace();

            throw ex.InnerException !;
        }
    }
Example #22
0
 public static PrimaryKey Parse(string value, Type entityType)
 {
     return(new PrimaryKey((IComparable)ReflectionTools.Parse(value, Type(entityType)) !));
 }
Example #23
0
 public static PropertyInfo PropertyInfo <T>(this T entity, Expression <Func <T, object?> > property) where T : ModifiableEntity
 {
     return(ReflectionTools.GetPropertyInfo(property));
 }
Example #24
0
        static Mapping()
        {
            MappingRepository <bool> .Mapping     = GetValue(ctx => ParseHtmlBool(ctx.Input));
            MappingRepository <byte> .Mapping     = GetValue(ctx => byte.Parse(ctx.Input));
            MappingRepository <sbyte> .Mapping    = GetValue(ctx => sbyte.Parse(ctx.Input));
            MappingRepository <short> .Mapping    = GetValue(ctx => short.Parse(ctx.Input));
            MappingRepository <ushort> .Mapping   = GetValue(ctx => ushort.Parse(ctx.Input));
            MappingRepository <int> .Mapping      = GetValue(ctx => int.Parse(ctx.Input));
            MappingRepository <uint> .Mapping     = GetValue(ctx => uint.Parse(ctx.Input));
            MappingRepository <long> .Mapping     = GetValue(ctx => long.Parse(ctx.Input));
            MappingRepository <ulong> .Mapping    = GetValue(ctx => ulong.Parse(ctx.Input));
            MappingRepository <float> .Mapping    = GetValue(ctx => ctx.PropertyRoute != null && ReflectionTools.IsPercentage(Reflector.FormatString(ctx.PropertyRoute), CultureInfo.CurrentCulture) ? (float)ReflectionTools.ParsePercentage(ctx.Input, typeof(float), CultureInfo.CurrentCulture) : float.Parse(ctx.Input));
            MappingRepository <double> .Mapping   = GetValue(ctx => ctx.PropertyRoute != null && ReflectionTools.IsPercentage(Reflector.FormatString(ctx.PropertyRoute), CultureInfo.CurrentCulture) ? (double)ReflectionTools.ParsePercentage(ctx.Input, typeof(double), CultureInfo.CurrentCulture) : double.Parse(ctx.Input));
            MappingRepository <decimal> .Mapping  = GetValue(ctx => ctx.PropertyRoute != null && ReflectionTools.IsPercentage(Reflector.FormatString(ctx.PropertyRoute), CultureInfo.CurrentCulture) ? (decimal)ReflectionTools.ParsePercentage(ctx.Input, typeof(decimal), CultureInfo.CurrentCulture) : decimal.Parse(ctx.Input));
            MappingRepository <DateTime> .Mapping = GetValue(ctx => DateTime.Parse(ctx.HasInput ? ctx.Input : ctx.Inputs["Date"] + " " + ctx.Inputs["Time"]).FromUserInterface());
            MappingRepository <Guid> .Mapping     = GetValue(ctx => Guid.Parse(ctx.Input));
            MappingRepository <TimeSpan> .Mapping = GetValue(ctx =>
            {
                var dateFormatAttr = ctx.PropertyRoute.PropertyInfo.GetCustomAttribute <TimeSpanDateFormatAttribute>();
                if (dateFormatAttr != null)
                {
                    return(DateTime.ParseExact(ctx.Input, dateFormatAttr.Format, CultureInfo.CurrentCulture).TimeOfDay);
                }
                else
                {
                    return(TimeSpan.Parse(ctx.Input));
                }
            });
            MappingRepository <SqlHierarchyId> .Mapping = GetValue(ctx => SqlHierarchyId.Parse(ctx.Input));
            MappingRepository <ColorEntity> .Mapping    = GetValue(ctx => ctx.Input.HasText() ? ColorEntity.FromRGBHex(ctx.Input) : null);

            MappingRepository <bool?> .Mapping     = GetValueNullable(ctx => ParseHtmlBool(ctx.Input));
            MappingRepository <byte?> .Mapping     = GetValueNullable(ctx => byte.Parse(ctx.Input));
            MappingRepository <sbyte?> .Mapping    = GetValueNullable(ctx => sbyte.Parse(ctx.Input));
            MappingRepository <short?> .Mapping    = GetValueNullable(ctx => short.Parse(ctx.Input));
            MappingRepository <ushort?> .Mapping   = GetValueNullable(ctx => ushort.Parse(ctx.Input));
            MappingRepository <int?> .Mapping      = GetValueNullable(ctx => int.Parse(ctx.Input));
            MappingRepository <uint?> .Mapping     = GetValueNullable(ctx => uint.Parse(ctx.Input));
            MappingRepository <long?> .Mapping     = GetValueNullable(ctx => long.Parse(ctx.Input));
            MappingRepository <ulong?> .Mapping    = GetValueNullable(ctx => ulong.Parse(ctx.Input));
            MappingRepository <float?> .Mapping    = GetValueNullable(ctx => ctx.PropertyRoute != null && ReflectionTools.IsPercentage(Reflector.FormatString(ctx.PropertyRoute), CultureInfo.CurrentCulture) ? (float)ReflectionTools.ParsePercentage(ctx.Input, typeof(float), CultureInfo.CurrentCulture) : float.Parse(ctx.Input));
            MappingRepository <double?> .Mapping   = GetValueNullable(ctx => ctx.PropertyRoute != null && ReflectionTools.IsPercentage(Reflector.FormatString(ctx.PropertyRoute), CultureInfo.CurrentCulture) ? (double)ReflectionTools.ParsePercentage(ctx.Input, typeof(double), CultureInfo.CurrentCulture) : double.Parse(ctx.Input));
            MappingRepository <decimal?> .Mapping  = GetValueNullable(ctx => ctx.PropertyRoute != null && ReflectionTools.IsPercentage(Reflector.FormatString(ctx.PropertyRoute), CultureInfo.CurrentCulture) ? (decimal)ReflectionTools.ParsePercentage(ctx.Input, typeof(decimal), CultureInfo.CurrentCulture) : decimal.Parse(ctx.Input));
            MappingRepository <DateTime?> .Mapping = GetValue(ctx =>
            {
                var input = ctx.HasInput ? ctx.Input : " ".CombineIfNotEmpty(ctx.Inputs["Date"], ctx.Inputs["Time"]);
                return(input.HasText() ? DateTime.Parse(input).FromUserInterface() : (DateTime?)null);
            });
            MappingRepository <Guid?> .Mapping     = GetValueNullable(ctx => Guid.Parse(ctx.Input));
            MappingRepository <TimeSpan?> .Mapping = GetValue(ctx =>
            {
                if (ctx.Input.IsNullOrEmpty())
                {
                    return((TimeSpan?)null);
                }

                var dateFormatAttr = ctx.PropertyRoute.PropertyInfo.GetCustomAttribute <TimeSpanDateFormatAttribute>();
                if (dateFormatAttr != null)
                {
                    return(DateTime.ParseExact(ctx.Input, dateFormatAttr.Format, CultureInfo.CurrentCulture).TimeOfDay);
                }
                else
                {
                    return(TimeSpan.Parse(ctx.Input));
                }
            });

            MappingRepository <string> .Mapping = StringTrim;
        }
Example #25
0
 public static string NicePropertyName <T>(this T entity, Expression <Func <T, object?> > property) where T : ModifiableEntity
 {
     return(ReflectionTools.GetPropertyInfo(property).NiceName());
 }
Example #26
0
 public static void AssertStarted(SchemaBuilder sb)
 {
     sb.AssertDefined(ReflectionTools.GetMethodInfo(() => Start(null)));
 }
Example #27
0
 public static bool FieldEquals <S, T>(this FieldInfo fi, Expression <Func <S, T> > field)
 {
     return(ReflectionTools.FieldEquals(ReflectionTools.BaseFieldInfo(field), fi));
 }
Example #28
0
 internal static Action <T, V> Setter <V>(PropertyInfo pi)
 {
     return((Action <T, V>)cache.GetOrAdd(pi.Name, s => ReflectionTools.CreateSetter <T, V>(Reflector.FindFieldInfo(typeof(T), pi))));
 }
Example #29
0
 public static bool PropertyEquals <S, T>(this PropertyInfo pi, Expression <Func <S, T> > property)
 {
     return(ReflectionTools.PropertyEquals(ReflectionTools.BasePropertyInfo(property), pi));
 }
Example #30
0
        private static Expression RemoveConvertChain(Expression exp)
        {
            while (true)
            {
                var newExp = exp.TryRemoveConvert(t => t.UnNullify().IsEnum) ?? exp.TryRemoveConvert(t => ReflectionTools.IsIntegerNumber(t.UnNullify()));
                if (newExp == null)
                {
                    return(exp);
                }

                exp = newExp;
            }
        }
Example #31
0
        public static void Start(IApplicationBuilder app, Func <AuthTokenConfigurationEmbedded> tokenConfig, string hashableEncryptionKey)
        {
            SignumControllerFactory.RegisterArea(MethodInfo.GetCurrentMethod());

            AuthTokenServer.Start(tokenConfig, hashableEncryptionKey);

            ReflectionServer.GetContext = () => new
            {
                Culture = ReflectionServer.GetCurrentValidCulture(),
                Role    = UserEntity.Current == null ? null : RoleEntity.Current,
            };

            AuthLogic.OnRulesChanged += () => ReflectionServer.cache.Clear();

            if (TypeAuthLogic.IsStarted)
            {
                ReflectionServer.AddTypeExtension += (ti, t) =>
                {
                    if (typeof(Entity).IsAssignableFrom(t))
                    {
                        var ta = UserEntity.Current != null?TypeAuthLogic.GetAllowed(t) : null;

                        ti.Extension.Add("maxTypeAllowed", ta == null ? TypeAllowedBasic.None : ta.MaxUI());
                        ti.Extension.Add("minTypeAllowed", ta == null ? TypeAllowedBasic.None : ta.MinUI());
                        ti.RequiresEntityPack |= ta != null && ta.Conditions.Any();
                    }
                };


                EntityPackTS.AddExtension += ep =>
                {
                    var typeAllowed =
                        UserEntity.Current == null ? TypeAllowedBasic.None :
                        ep.entity.IsNew ? TypeAuthLogic.GetAllowed(ep.entity.GetType()).MaxUI() :
                        TypeAuthLogic.IsAllowedFor(ep.entity, TypeAllowedBasic.Write, true) ? TypeAllowedBasic.Write :
                        TypeAuthLogic.IsAllowedFor(ep.entity, TypeAllowedBasic.Read, true) ? TypeAllowedBasic.Read :
                        TypeAllowedBasic.None;

                    ep.extension.Add("typeAllowed", typeAllowed);
                };

                OperationController.AnyReadonly += (Lite <Entity>[] lites) =>
                {
                    return(lites.GroupBy(ap => ap.EntityType).Any(gr =>
                    {
                        var ta = TypeAuthLogic.GetAllowed(gr.Key);

                        if (ta.Min(inUserInterface: true) == TypeAllowedBasic.Write)
                        {
                            return false;
                        }

                        if (ta.Max(inUserInterface: true) <= TypeAllowedBasic.Read)
                        {
                            return true;
                        }

                        return giCountReadonly.GetInvoker(gr.Key)() > 0;
                    }));
                };
            }

            if (QueryAuthLogic.IsStarted)
            {
                ReflectionServer.AddTypeExtension += (ti, t) =>
                {
                    if (ti.QueryDefined)
                    {
                        ti.Extension.Add("queryAllowed", UserEntity.Current == null ? QueryAllowed.None : QueryAuthLogic.GetQueryAllowed(t));
                    }
                };

                ReflectionServer.AddFieldInfoExtension += (mi, fi) =>
                {
                    if (fi.DeclaringType !.Name.EndsWith("Query"))
                    {
                        mi.Extension.Add("queryAllowed", UserEntity.Current == null ? QueryAllowed.None : QueryAuthLogic.GetQueryAllowed(fi.GetValue(null) !));
                    }
                };
            }

            if (PropertyAuthLogic.IsStarted)
            {
                ReflectionServer.AddPropertyRouteExtension += (mi, pr) =>
                {
                    mi.Extension.Add("propertyAllowed", UserEntity.Current == null ? PropertyAllowed.None : pr.GetPropertyAllowed());
                };
            }

            if (OperationAuthLogic.IsStarted)
            {
                ReflectionServer.AddOperationExtension += (oits, oi, type) =>
                {
                    oits.Extension.Add("operationAllowed",
                                       UserEntity.Current == null ? false :
                                       OperationAuthLogic.GetOperationAllowed(oi.OperationSymbol, type, inUserInterface: true));
                };
            }

            if (PermissionAuthLogic.IsStarted)
            {
                ReflectionServer.AddFieldInfoExtension += (mi, fi) =>
                {
                    if (fi.FieldType == typeof(PermissionSymbol))
                    {
                        mi.Extension.Add("permissionAllowed",
                                         UserEntity.Current == null ? false :
                                         PermissionAuthLogic.IsAuthorized((PermissionSymbol)fi.GetValue(null) !));
                    }
                };
            }


            var piPasswordHash = ReflectionTools.GetPropertyInfo((UserEntity e) => e.PasswordHash);
            var pcs            = PropertyConverter.GetPropertyConverters(typeof(UserEntity));

            pcs.GetOrThrow("passwordHash").CustomWriteJsonProperty = ctx => { };
            pcs.Add("newPassword", new PropertyConverter
            {
                AvoidValidate           = true,
                CustomWriteJsonProperty = ctx => { },
                CustomReadJsonProperty  = ctx =>
                {
                    EntityJsonConverter.AssertCanWrite(ctx.ParentPropertyRoute.Add(piPasswordHash));

                    var password = (string)ctx.JsonReader.Value !;

                    var error = UserEntity.OnValidatePassword(password);
                    if (error != null)
                    {
                        throw new ApplicationException(error);
                    }

                    ((UserEntity)ctx.Entity).PasswordHash = Security.EncodePassword(password);
                }
            });
        private void bt_Run_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (HasSelectedAlgorithm)
                {
                    string _Error = "";
                    if (!Enviroment.CanRunAlgorithm(out _Error, AlgorithmType.Clustering))
                    {
                        MessageBox.Show(_Error, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                    ReflectionTools _rct = new ReflectionTools();
                    ClusterAlgorithm _ClusterAlg = ReflectionTools.GetInstance<ClusterAlgorithm>(Tree.Value.FullName);

                    foreach (CEDS.Property _p in Tree.Value.InProperties)
                    {
                        _rct.SetProperty(Tree.Value.FullName, _ClusterAlg, _p);
                    }


                    if (!VisualUtils.SetGlobalInProperties(_rct, _ClusterAlg, Tree, out _Error, this.chbx_AttrRnd.IsChecked.Value))
                    {
                        MessageBox.Show(_Error, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }

                    Run _run = RunMethod;
                    
                    _run.BeginInvoke(_ClusterAlg, RunFinish, new DataThread() { Run = _run, ClusterAlgorithm = _ClusterAlg });

                }
                else
                    MessageBox.Show("You must first select a Clustering algorithm.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception _ex)
            {
                GeneralTools.Tools.WriteToLog(_ex);
            }
        }
 //...
 void OnEnable()
 {
     titleContent = new GUIContent("Preferred Types");
     typeList     = TypePrefs.GetPreferedTypesList();
     alltypes     = ReflectionTools.GetAllTypes(true).Where(t => !t.IsGenericType && !t.IsGenericTypeDefinition).ToList();
 }
Example #34
0
        ///Call the functions assigned to the event with argument
        public bool Dispatch <T>(string message, T arg, object sender = null)
        {
            if (sender == null)
            {
                sender = this;
            }

            List <object> targets;

            if (!listeners.TryGetValue(message, out targets))
            {
                return(false);
            }

            for (var i = 0; i < targets.Count; i++)
            {
                var target = targets[i];
                if (target == null)
                {
                    continue;
                }

                MethodInfo method = null;

                if (target is Delegate)
                {
                    method = (target as Delegate).RTGetDelegateMethodInfo();
                }
                else
                {
                    method = target.GetType().GetMethod(message, METHOD_FLAGS);
                }

                if (method == null)
                {
                    Logger.LogError(string.Format("Can't resolve method {0}.{1}.", target.GetType().Name, message), "Events", target);
                    continue;
                }

                var parameters = method.GetParameters();
                if (parameters.Length > 1)
                {
                    Logger.LogError(string.Format("Parameters on method {0}.{1}, are more than 1.", target.GetType().Name, message), "Events", target);
                    continue;
                }

                object[] argsArray = null;
                if (parameters.Length == 1)
                {
                    object realArg;
                    if (typeof(MessageData).RTIsAssignableFrom(parameters[0].ParameterType))
                    {
                        realArg = new MessageData <T>(arg, this.gameObject, sender);
                    }
                    else
                    {
                        realArg = arg;
                    }
                    argsArray = ReflectionTools.SingleTempArgsArray(realArg);
                }

                if (target is Delegate)
                {
                    (target as Delegate).DynamicInvoke(argsArray);
                }
                else
                {
                    if (method.ReturnType == typeof(IEnumerator))
                    {
                        MonoManager.current.StartCoroutine((IEnumerator)method.Invoke(target, argsArray));
                    }
                    else
                    {
                        method.Invoke(target, argsArray);
                    }
                }
            }

            return(true);
        }
        private void bt_Run_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (HasSelectedMeasures)
                {
                    List<PartitionInfo> _partitionsInfo = this.uctrl_ListClusterAlgVisualizerClustEnsemble.GetSelected();
                    string _Error = "";
                    List<MeasureInfo> _MeasuresChecked = GetMeasuresChecked();
                    if (_MeasuresChecked == null || _MeasuresChecked.Count == 0)
                    {
                        _Error = "You must select at least one Validation Index.";
                        MessageBox.Show(_Error, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                    if (_partitionsInfo == null || _partitionsInfo.Count == 0)
                    {
                        _Error = "You must select at least one Structuring to apply an Validation Index.";
                        MessageBox.Show(_Error, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }

                    Structuring _realpartition = RealPartitionBuilder.BuildRealPartition(Enviroment.Set, Att_objetive);
                    List<MeasureOutput> _measuresOutput = new List<MeasureOutput>();
                    List<Measure> _measures = new List<Measure>();

                    ReflectionTools _rct = new ReflectionTools();
                    for (int i = 0; i < _MeasuresChecked.Count; i++)
                    {
                        Measure _TempMeasure = ReflectionTools.GetInstance<Measure>(_MeasuresChecked[i].Tree.Value.FullName);
                        _measures.Add(_TempMeasure);
                        foreach (CEDS.Property _p in _MeasuresChecked[i].Tree.Value.InProperties)
                        {
                            _rct.SetProperty(_MeasuresChecked[i].Tree.Value.FullName, _TempMeasure, _p);
                        }


                    }

                    Run _run = RunMethod;
                    _run.BeginInvoke(_partitionsInfo, _measures, _realpartition, _measuresOutput, _MeasuresChecked, RunFinish, _run);
                }
                else
                    MessageBox.Show("You must first select a Validation Index.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception _ex)
            {
                GeneralTools.Tools.WriteToLog(_ex);
            }
        }