void IInstanceData.Init(IDumpContext dumpContext, object obj, int id)
        {
            seenInstances = new HashSet <int>();

            this.obj = obj;
            this.id  = id;

            var type            = obj.GetType();
            var typeDataFactory = dumpContext.TypeDataFactory;

            typeData = typeDataFactory.Create(type);
            typeSize = typeData.Size;

            if (typeData.IsPureValueType)
            {
                fields = emptyFields;
                return;
            }

            var fieldDataFactory = dumpContext.FieldDataFactory;
            var instanceFields   = typeData.InstanceFields;

            fields = new List <IFieldData>(instanceFields.Count);
            foreach (var fieldInfo in instanceFields)
            {
                var fieldData = fieldDataFactory.Create(fieldInfo, obj);
                fields.Add(fieldData);
            }
        }
        public override bool Serialize(XElement node, object obj, ITypeData expectedType)
        {
            if (obj is ITestStepParent step && activeElements.Contains(node) == false)
            {
                activeElements.Add(node);
                try
                {
                    var inputs = InputOutputRelation.GetRelations(step).Where(x => x.InputObject == step).ToArray();
                    if (inputs.Length == 0)
                    {
                        return(false);
                    }
                    var items = inputs.Select(x => new InputOutputMember
                    {
                        Id = (x.OutputObject as ITestStep)?.Id ?? Guid.Empty, Member = x.OutputMember.Name, TargetMember = x.InputMember.Name
                    }).ToArray();
                    var subnode = new XElement(stepInputsName);
                    Serializer.Serialize(subnode, items, TypeData.GetTypeData(items));
                    var ok = Serializer.Serialize(node, obj, expectedType);
                    if (ok)
                    {
                        node.Add(subnode);
                    }
                    return(ok);
                }
                finally
                {
                    activeElements.Remove(node);
                }
            }

            return(false);
        }
            /// <summary> Creates an Enabled from a string. </summary>
            public object FromString(string stringdata, ITypeData _type, object contextObject, CultureInfo culture)
            {
                Type type = (_type as TypeData)?.Type;

                if (type == null)
                {
                    return(null);
                }
                if (type.DescendsTo(typeof(IEnabledValue)) == false)
                {
                    return(null);
                }
                stringdata = stringdata.Trim();
                var           disabled = "(disabled)";
                IEnabledValue enabled  = (IEnabledValue)Activator.CreateInstance(type);
                var           elemType = GetEnabledElementType(type);

                if (stringdata.StartsWith(disabled))
                {
                    if (StringConvertProvider.TryFromString(stringdata.Substring(disabled.Length).Trim(), TypeData.FromType(elemType), null, out object obj, culture))
                    {
                        enabled.Value = obj;
                    }
                    else
                    {
                        return(null);
                    }
                    enabled.IsEnabled = false;
                }
Beispiel #4
0
        void updatePropertyFromName()
        {
            if (string.IsNullOrEmpty(propertyName))
            {
                return;
            }
            else
            {
                string[] parts = propertyName.Split('|');
                if (parts.Length == 1)
                {
                    if (Step != null)
                    {
                        ITypeData stepType = TypeData.GetTypeData(Step);
                        Property = stepType.GetMember(parts[0]);
                    }
                    else
                    {
                        Property = null;
                    }
                }
                else
                {
                    var       typename = parts[0];
                    ITypeData stepType = TypeData.GetTypeData(typename);
                    Property = stepType.GetMember(parts[1]);
                }
            }

            if (Property != null)
            {
                propertyName = null;
            }
        }
Beispiel #5
0
        /// <summary> Serialization implementation. </summary>
        public override bool Serialize(XElement elem, object obj, ITypeData expectedType)
        {
            if (false == obj is ITestStep)
            {
                return(false);
            }

            var objp = Serializer.SerializerStack.OfType <ObjectSerializer>().FirstOrDefault();

            if (objp != null && objp.Object != null)
            {
                if (objp.CurrentMember.TypeDescriptor.DescendsTo(typeof(ITestStep)))
                {
                    elem.Attributes("type")?.Remove();
                    elem.Value = ((ITestStep)obj).Id.ToString();
                    return(true);
                }
                if (objp.CurrentMember.TypeDescriptor is TypeData tp)
                {
                    // serialize references in list<ITestStep>, only when they are declared by a test step and not a TestStepList.
                    if ((tp.ElementType?.DescendsTo(typeof(ITestStep)) ?? false) && objp.CurrentMember.DeclaringType.DescendsTo(typeof(ITestStep)))
                    {
                        if (tp != TypeData.FromType(typeof(TestStepList)))
                        {
                            elem.Attributes("type")?.Remove();
                            elem.Value = ((ITestStep)obj).Id.ToString();
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
        /// <summary>
        /// Turn stringdata back to an object of type 'type', if an IStringConvertProvider plugin supports the string/type. returns true if the parsing was successful.
        /// </summary>
        /// <param name="stringdata"></param>
        /// <param name="type"></param>
        /// <param name="contextObject"></param>
        /// <param name="result">The result of the operation.</param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static bool TryFromString(string stringdata, ITypeData type, object contextObject, out object result, CultureInfo culture = null)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            result = null;
            if (stringdata == null)
            {
                return(false);
            }

            culture = culture ?? CultureInfo.InvariantCulture;
            foreach (var provider in Providers)
            {
                try
                {
                    var value = provider.FromString(stringdata, type, contextObject, culture);
                    if (value != null)
                    {
                        result = value;
                        return(true);
                    }
                }
                catch
                {
                } // ignore errors. Assume unsupported value.
            }
            return(false);
        }
        /// <summary> Deserialization implementation for SecureString. </summary>
        /// <param name="node"></param>
        /// <param name="targetType"></param>
        /// <param name="setResult"></param>
        /// <returns></returns>
        public override bool Deserialize(XElement node, ITypeData targetType, Action <object> setResult)
        {
            if (targetType.IsA(typeof(System.Security.SecureString)) == false)
            {
                return(false);
            }
            string valueString = node.Value;
            var    result      = new System.Security.SecureString();

            setResult(result);
            try
            {
                string encryptedString = CryptographyHelper.Decrypt(valueString, password);
                foreach (var c in encryptedString)
                {
                    result.AppendChar(c);
                }

                return(true);
            }
            catch
            {
                return(true);
            }
        }
        /// <summary> Deserialization implementation. </summary>
        public override bool Deserialize(XElement elem, ITypeData t, Action <object> setResult)
        {
            if (t.IsA(typeof(TestStepList)) == false)
            {
                return(false);
            }
            var steps = new TestStepList();

            foreach (var subnode in elem.Elements())
            {
                ITestStep result = null;
                try
                {
                    if (!Serializer.Deserialize(subnode, x => result = (ITestStep)x))
                    {
                        Log.Warning(subnode, "Unable to deserialize step.");
                        continue; // skip to next step.
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    continue;
                }

                if (result != null)
                {
                    steps.Add(result);
                }
            }
            setResult(steps);
            return(true);
        }
Beispiel #9
0
        /// <summary> Tries to deserialize a MacroString. This is just a simple string value XML element, but it tries to find the step context for the MacroString.</summary>
        public override bool Deserialize(XElement node, ITypeData t, Action <object> setter)
        {
            if (t.IsA(typeof(MacroString)) == false)
            {
                return(false);
            }
            string text = node.Value;
            var    obj  = Serializer.SerializerStack.OfType <ObjectSerializer>().FirstOrDefault();

            if (obj != null)
            {
                setter(new MacroString(obj.Object as ITestStep)
                {
                    Text = text
                });
            }
            else
            {
                setter(new MacroString {
                    Text = text
                });
            }

            return(true);
        }
Beispiel #10
0
        /// <summary>
        /// Stores an object as a result.  These results will be propagated to the ResultStore after the TestStep completes.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="result">The result whose properties should be stored.</param>
        public void Publish <T>(T result)
        {
            if (result == null)
            {
                throw new ArgumentNullException("result");
            }
            ITypeData runtimeType = TypeData.GetTypeData(result);

            if (ResultFunc == null)
            {
                lock (resultFuncLock)
                    ResultFunc = new Dictionary <ITypeData, Func <object, ResultTable> >();
            }
            if (!ResultFunc.ContainsKey(runtimeType))
            {
                var Typename  = runtimeType.GetDisplayAttribute().GetFullName();
                var Props     = runtimeType.GetMembers().Where(x => x.Readable && x.TypeDescriptor.DescendsTo(typeof(IConvertible))).ToArray();
                var PropNames = Props.Select(p => p.GetDisplayAttribute().GetFullName()).ToArray();

                ResultFunc[runtimeType] = (v) =>
                {
                    var cols = new ResultColumn[Props.Length];
                    for (int i = 0; i < Props.Length; i++)
                    {
                        cols[i] = new ResultColumn(PropNames[i], GetArray(Props[i].TypeDescriptor.AsTypeData().Type, Props[i].GetValue(v)));
                    }
                    return(new ResultTable(Typename, cols));
                };
            }

            var res = ResultFunc[runtimeType](result);

            DoStore(res);
        }
        public void Ignored_WhenInternalSetter_DefaultsToTrue()
        {
            SerializerSettings context = new SerializerSettings();
            ITypeData          handler = context.Types[typeof(NonWritableProperty)];

            Assert.IsTrue(handler.FindProperty("InternalInt").Ignored);
        }
        public void IgnoreProperty_WhenFieldDoesntExist_ThrowsError()
        {
            SerializerSettings context = new SerializerSettings();
            ITypeData          handler = context.Type <SimpleObject>();

            handler.IgnoreProperty("Foo");
        }
Beispiel #13
0
        private static void ParseCommand(ITypeData type, string[] group, CliActionTree command)
        {
            if (command.SubCommands == null)
            {
                command.SubCommands = new List <CliActionTree>();
            }

            // If group is not empty. Find command with first group name
            if (group.Length > 0)
            {
                var existingCommand = command.SubCommands.FirstOrDefault(c => c.Name == group[0]);

                if (existingCommand == null)
                {
                    existingCommand = new CliActionTree(command, group[0]);
                    command.SubCommands.Add(existingCommand);
                }

                ParseCommand(type, group.Skip(1).ToArray(), existingCommand);
            }
            else
            {
                command.SubCommands.Add(new CliActionTree(command, type.GetDisplayAttribute().Name)
                {
                    Type = type, SubCommands = new List <CliActionTree>()
                });
                command.SubCommands.Sort((x, y) => string.Compare(x.Name, y.Name));
            }
        }
Beispiel #14
0
        /// <summary> Serialization implementation. </summary>
        public override bool Serialize(XElement elem, object sourceObj, ITypeData expectedType)
        {
            if (sourceObj is IEnumerable == false || sourceObj is string)
            {
                return(false);
            }
            IEnumerable sourceEnumerable = (IEnumerable)sourceObj;
            Type        type             = sourceObj.GetType();
            Type        genericTypeArg   = type.GetEnumerableElementType();

            if (genericTypeArg.IsNumeric())
            {
                var parser = new NumberFormatter(CultureInfo.InvariantCulture)
                {
                    UseRanges = false
                };
                elem.Value = parser.FormatRange(sourceEnumerable);
                return(true);
            }

            object prevObj = this.Object;

            try
            {
                this.Object = sourceObj;
                bool isComponentSettings = sourceObj is ComponentSettings;
                foreach (object obj in sourceEnumerable)
                {
                    var step = new XElement(Element);
                    if (obj != null)
                    {
                        type      = obj.GetType();
                        step.Name = TapSerializer.TypeToXmlString(type);
                        if (isComponentSettings)
                        {
                            ComponentSettingsSerializing.Add(obj);
                        }
                        try
                        {
                            Serializer.Serialize(step, obj, expectedType: TypeData.FromType(genericTypeArg));
                        }
                        finally
                        {
                            if (isComponentSettings)
                            {
                                ComponentSettingsSerializing.Remove(obj);
                            }
                        }
                    }

                    elem.Add(step);
                }
            }
            finally
            {
                this.Object = prevObj;
            }

            return(true);
        }
Beispiel #15
0
        public object CastConstantValue(ITypeData type, string valueStr)
        {
            Type dataType = _typeDataMapping[ModuleUtils.GetTypeFullName(type)];

            // 值或简单类型或使用Json到类或struct的转换
            return(_context.Convertor.CastConstantValue(dataType, valueStr));
        }
Beispiel #16
0
        /// <summary>
        /// Merges in the properties from the base class to the property list
        /// </summary>
        /// <param name="properties">property list to merge into</param>
        protected virtual void MergeBaseProperties(IList <IPropertyData> properties)
        {
            if (this.ForType.BaseType == typeof(object) || this.ForType.BaseType == null)
            {
                return;
            }

            ITypeData            baseTypeData = this.Settings.Types[this.ForType.BaseType];
            List <IPropertyData> baseProps    = new List <IPropertyData>(baseTypeData.AllProperties);

            foreach (IPropertyData baseProp in baseProps)
            {
                bool found = false;
                foreach (IPropertyData localProp in properties)
                {
                    if (localProp.Name == baseProp.Name)
                    {
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    properties.Add(baseProp);
                }
            }
        }
Beispiel #17
0
        /// <summary>
        /// Turn stringdata back to an object of type 'type', if an IStringConvertProvider plugin supports the string/type.
        /// </summary>
        /// <param name="stringdata"></param>
        /// <param name="type"></param>
        /// <param name="contextObject"></param>
        /// <param name="culture">If null, invariant culture is used.</param>
        /// <returns></returns>
        public static object FromString(string stringdata, ITypeData type, object contextObject, CultureInfo culture = null)
        {
            if (stringdata == null)
            {
                return(null);
            }
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            culture = culture ?? CultureInfo.InvariantCulture;
            foreach (var provider in Providers)
            {
                try
                {
                    var value = provider.FromString(stringdata, type, contextObject, culture);
                    if (value != null)
                    {
                        return(value);
                    }
                }
                catch
                {
                } // ignore errors. Assume unsupported value.
            }

            throw new FormatException(string.Format("Unable to parse '{0}' as a {1}.", stringdata, type));
        }
Beispiel #18
0
        private static void InitializeArgumentType(ISequenceManager sequenceManager,
                                                   DescriptionDataTable descriptionCollection, IArgumentDescription argumentDescription)
        {
            ArgumentDescription argDescription = (ArgumentDescription)argumentDescription;

            // 如果类型描述类为空且TypeData非空,则说明该argDescription已经被修改过,无需再执行处理
            if (argDescription.TypeDescription == null)
            {
                if (null == argDescription.Type)
                {
                    I18N i18N = I18N.GetInstance(Constants.I18nName);
                    throw new TestflowRuntimeException(ModuleErrorCode.TypeCannotLoad,
                                                       i18N.GetFStr("InvalidArgType", argDescription.Name));
                }
                return;
            }
            string fullName = GetFullName(argDescription.TypeDescription);

            if (descriptionCollection.ContainsType(fullName))
            {
                argDescription.Type = descriptionCollection.GetTypeData(fullName);
            }
            else
            {
                ITypeData typeData = sequenceManager.CreateTypeData(argDescription.TypeDescription);
                descriptionCollection.AddTypeData(fullName, typeData);
                argDescription.Type = typeData;
            }
            argDescription.TypeDescription = null;
        }
 public MacroTypeVariables(IDataEngine engine, IWalkerTypeResult result, string output,
                           AttributeParser[] attributes, ITypeData reftype) : base(result, output, attributes)
 {
     Engine  = engine;
     TYPE    = TypeData.Factory(engine, result.TypeDeclarationSyntax);
     REFTYPE = reftype;
 }
Beispiel #20
0
        public ClrmdType(ClrHeap heap, ClrType?baseType, ClrModule?module, ITypeData data)
        {
            if (data is null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            Helpers          = data.Helpers;
            MethodTable      = data.MethodTable;
            Heap             = heap;
            BaseType         = baseType;
            Module           = module;
            MetadataToken    = data.Token;
            Shared           = data.IsShared;
            StaticSize       = data.BaseSize;
            ContainsPointers = data.ContainsPointers;
            IsShared         = data.IsShared;

            // If there are no methods, preempt the expensive work to create methods
            if (data.MethodCount == 0)
            {
                _methods = Array.Empty <ClrMethod>();
            }

            DebugOnlyLoadLazyValues();
        }
Beispiel #21
0
        /// <summary> Deserialization implementation. </summary>
        public override bool Deserialize(XElement elem, ITypeData t, Action <object> setter)
        {
            if (t.DescendsTo(typeof(IDynamicStep)) == false)
            {
                return(false);
            }

            try
            {
                IDynamicStep step = (IDynamicStep)t.CreateInstance(Array.Empty <object>());
                Serializer.Register(step);

                TryDeserializeObject(elem, TypeData.GetTypeData(step), setter, step, logWarnings: false);

                ITestStep genStep = step.GetStep();
                bool      res     = true;
                if (elem.IsEmpty == false)
                {
                    res = TryDeserializeObject(elem, TypeData.GetTypeData(genStep), setter, genStep, logWarnings: false);
                }
                else
                {
                    setter(genStep);
                }
                Serializer.GetSerializer <TestStepSerializer>().FixupStep(genStep, true);
                return(res);
            }
            catch (Exception e)
            {
                Log.Error("Unable to deserialize step of type {0}. Error was: {1}", t, e.Message);

                Log.Debug(e);
                return(true);
            }
        }
        /// <summary>
        /// Called as part for the deserialization chain. Returns false if it cannot serialize the XML element.
        /// </summary>
        public override bool Deserialize(XElement node, ITypeData t, Action <object> setter)
        {
            if (t.IsA(typeof(PackageDependency)))
            {
                string name    = null;
                string version = null;
                foreach (XAttribute attr in node.Attributes())
                {
                    switch (attr.Name.LocalName)
                    {
                    case "Version":
                        version = attr.Value;
                        break;

                    case "Package":     // TAP 8.0 support
                    case "Name":
                        name = attr.Value;
                        break;

                    default:
                        Debug.Assert(false);
                        break;
                    }
                }
                setter.Invoke(new PackageDependency(name, ConvertVersion(version), version));
                return(true);
            }
            return(false);
        }
 /// <summary>
 /// Called as part for the serialization chain. Returns false if it cannot serialize the XML element.
 /// </summary>
 public override bool Serialize(XElement node, object obj, ITypeData expectedType)
 {
     if (expectedType.IsA(typeof(PackageDependency)) == false)
     {
         return(false);
     }
     node.Name = "Package";
     node.Name = "PackageDependency"; // TODO: remove when server is updated (this is only here for support of the TAP 8.x Repository server that does not yet have a parser that can handle the new name)
     node.SetAttributeValue("type", null);
     foreach (var prop in expectedType.GetMembers())
     {
         object val  = prop.GetValue(obj);
         string name = prop.Name;
         if (val == null)
         {
             continue;
         }
         if (name == "Name")
         {
             name = "Package"; // TODO: remove when server is updated (this is only here for support of the TAP 8.x Repository server that does not yet have a parser that can handle the new name)
         }
         node.SetAttributeValue(name, val);
     }
     return(true);
 }
Beispiel #24
0
        public void WhenDefaultValuesSetOnContext_PropertyInheritsFromContextIfNotSetOnType()
        {
            ISerializerSettings config   = new SerializerSettings();
            ITypeData           typeData = config.Types[typeof(SimpleObject)];

            typeData.DefaultValueSetting         = DefaultValueOption.SuppressDefaultValues;
            config.DefaultValues[typeof(string)] = "FromType";
            typeData.DefaultValues[typeof(int)]  = 22;

            IPropertyData stringProperty = config.Types[typeof(SimpleObject)].FindProperty("StringValue");

            Assert.IsFalse(stringProperty.ShouldWriteValue(config, "FromType"));
            Assert.IsTrue(stringProperty.ShouldWriteValue(config, ""));

            IPropertyData intProperty = config.Types[typeof(SimpleObject)].FindProperty("IntValue");

            Assert.IsFalse(intProperty.ShouldWriteValue(config, 22));
            Assert.IsTrue(intProperty.ShouldWriteValue(config, 0));

            IPropertyData shortProperty = config.Types[typeof(SimpleObject)].FindProperty("ShortValue");

            shortProperty.DefaultValue = (short)9;
            Assert.IsFalse(shortProperty.ShouldWriteValue(config, (short)9));
            Assert.IsTrue(shortProperty.ShouldWriteValue(config, 0));
        }
Beispiel #25
0
        public IClassInterfaceDescription GetClassDescriptionByType(ITypeData typeData, out IAssemblyInfo assemblyInfo)
        {
            string assemblyName = typeData.AssemblyName;
            ComInterfaceDescription    interfaceDescription = _descriptionData.GetComDescription(assemblyName);
            IClassInterfaceDescription classDescription     = null;

            // 如果该类型描述已存在则直接返回
            if (interfaceDescription != null &&
                null != (classDescription = interfaceDescription.Classes.FirstOrDefault(item => item.ClassType.Equals(typeData))))
            {
                assemblyInfo = interfaceDescription.Assembly;
                return(classDescription);
            }
            string path, version;

            classDescription = _loaderManager.GetClassDescription(typeData, _descriptionData, out path, out version);

            assemblyInfo = GetAssemblyInfo(assemblyName);
            TestflowRunner testflowRunner;

            if (null == assemblyInfo && null != (testflowRunner = TestflowRunner.GetInstance()))
            {
                assemblyInfo              = testflowRunner.SequenceManager.CreateAssemblyInfo();
                assemblyInfo.Path         = path;
                assemblyInfo.Version      = version;
                assemblyInfo.AssemblyName = assemblyName;
                assemblyInfo.Available    = true;
                _descriptionData.Add(assemblyInfo);
            }
            return(classDescription);
        }
        private IJsonTypeConverter GetConverter(object value)
        {
            ITypeData          handler   = Settings.Types[value.GetType()];
            IJsonTypeConverter converter = (handler.HasConverter ? handler.TypeConverter : (IJsonTypeConverter)value);

            return(converter);
        }
Beispiel #27
0
        private void SetVariableAndArgumentType(string paramValue, ITypeData type, VariableTreeTable variableTree,
                                                ISequenceFlowContainer parent)
        {
            IVariable variable;
            IArgument argument;
            string    variableName = ModuleUtils.GetVarNameByParamValue(paramValue);

            if (null != (variable = variableTree.GetVariable(variableName)))
            {
                if (!ModuleUtils.IsPropertyParam(paramValue))
                {
                    variable.Type = type;
                }
            }
            else if (null != (argument = variableTree.GetArgument(variableName)))
            {
                if (!ModuleUtils.IsPropertyParam(paramValue))
                {
                    argument.Type = type;
                }
            }
            else
            {
                ThrowIfVariableNotFound(variableName, parent);
            }
        }
        static string getAssemblyName(ITypeData _x)
        {
            var asm = _x.AsTypeData()?.Type?.Assembly;

            if (asm == null)
            {
                Log.Warning("Unable to find source of type {0}. No package dependency will be recorded for this type in the xml file.", _x.Name);
                return(null);
            }

            // dynamic or assemblies loaded from bytes cannot be located.
            if (asm.IsDynamic || string.IsNullOrWhiteSpace(asm.Location))
            {
                return(null);
            }

            try
            {
                return(Path.GetFileName(asm.Location.Replace("\\", "/")));
            }
            catch
            {
                return(null);
            }
        }
        public void IgnoredBaseProperty_SharedByChildren()
        {
            SerializerSettings context   = new SerializerSettings();
            ITypeData          child     = context.Types[typeof(ChildClass)];
            ITypeData          baseClass = context.Types[typeof(BaseClass)];

            Assert.AreSame(baseClass.FindProperty("IgnoredProperty"), child.FindProperty("IgnoredProperty"), "child IgnoredProperty");
        }
        public void OverridenBaseProperty_NotSharedByChildren()
        {
            SerializerSettings context   = new SerializerSettings();
            ITypeData          child     = context.Types[typeof(ChildClass)];
            ITypeData          baseClass = context.Types[typeof(BaseClass)];

            Assert.AreNotSame(baseClass.FindProperty("OverriddenProperty"), child.FindProperty("OverriddenProperty"), "child OverriddenProperty");
        }