public void Test_Basic()
        {
            foreach (var testCase in TestCases)
            {
                var type     = testCase.Type;
                var typeName = type.Name;

                var classDescriptor = ClassDescriptor.GetClassDescriptor(type);

                TestFor.Equality(
                    testCase.IsNullable,
                    classDescriptor.IsNullable,
                    "{0} should {1}be nullable".FormatWith(typeName, GetNegation(testCase.IsNullable))
                    );

                TestFor.Equality(
                    testCase.IsListLike,
                    classDescriptor.IsListLike,
                    "{0} should {1}be list like".FormatWith(typeName, GetNegation(testCase.IsListLike))
                    );

                TestFor.Equality(
                    testCase.IsDictionaryLike,
                    classDescriptor.IsDictionaryLike,
                    "{0} should not {1}dictionary like".FormatWith(typeName, GetNegation(testCase.IsDictionaryLike))
                    );
            }
        }
Esempio n. 2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        private int ContainsValue(IEnumerable <Object> collection, Object value)
        {
            ClassDescriptor classDescriptor = ClassDescriptor.GetClassDescriptor(value.GetType());
            int             index           = 0;

            if (classDescriptor.StrictObjectGraphRequired)
            {
                foreach (var item in collection)
                {
                    if (item == value)
                    {
                        return(index);
                    }
                    index++;
                }
                return(-1);
            }
            else
            {
                foreach (var item in collection)
                {
                    if (item.Equals(value))
                    {
                        return(index);
                    }
                    index++;
                }
                return(-1);
            }
        }
Esempio n. 3
0
        public void InheritAttributes(MetaMetadataField inheritFrom)
        {
            var classDescriptor = ClassDescriptor.GetClassDescriptor(this);

            foreach (MetaMetadataFieldDescriptor fieldDescriptor in classDescriptor.AllFieldDescriptors)
            {
                if (fieldDescriptor.IsInheritable)
                {
                    ScalarType scalarType = fieldDescriptor.ScalarType;
                    try
                    {
                        if (scalarType != null &&
                            scalarType.IsDefaultValue(fieldDescriptor.Field, this) &&
                            !scalarType.IsDefaultValue(fieldDescriptor.Field, inheritFrom))
                        {
                            Object value = fieldDescriptor.Field.GetValue(inheritFrom);
                            fieldDescriptor.Field.SetValue(this, value);
                            Debug.WriteLine("inherit\t" + this.Name + "." + fieldDescriptor.Name + "\t= " + value);
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(inheritFrom.Name + " doesn't have field " + fieldDescriptor.Name + ", ignore it.");
                        //					e.printStackTrace();
                    }
                }
            }
        }
        public void EquivilantListsAndMapsAreTreatedCorreclty()
        {
            var classA = createInstance();
            var classB = createInstance();


            Assert.IsTrue(ClassDescriptor.GetClassDescriptor(classA.GetType()).AllFieldDescriptors.Count() == 2, "Incorrect number of field descriptors");
            Assert.IsFalse(classA == classB, "Should be different instances");
            Assert.IsFalse(TestMethods.CompareOriginalObjectToDeserializedObject(classA, classB).Any(), "Class A and B should be the same... their collections are equivilant.");
        }
        //          [TestMethod]
        /// <summary>
        /// AllDependent types should return all types that need to be added to the type scope
        /// </summary>
        public void TypeExtension_AllDepTypesIncludesFieldsPropertiesAndSelf()
        {
            var AllDepTypes = TypeExtensions.GetAllDependentTypes(typeof(SimplTestClassWithFieldsAndPropertiesOfAllScopes));


            var cdReal = ClassDescriptor.GetClassDescriptor(typeof(SimplTestClassWithFieldsAndPropertiesOfAllScopes));

            var cdRealObj = ClassDescriptor.GetClassDescriptor(new SimplTestClassWithFieldsAndPropertiesOfAllScopes());

            Assert.AreEqual(9, AllDepTypes.Count());
        }
Esempio n. 6
0
        public void TestGenericField()//ported from simplTestCases tests.generics.TestSimplGenerics.java
        {
            // Search.results
            ClassDescriptor       c     = ClassDescriptor.GetClassDescriptor(typeof(Search <>));
            List <GenericTypeVar> cvars = c.GetGenericTypeVars();
            FieldDescriptor       f     = c.GetFieldDescriptorByFieldName("searchResults");
            List <GenericTypeVar> vars  = f.GetGenericTypeVars();
            GenericTypeVar        var1  = vars[0];

            Assert.AreEqual(var1.Name, "T");
            Assert.AreSame(var1.ReferredGenericTypeVar, cvars[0]);

            // MediaSearch.results
            c     = ClassDescriptor.GetClassDescriptor(typeof(MediaSearch <,>));
            cvars = c.GetGenericTypeVars();
            f     = c.GetFieldDescriptorByFieldName("searchResults");
            vars  = f.GetGenericTypeVars();
            var1  = vars[0];
            Assert.AreEqual(var1.Name, "T");
            Assert.AreSame(var1.ReferredGenericTypeVar, cvars[1]);

            // MediaSearch.firstResult
            f    = c.GetFieldDescriptorByFieldName("firstResult");
            vars = f.GetGenericTypeVars();
            var1 = vars[0];
            Assert.AreSame(var1.ClassDescriptor, ClassDescriptor.GetClassDescriptor(typeof(Media)));

            // MediaSearchResult.media
            c     = ClassDescriptor.GetClassDescriptor(typeof(MediaSearchResult <>));
            cvars = c.GetGenericTypeVars();
            f     = c.GetFieldDescriptorByFieldName("media");
            vars  = f.GetGenericTypeVars();
            var1  = vars[0];
            Assert.AreEqual(var1.Name, "M");
            Assert.AreSame(var1.ReferredGenericTypeVar, cvars[0]);

            // MeidaSearchResult.ms
            f    = c.GetFieldDescriptorByFieldName("ms");
            vars = f.GetGenericTypeVars();
            var1 = vars[0];
            Assert.AreEqual(var1.Name, "M");
            Assert.AreSame(var1.ReferredGenericTypeVar, cvars[0]);
            GenericTypeVar var2 = vars[1];

            Assert.AreSame(var2.ClassDescriptor, ClassDescriptor.GetClassDescriptor(typeof(MediaSearchResult <>)));
            List <GenericTypeVar> var2args = var2.GenericTypeVarArgs;

            Assert.AreEqual(var2args.Count, 1);
            GenericTypeVar var2arg1 = var2args[0];

            Assert.AreEqual(var2arg1.Name, "M");
            Assert.AreSame(var2arg1.ReferredGenericTypeVar, cvars[0]);
        }
Esempio n. 7
0
        public void CompositeClassEmitsCorrectClassDescriptor()
        {
            var containerDescriptor = ClassDescriptor.GetClassDescriptor(typeof(Container));
            var wcBaseDescriptor    = ClassDescriptor.GetClassDescriptor(typeof(WcBase));

            var wcDesc = containerDescriptor.GetFieldDescriptorByFieldName("wc");

            Assert.IsTrue(wcDesc != null, "No field descriptor for wc!");
            Assert.AreEqual(typeof(WcBase), wcDesc.Field.FieldType);
            Assert.IsTrue(ClassDescriptor.GetClassDescriptor(wcDesc.Field.FieldType).Equals(wcBaseDescriptor), string.Format("wc Field type is not correct! {0} | {1}", wcDesc, ClassDescriptor.GetClassDescriptor(wcDesc.Field.MemberType)));

            var instance = new Container(new WcBase(1));
        }
Esempio n. 8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="textWriter"></param>
        /// <param name="translationContext"></param>
        public override void Serialize(object obj, TextWriter textWriter, TranslationContext translationContext)
        {
            translationContext.ResolveGraph(obj);
            ClassDescriptor rootObjectClassDescriptor = ClassDescriptor.GetClassDescriptor(obj.GetType());

            try
            {
                Serialize(obj, rootObjectClassDescriptor.PseudoFieldDescriptor, textWriter, translationContext);
            }
            catch (Exception ex)
            {
                throw new SimplTranslationException("IO exception occured: ", ex);
            }
        }
        public void TypeDescriptorEmittedCorrectlyForMapAndListFields()
        {
            var collectionAndMaps = createInstance();

            var typeDescriptor = ClassDescriptor.GetClassDescriptor(collectionAndMaps.GetType());

            var listDescriptor = typeDescriptor.FieldDescriptorByFieldName["list"];

            Assert.IsTrue(listDescriptor.IsCollection, "A list is a collection");

            var mapDescriptor = typeDescriptor.FieldDescriptorByFieldName["map"];

            Assert.IsTrue(listDescriptor.IsCollection, "A map is also a collection.");
        }
Esempio n. 10
0
        public void TestClassGenerics()//ported from simplTestCases tests.generics.TestSimplGenerics.java
        {
            // case 1: constraint is a concrete class
            ClassDescriptor       c    = ClassDescriptor.GetClassDescriptor(typeof(Search <>));
            List <GenericTypeVar> vars = c.GetGenericTypeVars();

            Assert.AreEqual(vars.Count, 1);
            GenericTypeVar var1 = vars[0];

            Assert.AreEqual(var1.Name, "T");
            Assert.AreSame(var1.ConstraintClassDescriptor, ClassDescriptor.GetClassDescriptor(typeof(SearchResult)));

            // case 2: constraint is parameterized
            c    = ClassDescriptor.GetClassDescriptor(typeof(MediaSearch <,>));
            vars = c.GetGenericTypeVars();
            Assert.AreEqual(vars.Count, 2);
            var1 = vars[0];
            GenericTypeVar var2 = vars[1];

            Assert.AreEqual(var2.Name, "T");
            Assert.AreSame(var2.ConstraintClassDescriptor, ClassDescriptor.GetClassDescriptor(typeof(MediaSearchResult <>)));
            List <GenericTypeVar> var2args = var2.ConstraintGenericTypeVarArgs;

            Assert.AreEqual(var2args.Count, 1);
            GenericTypeVar var2arg1 = var2args[0];

            Assert.AreEqual(var2arg1.Name, "M");
            Assert.AreSame(var2arg1.ReferredGenericTypeVar, var1);

            // case 3: constraint is parameterized
            c    = ClassDescriptor.GetClassDescriptor(typeof(ImageSearch <, ,>));
            vars = c.GetGenericTypeVars();
            Assert.AreEqual(vars.Count, 3);
            var1 = vars[0];
            var2 = vars[1];
            GenericTypeVar var3 = vars[2];

            Assert.AreEqual(var2.Name, "X");
            Assert.AreSame(var2.ConstraintGenericTypeVar, var1);
            Assert.AreEqual(var3.Name, "T");
            Assert.AreSame(var3.ConstraintClassDescriptor, ClassDescriptor.GetClassDescriptor(typeof(MediaSearchResult <>)));
            List <GenericTypeVar> var3args = var3.ConstraintGenericTypeVarArgs;

            Assert.AreEqual(var3args.Count, 1);
            GenericTypeVar var3arg1 = var3args[0];

            Assert.AreEqual(var3arg1.Name, "X");
            Assert.AreSame(var3arg1.ReferredGenericTypeVar, var2);
        }
Esempio n. 11
0
        /**
         * For the root, compare the meta-metadata from the binding with the one we started with. Down the
         * hierarchy, try to perform similar bindings.
         */
        public void DeserializationPreHook(MetadataNS.Metadata deserializedMetadata, MetadataFieldDescriptor mfd)
        {
            if (deserializingRoot)
            {
                deserializingRoot = false;
                Document document = GetDocument();
                MetaMetadataCompositeField preMM = document.MetaMetadata;
                MetadataClassDescriptor    mcd   = (MetadataClassDescriptor)ClassDescriptor.GetClassDescriptor(deserializedMetadata);;
                MetaMetadataCompositeField metaMetadata;
                String tagName = mcd.TagName;
                if (preMM.GetTagForTranslationScope().Equals(tagName))
                {
                    metaMetadata = preMM;
                }
                else
                {               // just match in translation scope
                    //TODO use local TranslationScope if there is one
                    metaMetadata = SemanticsSessionScope.MetaMetadataRepository.GetMMByName(tagName);
                }
                deserializedMetadata.MetaMetadata = metaMetadata;

                currentMMstack.Push(metaMetadata);
            }
            else
            {
                String mmName = mfd.MmName;
                MetaMetadataNestedField currentMM     = currentMMstack.Peek();
                MetaMetadataNestedField childMMNested = (MetaMetadataNestedField)currentMM.LookupChild(mmName);              // this fails for collections :-(
                if (childMMNested == null)
                {
                    throw new Exception("Can't find composite child meta-metadata for " + mmName + " amidst " + mfd +
                                        "\n\tThis probably means there is a conflict between the meta-metadata repository and the runtime." +
                                        "\n\tProgrammer: Have you Changed the fields in built-in Metadata subclasses without updating primitives.xml???!");
                }
                MetaMetadataCompositeField childMMComposite = null;
                if (childMMNested.IsPolymorphicInherently)
                {
                    String tagName = ClassDescriptor.GetClassDescriptor(deserializedMetadata).TagName;
                    childMMComposite = SemanticsSessionScope.MetaMetadataRepository.GetMMByName(tagName);
                }
                else
                {
                    childMMComposite = childMMNested.GetMetaMetadataCompositeField();
                }
                deserializedMetadata.MetaMetadata = childMMComposite;
                currentMMstack.Push(childMMComposite);
            }
        }
        MetadataClassDescriptor GetMetadataClassDescriptor(SimplTypesScope metadataTScope)
        {
            MetadataClassDescriptor metadataCd = this.metadataClassDescriptor;

            if (metadataCd == null)
            {
                //this.InheritMetaMetadata(null); //edit

                String metadataClassSimpleName = this.GetMetadataClassSimpleName();
                // first look up by simple name, since package names for some built-ins are wrong

                metadataCd =
                    (MetadataClassDescriptor)metadataTScope.GetClassDescriptorBySimpleName(metadataClassSimpleName);
                if (metadataCd == null)
                {
                    String metadataClassName = this.GetMetadataClassName();

                    metadataCd = (MetadataClassDescriptor)metadataTScope.GetClassDescriptorByClassName(metadataClassName);
                    if (metadataCd == null)
                    {
                        try
                        {
                            Type metadataType = Type.GetType(metadataClassName) ??
                                                Type.GetType(metadataClassName +
                                                             AsemblyQualifiedNameForGeneratedSemantics);
                            this.metadataClass = metadataType;
                            if (MetadataClass != null)
                            {
                                metadataCd = (MetadataClassDescriptor)ClassDescriptor.GetClassDescriptor(MetadataClass);
                                metadataTScope.AddTranslation(MetadataClass);
                            }
                            else
                            {
                                Debug.WriteLineIf(BigSemanticsSettings.DebugLevel > 5, "Cannot find metadata class " + metadataClassName + " for " + this);
                            }
                        }
                        catch (Exception e)
                        {
                            Debug.WriteLine("Exception: " + e.Message);
                            Debug.WriteLine("Stacktrace:\n" + e.StackTrace);
                            Debug.WriteLine("Cannot find metadata class " + metadataClassName + " for " + this);
                        }
                    }
                }
            }
            return(metadataCd);
        }
Esempio n. 13
0
        public void SimplPolymorphicCompositeFieldDescriptorFollowsTagNameConventions()
        {
            // The case below double covers this slightly, but this makes the issue a bit easier to uncover.


            var v = new InternalPolymorphicCompositeTestClass(3, true);

            ClassDescriptor cd = ClassDescriptor.GetClassDescriptor(v);

            var polymorphicField = cd.FieldDescriptorByFieldName["polyMorph"];

            Assert.AreEqual("polyMorph", polymorphicField.Name, "Name incorrect!");
            Assert.AreEqual("poly_morph", polymorphicField.TagName, "Tag name incorrect!");

            Assert.IsTrue(polymorphicField.IsPolymorphic, "Should be polymorphic!");


            var psuedoDescriptor = ClassDescriptor.GetClassDescriptor(v.polyMorph).PseudoFieldDescriptor;

            Assert.AreEqual("polyMorph", psuedoDescriptor.Name, "Psuedo Descriptor is wrecking life.");
            Assert.AreEqual("poly_morph", psuedoDescriptor.TagName, "Psuedo descriptor is again messing stuff up.");
        }
Esempio n. 14
0
        public void TestSuperClassGenerics()//ported from simplTestCases tests.generics.TestSimplGenerics.java
        {
            // public class FlickrSearchResult extends MediaSearchResult<Image>
            ClassDescriptor       c      = ClassDescriptor.GetClassDescriptor(typeof(FlickrSearchResult));
            List <GenericTypeVar> scvars = c.GetSuperClassGenericTypeVars();

            Assert.AreEqual(scvars.Count, 1);
            GenericTypeVar var1 = scvars[0];

            Assert.AreSame(var1.ClassDescriptor, ClassDescriptor.GetClassDescriptor(typeof(Image)));

            // public class MediaSearch<M extends Media, T extends MediaSearchResult<M>> extends Search<T>
            c = ClassDescriptor.GetClassDescriptor(typeof(MediaSearch <,>));
            List <GenericTypeVar> vars = c.GetGenericTypeVars();

            scvars = c.GetSuperClassGenericTypeVars();
            Assert.AreEqual(scvars.Count, 1);
            var1 = scvars[0];
            Assert.AreEqual(var1.Name, "T");
            Assert.AreSame(var1.ReferredGenericTypeVar, vars[1]);

            // public class ImageSearch<I extends Image, X extends I, T extends MediaSearchResult<X>> extends MediaSearch<X, T>
            c      = ClassDescriptor.GetClassDescriptor(typeof(ImageSearch <, ,>));
            vars   = c.GetGenericTypeVars();
            scvars = c.GetSuperClassGenericTypeVars();
            Assert.AreEqual(scvars.Count, 2);
            var1 = scvars[0];
            Assert.AreEqual(var1.Name, "X");
            Assert.AreSame(var1.ReferredGenericTypeVar, vars[1]);
            GenericTypeVar var2 = scvars[1];

            Assert.AreSame(var2.ClassDescriptor, ClassDescriptor.GetClassDescriptor(typeof(MediaSearchResult <>)));
            Assert.AreEqual(var2.GenericTypeVarArgs.Count, 1);
            Assert.AreEqual(var2.GenericTypeVarArgs[0].Name, "X");
            Assert.AreSame(var2.GenericTypeVarArgs[0].ReferredGenericTypeVar, vars[1]);
        }
Esempio n. 15
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="obj"></param>
 /// <returns></returns>
 protected ClassDescriptor GetClassDescriptor(Object obj)
 {
     return(ClassDescriptor.GetClassDescriptor(obj.GetType()));
 }
Esempio n. 16
0
 public CompositeType(Type theType) : base(theType.Name, theType, "java", "objc", "db")
 {
     this.Type           = ClassDescriptor.GetClassDescriptor(theType);
     this.cSharpTypeName = theType.Name;
 }
Esempio n. 17
0
        /// <summary>
        /// Recursively compares two objects to ensure that they are the same.
        /// Compares only values in the objects that will be simpl de/serialized
        /// </summary>
        /// <param name="originalObject">Original object</param>
        /// <param name="deserializedObject">Deserialized representation, the result of round-tripping</param>
        /// <param name="originalCompared">List of compared composite objects, prevents graph infinite loops</param>
        /// <param name="derserializedCompared">List of compared composite objects, prevents graph infinite loops</param>
        /// <param name="issues">List of issues found in the comparison</param>
        /// <returns>True if both are equal, false otherwise</returns>
        private static bool CompareObjectsRecursive(object originalObject, object deserializedObject, List <object> originalCompared, List <object> derserializedCompared, List <SimplIssue> issues)
        {
            if (originalObject == null && deserializedObject == null)
            {
                // both null is questionably acceptable. :|
                System.Diagnostics.Debug.WriteLine("Both null for deserialization... seems questionable.", category: "Comparison warning.");
                return(true);
            }
            else
            {
                // They are not equal here, obviously
                if (OneIsNullAndOtherIsNot(originalObject, deserializedObject))
                {
                    issues.Add(new SimplIssue("One object null, the other wasn't.", originalObject, deserializedObject));
                    return(false);
                }
            }

            // Add our objects to the compared object lists
            originalCompared.Add(originalObject);
            derserializedCompared.Add(deserializedObject);



            // Compare object types... Make sure they are the same.
            if (originalObject.GetType().Equals(deserializedObject.GetType()))
            {
                // Get a class descriptor for both.

                var classDescriptor = ClassDescriptor.GetClassDescriptor(originalObject.GetType());

                foreach (var fieldDescriptor in classDescriptor.AllFieldDescriptors)
                {
                    var originalDescribedObject     = fieldDescriptor.GetValue(originalObject);
                    var deserializedDescribedObject = fieldDescriptor.GetValue(deserializedObject);

                    if (originalCompared.Contains(originalDescribedObject) || derserializedCompared.Contains(deserializedDescribedObject))
                    {
                        // skip if we've already compared these.
                        continue;
                    }

                    if (fieldDescriptor.IsComposite)
                    {
                        // Catches a self-reference
                        if (Object.ReferenceEquals(originalDescribedObject, originalObject) || Object.ReferenceEquals(deserializedDescribedObject, deserializedObject))
                        {
                            // Circular refernces are fine, skip them / move on.
                            continue;
                        }

                        //Recurse and compare the inner objects
                        bool result = CompareObjectsRecursive(originalDescribedObject, deserializedDescribedObject, originalCompared, derserializedCompared, issues);
                        if (!result)
                        {
                            issues.Add(new SimplIssue("The composite objects are not equal.", originalDescribedObject, deserializedDescribedObject));
                            return(false);
                        }
                    }
                    else
                    {
                        if (fieldDescriptor.IsCollection)
                        {
                            // We have three options here; either the field is an IDictionary, in which case we need to sort and compare keys
                            // or we have an IList, in which case we should sort and compare values.
                            // or we have another collection that we don't support for some reason. Throw exception.

                            var collectionType = originalDescribedObject.GetType();

                            var comparator = new SimplObjectEqualityComparer();

                            var result = comparator.Equals(originalDescribedObject, deserializedDescribedObject);

                            if (!result)
                            {
                                issues.Add(new SimplIssue("Collections between two types differ in values", originalDescribedObject, deserializedDescribedObject));
                            }

                            return(result);
                        }
                        else
                        {
                            if (fieldDescriptor.IsScalar)
                            {
                                if (!fieldDescriptor.ContextSimplEquals(originalObject, deserializedObject))
                                {
                                    issues.Add(new SimplIssue("RHS and LHS scalars are different", originalDescribedObject.ToString(), deserializedDescribedObject.ToString()));
                                    return(false);
                                }
                            }
                            else
                            {
                                throw new ArgumentException("Given field descriptor cannot be compared in the test method yet. Type: {0}", fieldDescriptor.CSharpTypeName);
                            }
                        }
                    }
                }
            }
            else
            {
                issues.Add(new SimplIssue("Types of original object and deserialized object differ.", originalObject.GetType(), deserializedObject.GetType()));
                return(false);
            }

            //If we didn't return false by now, the types are equal.
            return(true);
        }
Esempio n. 18
0
        public static IEnumerable <T> LineToObject <T>(this IEnumerable <Line> lines)
            where T : class, new()
        {
            if (lines == null)
            {
                yield break;
            }

            var classDescriptor = ClassDescriptor.GetClassDescriptor(typeof(T));

            using (var e = lines.GetEnumerator())
            {
                Line             header         = null;
                string[]         allFields      = null;
                HashSet <string> allValidFields = null;
                if (e.MoveNext())
                {
                    header = e.Current;

                    allFields = header.Fields.Select(f => f.Trim()).ToArray();

                    var allMembers = classDescriptor
                                     .Members
                                     .Where(m => m.MemberInfo.GetCustomAttributes(typeof(IgnoreMemberAttribute), true).Length == 0)
                                     .ToArray()
                    ;

                    var allWriteableMembers = allMembers
                                              .Where(m => m.HasSetter)
                                              .Select(memberDefinition => memberDefinition.Name)
                                              .ToArray();
                    var allStringMembers = allMembers
                                           .Where(m => m.MemberType == typeof(string))
                                           .Select(memberDefinition => memberDefinition.Name)
                                           .ToArray();

                    var allNonWriteableMembers = allMembers
                                                 .Where(m => !m.HasSetter)
                                                 .Select(memberDefinition => memberDefinition.Name)
                                                 .ToArray();
                    var allNonStringMembers = allMembers
                                              .Where(m => m.MemberType != typeof(string))
                                              .Select(memberDefinition => memberDefinition.Name)
                                              .ToArray();

                    var emptyFieldCount = allFields.Count(s => s.IsNullOrWhiteSpace());
                    if (emptyFieldCount > 0)
                    {
                        ParserWarning("Empty field names in header line: {0}", emptyFieldCount);
                    }

                    var missingFields = allWriteableMembers.Except(allFields).ToArray();
                    if (missingFields.Length > 0)
                    {
                        ParserWarning("Missing field names in header line: {0}", missingFields.Concatenate());
                    }

                    var additionalFields = allFields.Except(allWriteableMembers).ToArray();
                    if (additionalFields.Length > 0)
                    {
                        ParserWarning("Additionals field names in header line (ignored): {0}", additionalFields.Concatenate());
                    }

                    var allNonWriteableFields = allFields.Intersect(allNonWriteableMembers).ToArray();
                    if (allNonWriteableFields.Length > 0)
                    {
                        ParserWarning("Non writeable fields referenced: {0}", allNonWriteableFields.Concatenate());
                    }

                    var allNonStringFields = allFields.Intersect(allNonStringMembers).ToArray();
                    if (allNonWriteableFields.Length > 0)
                    {
                        ParserWarning("Non string fields referenced: {0}", allNonStringFields.Concatenate());
                    }

                    allValidFields = new HashSet <string>(allFields
                                                          .Intersect(allWriteableMembers)
                                                          .Intersect(allStringMembers)
                                                          );
                }

                if (header == null)
                {
                    yield break;
                }

                while (e.MoveNext())
                {
                    var line = e.Current;
                    if (line.IsEmpty)
                    {
                        continue;
                    }

                    var lineFields = line.Fields;

                    if (allFields.Length < lineFields.Length)
                    {
                        ParserWarning(
                            "Line @{0} - {1} additinal fields detected",
                            line.LineNo,
                            lineFields.Length - allFields.Length
                            );
                    }

                    if (lineFields.Length < allFields.Length)
                    {
                        ParserWarning(
                            "Line @{0} - {1} missing fields detected",
                            line.LineNo,
                            allFields.Length - lineFields.Length
                            );
                    }

                    var instance   = new T();
                    var lineSource = instance as IOriginatedFromLine;
                    if (lineSource != null)
                    {
                        lineSource.SetLine(line);
                    }

                    var max = Math.Min(lineFields.Length, allFields.Length);

                    for (var iter = 0; iter < max; ++iter)
                    {
                        var fieldName  = allFields[iter];
                        var fieldValue = lineFields[iter] ?? "";
                        if (allValidFields.Contains(fieldName))
                        {
                            var memberDescriptor = classDescriptor.FindMember(fieldName);
                            if (memberDescriptor != null)
                            {
                                memberDescriptor.Setter(instance, fieldValue.Trim());
                            }
                            else
                            {
                                ParserWarning(
                                    "Line @{0} - Failed to set field {1}: {2}",
                                    line.LineNo,
                                    fieldName
                                    );
                            }
                        }
                    }

                    yield return(instance);
                }
            }
        }
Esempio n. 19
0
        /// <summary>
        /// resolving the graph based on the value of the graph switch
        /// </summary>
        /// <param name="obj"></param>
        public void ResolveGraph(object obj)
        {
            if (SimplTypesScope.graphSwitch == SimplTypesScope.GRAPH_SWITCH.ON)
            {
                _visitedElements.Add(obj.GetHashCode(), obj);

                List <FieldDescriptor> elementFieldDescriptors =
                    ClassDescriptor.GetClassDescriptor(obj).ElementFieldDescriptors;

                foreach (FieldDescriptor elementFieldDescriptor in elementFieldDescriptors)
                {
                    Object    thatReferenceObject = null;
                    FieldInfo childField          = elementFieldDescriptor.Field;
                    try
                    {
                        thatReferenceObject = childField.GetValue(obj);
                    }
                    catch (MemberAccessException e)
                    {
                        Debug.WriteLine("WARNING re-trying access! " + e.StackTrace);

                        try
                        {
                            thatReferenceObject = childField.GetValue(obj);
                        }
                        catch (MemberAccessException e1)
                        {
                            Debug.WriteLine("Can't access " + childField.Name);
                            Debug.WriteLine(e1.StackTrace);
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine("error" + e);
                    }

                    if (thatReferenceObject == null)
                    {
                        continue;
                    }

                    int childFdType = elementFieldDescriptor.FdType;

                    ICollection thatCollection;
                    switch (childFdType)
                    {
                    case FieldTypes.CollectionElement:
                    case FieldTypes.CollectionScalar:
                    case FieldTypes.MapElement:
                        thatCollection = XmlTools.GetCollection(thatReferenceObject);
                        break;

                    default:
                        thatCollection = null;
                        break;
                    }

                    if (thatCollection != null && (thatCollection.Count > 0))
                    {
                        foreach (Object next in thatCollection)
                        {
                            var compositeElement = next;
                            if (AlreadyVisited(compositeElement))
                            {
                                _needsAttributeHashCode.Add(compositeElement.GetHashCode(), compositeElement);
                            }
                            else
                            {
                                ResolveGraph(compositeElement);
                            }
                        }
                    }
                    else
                    {
                        var compositeElement = thatReferenceObject;
                        if (AlreadyVisited(compositeElement))
                        {
                            _needsAttributeHashCode.Add(compositeElement.GetHashCode(), compositeElement);
                        }
                        else
                        {
                            ResolveGraph(compositeElement);
                        }
                    }
                }
            }
        }