示例#1
0
        public static void SetVariableOn(NamedObjectSave nos, string memberName, Type memberType, object value)
        {
            bool shouldConvertValue = false;


            if (memberType != null &&
                value is string &&
                memberType != typeof(Microsoft.Xna.Framework.Color) &&
                !CustomVariableExtensionMethods.GetIsFile(memberType) && // If it's a file, we just want to set the string value and have the underlying system do the loading
                !CustomVariableExtensionMethods.GetIsObjectType(memberType.FullName)
                )
            {
                bool isCsv = NamedObjectPropertyGridDisplayer.GetIfIsCsv(nos, memberName);
                shouldConvertValue = !isCsv &&
                                     memberType != typeof(object) &&
                                     // variable could be an object
                                     memberType != typeof(PositionedObject);
                // If the MemberType is object, then it's something we can't convert to - it's likely a state
            }

            if (shouldConvertValue)
            {
                value = PropertyValuePair.ConvertStringToType((string)value, memberType);
            }
            nos.SetPropertyValue(memberName, value);
        }
        private object ConvertValueToType(object value)
        {
            Type type = mParameterType;


            value = PropertyValuePair.ConvertStringToType((string)value, type);
            return(value);
        }
示例#3
0
        public void TestStringCreation()
        {
            ClassWithStringMember cwsm =
                PropertyValuePair.ConvertStringToType <ClassWithStringMember>("StringMember=\"Test With, comma\"");

            if (cwsm.StringMember != "Test With, comma")
            {
                throw new Exception("ConvertStringToType is not properly handling commas");
            }

            // Just making sure this doesn't throw an exception.
            string result = PropertyValuePair.ConvertStringToType
                            <string>("\"Beef = Yeah!\"");
        }
示例#4
0
        public static object ConvertValueToType(object foundValue, string csvHeaderText)
        {
            if (csvHeaderText.Contains("("))
            {
                // We should use whatever logic Glue uses here....and we should probably cache it so that it's fast
                string typeToConvertTo = CsvHeader.GetClassNameFromHeader(csvHeaderText);

                Type type = TypeManager.GetTypeFromString(typeToConvertTo);
                return(PropertyValuePair.ConvertStringToType((string)foundValue, type));
            }
            else
            {
                return(foundValue);
            }
        }
示例#5
0
        public void TestCreatingShortHandCustomObjects()
        {
            ClassWithStringMember cwsm =
                PropertyValuePair.ConvertStringToType <ClassWithStringMember>("StringMember=\"Test With Space\"");

            if (cwsm.StringMember != "Test With Space")
            {
                throw new Exception("ConvertStringToType is not properly handling shorthand conversions using spaces");
            }


            cwsm =
                PropertyValuePair.ConvertStringToType <ClassWithStringMember>("StringMember  =  \"Test With Space\"");

            if (cwsm.StringMember != "Test With Space")
            {
                throw new Exception("ConvertStringToType is not properly handling shorthand conversions using spaces");
            }
        }
示例#6
0
        private void GetFieldValueToSet(string contentManagerName, IReadOnlyList <FieldInfo> fieldInfos, int row, int column, int columnIndex, out FieldInfo fieldInfo, out bool isList, out object valueToSet)
        {
            fieldInfo = fieldInfos[columnIndex];

            var type = fieldInfo.FieldType;
            var name = fieldInfo.Name;


            isList = type.Name == "List`1";

            var typeOfObjectInCell = type;

            if (isList)
            {
                typeOfObjectInCell = type.GetGenericArguments()[0];
            }

            var cellValue = Records[row][column];

            if (string.IsNullOrEmpty(cellValue))
            {
                valueToSet = null;
            }
            else
            {
                try
                {
                    valueToSet = PropertyValuePair.ConvertStringToType(
                        Records[row][column],
                        typeOfObjectInCell,
                        contentManagerName);
                }
                catch (ArgumentException e)
                {
                    throw new Exception("Could not set variable " + name + " to " + cellValue + "\n\n" + e, e);
                }
                catch (FormatException)
                {
                    throw new Exception("Error parsing the value " + cellValue + " for the property " + name);
                }
            }
        }
        public static void OnMemberChanged(object sender, MemberChangeArgs args)
        {
            CustomVariable variable = args.Owner as CustomVariable;

            object value = args.Value;

            if (GetShouldCustomVariableBeConvertedToType(args, variable))
            {
                var variableRuntimeType = variable.GetRuntimeType();

                value = PropertyValuePair.ConvertStringToType((string)args.Value, variableRuntimeType);
            }

            if (EditorLogic.CurrentEntitySave != null)
            {
                EditorLogic.CurrentEntitySave.SetCustomVariable(EditorLogic.CurrentCustomVariable.Name, value);
            }
            else
            {
                EditorLogic.CurrentScreenSave.SetCustomVariable(EditorLogic.CurrentCustomVariable.Name, value);
            }
        }
示例#8
0
        public void TestStaticMemberReferences()
        {
            var result = PropertyValuePair.ConvertStringToType
                         <Microsoft.Xna.Framework.Color>("Red");

            if (result != Microsoft.Xna.Framework.Color.Red)
            {
                throw new Exception("Color values are not using their static members properly");
            }

            result = PropertyValuePair.ConvertStringToType
                     <Microsoft.Xna.Framework.Color>("R = 255");

            if (result.R != 255)
            {
                throw new Exception("Color values are not using their static members properly");
            }

            bool threwException = false;

            try
            {
                result = PropertyValuePair.ConvertStringToType
                         <Microsoft.Xna.Framework.Color>("Color.Red");
            }
            catch
            {
                threwException = true;
            }

            if (!threwException)
            {
                throw new Exception("The value \"Color.Red\" should throw an exception when trying to parse as Color.  " +
                                    "Values should not prefix \"Color.\"");
            }
        }
示例#9
0
        private void UpdateIncludedAndExcluded(StateSave instance)
        {
            ResetToDefault();

            ExcludeMember("InstructionSaves");
            ExcludeMember("NamedObjectPropertyOverrides");
            IElement element = ObjectFinder.Self.GetElementContaining(instance);


            for (int i = 0; i < element.CustomVariables.Count; i++)
            {
                CustomVariable customVariable = element.CustomVariables[i];

                StateSave stateSaveOwningVariable = null;

                // This doesn't share variables, so it may own the variable
                StateSaveCategory thisCategory         = GetContainingCategory(instance, element);
                List <StateSave>  statesInThisCategory = null;
                if (thisCategory != null)
                {
                    statesInThisCategory = thisCategory.States;
                }
                else
                {
                    statesInThisCategory = element.States;
                }

                foreach (StateSave stateInThisCategory in statesInThisCategory)
                {
                    if (stateInThisCategory.AssignsVariable(customVariable))
                    {
                        stateSaveOwningVariable = instance;
                    }
                }

                if (stateSaveOwningVariable == null)
                {
                    stateSaveOwningVariable = GetStateThatVariableBelongsTo(customVariable, element);
                }
                Type type = TypeManager.GetTypeFromString(customVariable.Type);

                TypeConverter typeConverter = customVariable.GetTypeConverter(CurrentElement, instance, null);

                Attribute[] customAttributes;
                if (stateSaveOwningVariable == instance ||
                    stateSaveOwningVariable == null || GetContainingCategory(instance, element) == GetContainingCategory(stateSaveOwningVariable, element))
                {
                    customAttributes = new Attribute[]
                    {
                        new CategoryAttribute("State Variable"),
                        new EditorAttribute(typeof(StateValueEditor), typeof(System.Drawing.Design.UITypeEditor))
                    };
                }
                else
                {
                    StateSaveCategory category = GetContainingCategory(stateSaveOwningVariable, element);

                    string categoryName = "Uncategorized";

                    if (category != null)
                    {
                        categoryName = category.Name;
                    }
                    customAttributes = new Attribute[]
                    {
                        // Do we want it to be readonly?  I think this may be too restrictive
                        //new ReadOnlyAttribute(true),
                        new CategoryAttribute("Variables set by other states"),
                        new DisplayNameAttribute(customVariable.Name + " set in " + categoryName)
                        //,
                        //new EditorAttribute(typeof(StateValueEditor), typeof(System.Drawing.Design.UITypeEditor))
                    };
                }


                Type typeToPass = customVariable.GetRuntimeType();
                if (typeToPass == null)
                {
                    typeToPass = typeof(string);
                }

                IncludeMember(
                    customVariable.Name,
                    typeToPass,
                    delegate(object sender, MemberChangeArgs args)
                {
                    object value = args.Value;

                    // May 16, 2012
                    // This crashed if
                    // the type was a Texture2D.
                    // I don't think we ever want
                    // to set the value on a StateSave
                    // to an actual Texture2D - rather it
                    // should be a string.  I don't think it
                    // should ever be any loaded file, in fact,
                    // so we should prob make sure it's not a file
                    // by adding a check.
                    if (CustomVariablePropertyGridDisplayer.GetShouldCustomVariableBeConvertedToType(args, customVariable))
                    {
                        value = PropertyValuePair.ConvertStringToType((string)args.Value, customVariable.GetRuntimeType());
                    }

                    instance.SetValue(args.Member, value);
                }

                    ,
                    delegate()
                {
                    return(GetValue(customVariable.Name));
                },
                    typeConverter,
                    customAttributes


                    );
            }


            //if (false)
            //{

            //    #region Add the Object Overrides

            //    Type namedObjectPropertyOverrideType = typeof(NamedObjectPropertyOverride);
            //    TypeConverter expandableTypeConverter = new ExpandableObjectConverter();

            //    List<NamedObjectSave> namedObjectList = element.NamedObjects;

            //    pdc = AddNamedObjectOverrides(pdc, namedObjectPropertyOverrideType, expandableTypeConverter, namedObjectList);

            //    #endregion
            //}
        }
        private static object GetDefaultValueFor(NamedObjectSave nos, string property, string overridingType)
        {
            if (!string.IsNullOrEmpty(overridingType))
            {
                Type overridingTypeAsType = TypeManager.GetTypeFromString(overridingType);


                string valueAsString = TypeManager.GetDefaultForType(overridingType);

                return(PropertyValuePair.ConvertStringToType(valueAsString, overridingTypeAsType));
            }



            switch (nos.SourceType)
            {
            case SourceType.File:

                if (!string.IsNullOrEmpty(nos.SourceFile) && !string.IsNullOrEmpty(nos.SourceNameWithoutParenthesis))
                {
                    string absoluteFileName = ProjectManager.MakeAbsolute(nos.SourceFile, true);



                    return(ContentParser.GetValueForProperty(absoluteFileName, nos.SourceNameWithoutParenthesis, property));
                }



                break;

            case SourceType.Entity:
                if (!string.IsNullOrEmpty(nos.SourceClassType))
                {
                    IElement element = ObjectFinder.Self.GetIElement(nos.SourceClassType);

                    if (element != null)
                    {
                        CustomVariable customVariable = element.GetCustomVariable(property);

                        if (customVariable != null)
                        {
                            return(GetDefaultValueFor(customVariable, element));
                        }
                        else if (property == "Visible" && element is EntitySave &&
                                 ((EntitySave)element).ImplementsIVisible)
                        {
                            return(true);
                        }
                        else if (property == "Enabled" && element is EntitySave &&
                                 ((EntitySave)element).ImplementsIWindow)
                        {
                            return(true);
                        }
                    }
                }
                break;

            case SourceType.FlatRedBallType:
                if (!string.IsNullOrEmpty(nos.SourceClassType))
                {
                    // See if there is a variable set for this already - there may be
                    // now that we allow users to specify values right on FlatRedBall-type
                    // NamedObjectSaves
                    InstructionSave instructionSave = nos.GetCustomVariable(property);
                    if (instructionSave != null && instructionSave.Value != null)
                    {
                        return(instructionSave.Value);
                    }
                    else
                    {
                        object value = GetExceptionForFlatRedBallTypeDefaultValue(nos, property);

                        if (value != null)
                        {
                            return(value);
                        }
                        else
                        {
                            string classType = nos.SourceClassType;

                            value = GetDefaultValueForPropertyInType(property, classType);

                            return(value);
                        }
                    }
                }

                break;
            }

            return(null);
        }
示例#11
0
        private bool AsssignValuesOnElement(string contentManagerName, MemberTypeIndexPair[] memberTypeIndexPairs, List <PropertyInfo> propertyInfos, List <FieldInfo> fieldInfos, int numberOfColumns, object lastElement, bool wasRequiredMissing, int row, object newElement)
        {
            for (var column = 0; column < numberOfColumns; column++)
            {
                if (memberTypeIndexPairs[column].Index == -1)
                {
                    continue;
                }
                var objectToSetValueOn = newElement;
                if (wasRequiredMissing)
                {
                    objectToSetValueOn = lastElement;
                }
                var columnIndex = memberTypeIndexPairs[column].Index;

                var isRequired = Headers[column].IsRequired;

                if (isRequired && string.IsNullOrEmpty(Records[row][column]))
                {
                    wasRequiredMissing = true;
                    continue;
                }

                #region If the member is a Property, so set the value obtained from converting the string.
                if (memberTypeIndexPairs[column].MemberType == MemberTypes.Property)
                {
                    var propertyInfo = propertyInfos[memberTypeIndexPairs[column].Index];

                    var propertyType = propertyInfo.PropertyType;

                    var isList = propertyInfo.PropertyType.Name == "List`1";
                    if (isList)
                    {
                        propertyType = propertyType.GetGenericArguments()[0];
                    }

                    object valueToSet;

                    var cellValue = Records[row][column];
                    if (string.IsNullOrEmpty(cellValue))
                    {
                        valueToSet = null;
                    }
                    else
                    {
                        try
                        {
                            valueToSet = PropertyValuePair.ConvertStringToType(
                                Records[row][column],
                                propertyType,
                                contentManagerName);
                        }
                        catch (ArgumentException e)
                        {
                            throw new Exception("Could not set variable " + propertyInfo.Name + " to " + cellValue + "\n\n" + e, e);
                        }
                        catch (FormatException)
                        {
                            throw new Exception("Error parsing the value " + cellValue + " for the property " + propertyInfo.Name);
                        }
                    }

                    if (isList)
                    {
                        // todo - need to support adding to property lists
                        var objectToCallOn = propertyInfo.GetValue(objectToSetValueOn, null);
                        if (objectToCallOn == null)
                        {
                            objectToCallOn = Activator.CreateInstance(propertyInfo.PropertyType);

                            propertyInfo.SetValue(objectToSetValueOn, objectToCallOn, null);
                        }

                        if (valueToSet == null)
                        {
                            continue;
                        }
                        var methodInfo = propertyInfo.PropertyType.GetMethod("Add");

                        if (methodInfo != null)
                        {
                            methodInfo.Invoke(objectToCallOn, new[] { valueToSet });
                        }
                    }
                    else if (!wasRequiredMissing)
                    {
                        propertyInfo.SetValue(
                            objectToSetValueOn,
                            valueToSet,
                            null);
                    }
                }
                #endregion

                else if (memberTypeIndexPairs[column].MemberType == MemberTypes.Field)
                {
                    {
                        GetFieldValueToSet(contentManagerName, fieldInfos, row, column, columnIndex, out var fieldInfo,
                                           out var isList, out var valueToSet);

                        if (isList)
                        {
                            object objectToCallOn = fieldInfo.GetValue(objectToSetValueOn);
                            if (objectToCallOn == null)
                            {
                                objectToCallOn = Activator.CreateInstance(fieldInfo.FieldType);

                                fieldInfo.SetValue(objectToSetValueOn, objectToCallOn);
                            }

                            if (valueToSet != null)
                            {
                                MethodInfo methodInfo = fieldInfo.FieldType.GetMethod("Add");

                                if (methodInfo != null)
                                {
                                    methodInfo.Invoke(objectToCallOn, new[] { valueToSet });
                                }
                            }
                        }
                        else if (!wasRequiredMissing)
                        {
                            fieldInfo.SetValue(objectToSetValueOn, valueToSet);
                        }
                    }
                }
            }

            return(wasRequiredMissing);
        }
        private bool AsssignValuesOnElement(string contentManagerName, MemberTypeIndexPair[] memberTypeIndexPairs, List <PropertyInfo> propertyInfos, List <FieldInfo> fieldInfos, int numberOfColumns, object lastElement, bool wasRequiredMissing, int row, object newElement)
        {
            for (int column = 0; column < numberOfColumns; column++)
            {
                if (memberTypeIndexPairs[column].Index != -1)
                {
                    object objectToSetValueOn = newElement;
                    if (wasRequiredMissing)
                    {
                        objectToSetValueOn = lastElement;
                    }
                    int columnIndex = memberTypeIndexPairs[column].Index;

                    bool isRequired = Headers[column].IsRequired;

                    if (isRequired && string.IsNullOrEmpty(Records[row][column]))
                    {
                        wasRequiredMissing = true;
                        continue;
                    }

                    #region If the member is a Property, so set the value obtained from converting the string.
                    if (memberTypeIndexPairs[column].MemberType == MemberTypes.Property)
                    {
                        PropertyInfo propertyInfo = propertyInfos[memberTypeIndexPairs[column].Index];

                        var propertyType = propertyInfo.PropertyType;

                        bool isList = propertyInfo.PropertyType.Name == "List`1";
                        if (isList)
                        {
                            propertyType = propertyType.GetGenericArguments()[0];
                        }

                        string valueAtRowColumn = Records[row][column];

                        object valueToSet = null;

                        string cellValue = Records[row][column];
                        if (string.IsNullOrEmpty(cellValue))
                        {
                            valueToSet = null;
                        }
                        else
                        {
                            try
                            {
                                valueToSet = PropertyValuePair.ConvertStringToType(
                                    Records[row][column],
                                    propertyType,
                                    contentManagerName);
                            }
                            catch (ArgumentException e)
                            {
                                throw new Exception("Could not set variable " + propertyInfo.Name + " to " + cellValue + "\n\n" + e, e);
                            }
                            catch (FormatException)
                            {
                                throw new Exception("Error parsing the value " + cellValue + " for the property " + propertyInfo.Name);
                            }
                        }

                        if (isList)
                        {
                            // todo - need to support adding to property lists
                            object objectToCallOn = propertyInfo.GetValue(objectToSetValueOn, null);
                            if (objectToCallOn == null)
                            {
                                objectToCallOn = Activator.CreateInstance(propertyInfo.PropertyType);

                                propertyInfo.SetValue(objectToSetValueOn, objectToCallOn, null);
                            }

                            if (valueToSet != null)
                            {
                                MethodInfo methodInfo = propertyInfo.PropertyType.GetMethod("Add");

                                methodInfo.Invoke(objectToCallOn, new object[] { valueToSet });
                            }
                        }
                        else if (!wasRequiredMissing)
                        {
                            propertyInfo.SetValue(
                                objectToSetValueOn,
                                valueToSet,
                                null);
                        }
                    }
                    #endregion

                    #region Else, it's a Field, so set the value obtained from converting the string.
                    else if (memberTypeIndexPairs[column].MemberType == MemberTypes.Field)
                    {
                        //try
                        {
                            FieldInfo fieldInfo;
                            bool      isList;
                            object    valueToSet;
                            GetFieldValueToSet(contentManagerName, fieldInfos, row, column, columnIndex, out fieldInfo, out isList, out valueToSet);

                            if (isList)
                            {
                                // Check to see if the list is null.
                                // If so, create it. We want to make the
                                // list even if we're not going to add anything
                                // to it.  Maybe we'll change this in the future
                                // to improve memory usage?
                                object objectToCallOn = fieldInfo.GetValue(objectToSetValueOn);
                                if (objectToCallOn == null)
                                {
                                    objectToCallOn = Activator.CreateInstance(fieldInfo.FieldType);

                                    fieldInfo.SetValue(objectToSetValueOn, objectToCallOn);
                                }

                                if (valueToSet != null)
                                {
                                    MethodInfo methodInfo = fieldInfo.FieldType.GetMethod("Add");

                                    methodInfo.Invoke(objectToCallOn, new object[] { valueToSet });
                                }
                            }
                            else if (!wasRequiredMissing)
                            {
                                fieldInfo.SetValue(objectToSetValueOn, valueToSet);
                            }
                        }
                        // May 5, 2011:
                        // This code used
                        // to try/catch and
                        // just throw away failed
                        // attempts to instantiate
                        // a new object.  This caused
                        // debugging problems.  I think
                        // we should be stricter with this
                        // and let the exception occur so that
                        // developers can fix any problems related
                        // to CSV deseiralization.  Silent bugs could
                        // be difficult/annoying to track down.
                        //catch
                        //{
                        //    // don't worry, just skip for now.  May want to log errors in the future if this
                        //    // throw-away of exceptions causes difficult debugging.
                        //    newElementFailed = true;
                        //    break;
                        //}
                    }
                    #endregion
                }
            }

            return(wasRequiredMissing);
        }