public override void because()
 {
     mappings = model.BuildMappings();
     target_mapping = mappings
         .SelectMany(x => x.Classes)
         .FirstOrDefault(x => x.Type == typeof(Target));
 }
Beispiel #2
0
        public Stream GetStream(ClassMapping clazz,string directory,out string fileName)
        {
            directoryForOutput = directory;
            if (!string.IsNullOrEmpty(directoryForOutput))
            {
                if (!Directory.Exists(directoryForOutput))
                    Directory.CreateDirectory(directoryForOutput);
            }

            try
            {
                fileName = GetFileName(clazz);
            }
            catch
            {
                fileName = clazz.GeneratedName + ".cs";
                log.Error("Error processing template for file name. " + fileName + " used.");
            }

            string toSave = Path.Combine(directoryForOutput, fileName);

            FileStream output = new FileStream(toSave, FileMode.Create, FileAccess.ReadWrite);
            log.Debug("Flushing output on file:" + output.Name);
            fileName = toSave;
            return output;
        }
 /// <summary>
 /// Returns true if you need to call "CreateStoreRoom" before storing any
 /// data.  This method is "Missing" not "Exists" because implementations that
 /// do not use a store room can return "false" from this method without
 /// breaking either a user's app or the spirit of the method.
 /// 
 /// Store room typically corresponds to "table".
 /// Firebird doesn't appear to support the SQL standard information_schema.
 /// </summary>
 /// <returns>Returns true if you need to call "CreateStoreRoom"
 ///          before storing any data.</returns>
 public override bool StoreRoomMissing(ClassMapping mapping)
 {
     int count = SqlConnectionUtilities.XSafeIntQuery(_connDesc,
         "select count(*) from rdb$relations where rdb$relation_name = '" +
         mapping.Table.ToUpper() + "'", null);
     return count == 0;
 }
        private ISubclassMapping CreateSubclass(ClassMapping mapping)
        {
            if (mapping.Discriminator == null)
                return new JoinedSubclassMapping();

            return new SubclassMapping();
        }
Beispiel #5
0
        public void TestCheckStoreRoomMissing()
        {
            OleDbOracleDaLayer ddl =
                new OleDbOracleDaLayer(
                    (OleDbDescriptor)
                    ConnectionDescriptor.LoadFromConfig(
                        new Config("..\\..\\Tests\\OracleDao.config", "OracleDaoConfig"), "DAO"));

            // Make sure the store room to test does not exist
            var colDef = new ClassMapColDefinition("Id", "Id", "INTEGER");
            var cm = new ClassMapping("test", "UNITTEST.StoreroomDoesNotExist", new List<ClassMapColDefinition>{colDef}, false);
            ddl.DeleteStoreRoom(cm);

            try
            {
                // Hasn't been added yet, should not exist
                Assert.IsTrue(
                    ddl.StoreRoomMissing(cm), "Oracle storeroom should not exist");

                ddl.CreateStoreRoom(cm);

                // Correct name, should exist
                Assert.IsFalse(
                    ddl.StoreRoomMissing(cm), "Oracle Storeroom should exist");
            }
            finally
            {
                // Delete the storeromm, no matter what
                ddl.DeleteStoreRoom(cm);
            }

            // Storeroom should be gone
            Assert.IsTrue(
                ddl.StoreRoomMissing(cm), "Oracle storeroom should not exist");
        }
        public ClassInspector(ClassMapping mapping)
        {
            this.mapping = mapping;

            propertyMappings.Map(x => x.LazyLoad, x => x.Lazy);
            propertyMappings.Map(x => x.ReadOnly, x => x.Mutable);
            propertyMappings.Map(x => x.EntityType, x => x.Type);
        }
        public void ShouldMapByteArrayAsTimestampSqlType()
        {
            var mapping = new ClassMapping { Type = typeof(Target) };

            mapper.Map(mapping, typeof(Target).GetProperty("Version"));

            mapping.Version.Columns.All(x => x.SqlType == "timestamp").ShouldBeTrue();
        }
        public void ShouldMapByteArrayAsBinaryBlob()
        {
            var mapping = new ClassMapping { Type = typeof(Target) };

            mapper.Map(mapping, typeof(Target).GetProperty("Version"));

            mapping.Version.Type.ShouldEqual(new TypeReference("BinaryBlob"));
        }
Beispiel #9
0
        /// <summary>
        /// Create the data reader.
        /// </summary>
        /// <param name="layer">Layer creating it.</param>
        /// <param name="mapping">Mapping for the class stored in the data store.</param>
        /// <param name="criteria">Criteria for which instances you want.</param>
        /// <param name="objects">Iterator over the list of objects.</param>
        public MemoryDataReader(UnqueryableDaLayer layer, ClassMapping mapping, DaoCriteria criteria,
            IEnumerator<MemoryObject> objects)
            : base(layer, mapping, criteria, GetConfig(mapping))
        {
            _objects = objects;

            PreProcessSorts();
        }
        public void ShouldMapByteArrayAsNotNull()
        {
            var mapping = new ClassMapping { Type = typeof(Target) };

            mapper.Map(mapping, typeof(Target).GetProperty("Version"));

            mapping.Version.Columns.All(x => x.NotNull == true).ShouldBeTrue();
        }
        public void ShouldSetContainingEntityType()
        {
            var mapping = new ClassMapping { Type = typeof(Target) };

            mapper.Map(mapping, typeof(Target).GetProperty("Version").ToMember());

            mapping.Version.ContainingEntityType.ShouldEqual(typeof(Target));
        }
        public void ShouldMapByteArrayWithUnsavedValueOfNull()
        {
            var mapping = new ClassMapping { Type = typeof(Target) };

            mapper.Map(mapping, typeof(Target).GetProperty("Version"));

            mapping.Version.UnsavedValue.ShouldEqual(null);
        }
        public void ShouldMapInheritedByteArray()
        {
            var mapping = new ClassMapping { Type = typeof(SubTarget) };

            mapper.Map(mapping, typeof(SubTarget).GetProperty("Version"));

            Assert.That(mapping.Version, Is.Not.Null);
        }
        public void ShouldMapByteArrayAsNotNull()
        {
            var mapping = new ClassMapping { Type = typeof(Target) };

            mapper.Map(mapping, typeof(Target).GetProperty("Version").ToMember());

            SpecificationExtensions.ShouldBeTrue(mapping.Version.Columns.All(x => x.NotNull == true));
        }
        public void ShouldMapByteArrayAsBinaryBlob()
        {
            var mapping = new ClassMapping();
            mapping.Set(x => x.Type, Layer.Defaults, typeof(Target));

            mapper.Map(mapping, typeof(Target).GetProperty("Version").ToMember());

            mapping.Version.Type.ShouldEqual(new TypeReference("BinaryBlob"));
        }
        public void ShouldMapByteArrayAsNotNull()
        {
            var mapping = new ClassMapping();
            mapping.Set(x => x.Type, Layer.Defaults, typeof(Target));

            mapper.Map(mapping, typeof(Target).GetProperty("Version").ToMember());

            mapping.Version.Columns.All(x => x.NotNull).ShouldBeTrue();
        }
        public void ShouldMapByteArrayWithUnsavedValueOfNull()
        {
            var mapping = new ClassMapping();
            mapping.Set(x => x.Type, Layer.Defaults, typeof(Target));

            mapper.Map(mapping, typeof(Target).GetProperty("Version").ToMember());

            mapping.Version.UnsavedValue.ShouldEqual(null);
        }
        public void ShouldMapInheritedByteArray()
        {
            var mapping = new ClassMapping();
            mapping.Set(x => x.Type, Layer.Defaults, typeof(SubTarget));

            mapper.Map(mapping, typeof(SubTarget).GetProperty("Version").ToMember());

            Assert.That(mapping.Version, Is.Not.Null);
        }
        public override void ProcessClass(ClassMapping mapping)
        {
            var subclasses = FindClosestSubclasses(mapping.Type);

            foreach (var provider in subclasses)
                mapping.AddSubclass(provider.GetSubclassMapping(CreateSubclass(mapping)));

            base.ProcessClass(mapping);
        }
        public void ShouldWriteAny()
        {
            var mapping = new ClassMapping();

            mapping.AddAny(new AnyMapping());

            writer.VerifyXml(mapping)
                .Element("any").Exists();
        }
        public void ShouldWriteBag()
        {
            var mapping = new ClassMapping();

            mapping.AddCollection(new BagMapping());

            writer.VerifyXml(mapping)
                .Element("bag").Exists();
        }
        public void ShouldWriteCache()
        {
            var mapping = new ClassMapping();

            mapping.Cache = new CacheMapping();

            writer.VerifyXml(mapping)
                .Element("cache").Exists();
        }
        public void ShouldSetContainingEntityType()
        {
            var mapping = new ClassMapping();
            mapping.Set(x => x.Type, Layer.Defaults, typeof(Target));

            mapper.Map(mapping, typeof(Target).GetProperty("Version").ToMember());

            mapping.Version.ContainingEntityType.ShouldEqual(typeof(Target));
        }
        public void ShouldWriteSqlUpdate()
        {
            var mapping = new ClassMapping();

            mapping.AddStoredProcedure(new StoredProcedureMapping("sql-update", "update ABC"));

            writer.VerifyXml(mapping)
                .Element("sql-update").Exists();
        }
        public DiscriminatorMapping(ClassMapping parentClass)
        {
            ParentClass = parentClass;

            attributes = new AttributeStore<DiscriminatorMapping>();
            attributes.SetDefault(x => x.NotNull, true);
            attributes.SetDefault(x => x.Insert, true);
            attributes.SetDefault(x => x.Type, typeof(string));
        }
        public void ShouldMapHashSetAsSet()
        {
            var classMapping = new ClassMapping();
            classMapping.Set(x => x.Type, Layer.Defaults, typeof(PropertyTarget));

            mapper.Map(classMapping, typeof(PropertyTarget).GetProperty("HashSet").ToMember());

            classMapping.Collections
                .First().Collection.ShouldEqual(Collection.Set);
        }
        public ClassMapping Map(Type classType, List<AutoMapType> types)
        {
            var classMap = new ClassMapping { Type = classType };

            classMap.SetDefaultValue(x => x.Name, classType.AssemblyQualifiedName);
            classMap.SetDefaultValue(x => x.TableName, GetDefaultTableName(classType));

            mappingTypes = types;
            return (ClassMapping)MergeMap(classType, classMap, new List<string>());
        }
        public override void ProcessClass(ClassMapping mapping)
        {
            var subclasses = subclassProviders
                .Select(x => x.GetSubclassMapping(CreateSubclass(mapping)))
                .Where(x => x.Type.BaseType == mapping.Type);

            foreach (var subclass in subclasses)
                mapping.AddSubclass(subclass);

            base.ProcessClass(mapping);
        }
Beispiel #29
0
        public ClassMapping Map(Type classType, List<AutoMapType> types)
        {
            var classMap = new ClassMapping();

            classMap.Set(x => x.Type, Layer.Defaults, classType);
            classMap.Set(x => x.Name, Layer.Defaults, classType.AssemblyQualifiedName);
            classMap.Set(x => x.TableName, Layer.Defaults, GetDefaultTableName(classType));

            mappingTypes = types;
            return (ClassMapping)MergeMap(classType, classMap, new List<Member>());
        }
        public void CanAddClassMappings()
        {
            var hibMap = new HibernateMapping();
            var classMap1 = new ClassMapping();
            var classMap2 = new ClassMapping();

            hibMap.AddClass(classMap1);
            hibMap.AddClass(classMap2);

            hibMap.Classes.ShouldContain(classMap1);
            hibMap.Classes.ShouldContain(classMap2);
        }
 public FhirbaseJsonWriter(StringWriter sw, Type t) : base(sw)
 {
     m_mapping = s_modelInspector.FindClassMappingByType(t);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ClassMappingBuilder{TEntity}"/> class.
 /// </summary>
 /// <param name="classMapping">The class mapping.</param>
 public ClassMappingBuilder(ClassMapping classMapping)
 {
     ClassMapping = classMapping;
 }
Beispiel #33
0
        //this should be refactored into read(ITypedElement parent, Base existing)

        private void read(ClassMapping mapping, IEnumerable <ITypedElement> members, Base existing)
        {
            foreach (var memberData in members)
            {
                var memberName = memberData.Name;  // tuple: first is name of member

                // Find a property on the instance that matches the element found in the data
                // NB: This function knows how to handle suffixed names (e.g. xxxxBoolean) (for choice types).
                var mappedProperty = mapping.FindMappedElementByName(memberName);

                if (mappedProperty != null)
                {
                    //   Message.Info("Handling member {0}.{1}", mapping.Name, memberName);

                    object value = null;

                    // For primitive members we can save time by not calling the getter
                    if (!mappedProperty.IsPrimitive)
                    {
                        value = mappedProperty.GetValue(existing);

                        if (value != null && !mappedProperty.IsCollection)
                        {
                            RaiseFormatError($"Element '{mappedProperty.Name}' must not repeat", memberData.Location);
                        }
                    }

                    var reader = new DispatchingReader(memberData, Settings, arrayMode: false);

                    // Since we're still using both ClassMappings and the newer IElementDefinitionSummary provider at the same time,
                    // the member might be known in the one (POCO), but unknown in the provider. This is only in theory, since the
                    // provider should provide exactly the same information as the mappings. But better to get a clear exception
                    // when this happens.
                    value = reader.Deserialize(mappedProperty, memberName, value);

                    if (mappedProperty.RepresentsValueElement && mappedProperty.ElementType.IsEnum() && value is String)
                    {
                        if (!Settings.AllowUnrecognizedEnums)
                        {
                            if (EnumUtility.ParseLiteral((string)value, mappedProperty.ElementType) == null)
                            {
                                RaiseFormatError($"Literal '{value}' is not a valid value for enumeration '{mappedProperty.ElementType.Name}'", _current.Location);
                            }
                        }

                        ((Primitive)existing).ObjectValue = value;
                        //var prop = ReflectionHelper.FindPublicProperty(mapping.NativeType, "RawValue");
                        //prop.SetValue(existing, value, null);
                        //mappedProperty.SetValue(existing, null);
                    }
                    else
                    {
                        mappedProperty.SetValue(existing, value);
                    }
                }
                else
                {
                    if (Settings.AcceptUnknownMembers == false)
                    {
                        RaiseFormatError($"Encountered unknown member '{memberName}' while de-serializing", memberData.Location);
                    }
                    else
                    {
                        Message.Info("Skipping unknown member " + memberName);
                    }
                }
            }
        }
Beispiel #34
0
        ClassMapping IMappingProvider.GetClassMapping()
        {
            var mapping = new ClassMapping(attributes.CloneInner());

            mapping.Type = typeof(T);
            mapping.Name = typeof(T).AssemblyQualifiedName;

            foreach (var property in properties)
            {
                mapping.AddProperty(property.GetPropertyMapping());
            }

            foreach (var component in components)
            {
                mapping.AddComponent(component.GetComponentMapping());
            }

            if (version != null)
            {
                mapping.Version = version.GetVersionMapping();
            }

            foreach (var oneToOne in oneToOnes)
            {
                mapping.AddOneToOne(oneToOne.GetOneToOneMapping());
            }

            foreach (var collection in collections)
            {
                mapping.AddCollection(collection.GetCollectionMapping());
            }

            foreach (var reference in references)
            {
                mapping.AddReference(reference.GetManyToOneMapping());
            }

            foreach (var any in anys)
            {
                mapping.AddAny(any.GetAnyMapping());
            }

            foreach (var subclass in subclasses.Values)
            {
                mapping.AddSubclass(subclass.GetSubclassMapping());
            }

            foreach (var join in joins)
            {
                mapping.AddJoin(join);
            }

            if (discriminator != null)
            {
                mapping.Discriminator = ((IDiscriminatorMappingProvider)discriminator).GetDiscriminatorMapping();
            }

            if (cache != null)
            {
                mapping.Cache = cache;
            }

            if (id != null)
            {
                mapping.Id = id.GetIdentityMapping();
            }

            if (compositeId != null)
            {
                mapping.Id = compositeId.GetCompositeIdMapping();
            }

            if (naturalId != null)
            {
                mapping.NaturalId = naturalId.GetNaturalIdMapping();
            }

            if (!mapping.IsSpecified("TableName"))
            {
                mapping.SetDefaultValue(x => x.TableName, GetDefaultTableName());
            }

            foreach (var filter in filters)
            {
                mapping.AddFilter(filter.GetFilterMapping());
            }

            foreach (var storedProcedure in storedProcedures)
            {
                mapping.AddStoredProcedure(storedProcedure.GetStoredProcedureMapping());
            }

            mapping.Tuplizer = tuplizerMapping;

            return(mapping);
        }
Beispiel #35
0
 public virtual bool HasExtends(ClassMapping cmap)
 {
     return(GetExtends(cmap).Length != 0);
 }
Beispiel #36
0
 public virtual bool HasImplements(ClassMapping cmap)
 {
     return(GetImplements(cmap).Length != 0);
 }
Beispiel #37
0
        public virtual string FieldsAsArguments(SupportClass.ListCollectionSupport fieldslist, ClassMapping classMapping,
                                                IDictionary class2classmap)
        {
            StringBuilder buf   = new StringBuilder();
            bool          first = true;

            for (IEnumerator fields = fieldslist.GetEnumerator(); fields.MoveNext();)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    buf.Append(", ");
                }

                FieldProperty field = (FieldProperty)fields.Current;
                buf.Append(field.fieldcase);
            }
            return(buf.ToString());
        }
Beispiel #38
0
 public virtual void DoImports(ClassMapping classMapping, StreamWriter writer)
 {
     writer.WriteLine(languageTool.GenerateImports(classMapping));
     writer.WriteLine();
 }
Beispiel #39
0
        private int DoFields(ClassMapping classMapping, IDictionary class2classmap, StringWriter writer, string vetoSupport,
                             string changeSupport, int fieldTypes, SupportClass.ListCollectionSupport fieldz)
        {
            // field accessors
            for (IEnumerator fields = fieldz.GetEnumerator(); fields.MoveNext();)
            {
                FieldProperty field = (FieldProperty)fields.Current;
                if (field.GeneratedAsProperty)
                {
                    // getter
                    string getAccessScope = GetFieldScope(field, "scope-get", "public");


                    if (field.GetMeta("field-description") != null)
                    {
                        //writer.WriteLine("    /** \n" + languageTool.toJavaDoc(field.getMetaAsString("field-description"), 4) + "     */");
                        writer.WriteLine("    /// <summary>\n" + languageTool.ToJavaDoc(field.GetMetaAsString("field-description"), 4) +
                                         "\n    /// </summary>");
                    }
                    writer.Write("    " + getAccessScope + " virtual " + field.FullyQualifiedTypeName + " " + field.Propcase);
                    if (classMapping.Interface)
                    {
                        writer.WriteLine(";");
                    }
                    else
                    {
                        writer.WriteLine();
                        writer.WriteLine("    {");
                        writer.WriteLine("        get { return this." + field.fieldcase + "; }");
                        //writer.WriteLine("        {");
                        //writer.WriteLine("            return this." + field.FieldName + ";");
                        //writer.WriteLine("        }");
                    }

                    // setter
                    int fieldType = 0;
                    if (field.GetMeta("beans-property-type") != null)
                    {
                        string beansPropertyType = field.GetMetaAsString("beans-property-type").Trim().ToLower();
                        if (beansPropertyType.Equals("constraint"))
                        {
                            fieldTypes = (fieldTypes | CONSTRAINT);
                            fieldType  = CONSTRAINT;
                        }
                        else if (beansPropertyType.Equals("bound"))
                        {
                            fieldTypes = (fieldTypes | BOUND);
                            fieldType  = BOUND;
                        }
                    }
                    string setAccessScope = GetFieldScope(field, "scope-set", "public");
                    writer.Write("        set");
                    writer.Write((fieldType & CONSTRAINT) == CONSTRAINT ? " throws PropertyVetoException " : "");
                    if (classMapping.Interface)
                    {
                        writer.WriteLine(";");
                    }
                    else
                    {
                        writer.WriteLine();
                        writer.WriteLine("        {");
                        if ((fieldType & CONSTRAINT) == CONSTRAINT || (fieldType & BOUND) == BOUND)
                        {
                            writer.WriteLine("            object oldValue = " + GetFieldAsObject(true, field) + ";");
                        }
                        if ((fieldType & CONSTRAINT) == CONSTRAINT)
                        {
                            writer.WriteLine("            " + vetoSupport + ".fireVetoableChange(\"" + field.fieldcase + "\",");
                            writer.WriteLine("                    oldValue,");
                            writer.WriteLine("                    " + GetFieldAsObject(false, field) + ");");
                        }

                        writer.WriteLine("            this." + field.fieldcase + " = value;");
                        if ((fieldType & BOUND) == BOUND)
                        {
                            writer.WriteLine("            " + changeSupport + ".firePropertyChange(\"" + field.fieldcase + "\",");
                            writer.WriteLine("                    oldValue,");
                            writer.WriteLine("                    " + GetFieldAsObject(false, field) + ");");
                        }
                        writer.WriteLine("        }");
                    }
                    writer.WriteLine("    }");
                    writer.WriteLine();

                    // add/remove'rs (commented out for now)

                    /*
                     * if(field.getForeignClass()!=null) {
                     * ClassName foreignClass = field.getForeignClass();
                     *
                     * string trueforeign = getTrueTypeName(foreignClass, class2classmap);
                     * classMapping.addImport(trueforeign);
                     *
                     * // Try to identify the matching set method on the child.
                     * ClassMapping forignMap = (ClassMapping) class2classmap.get(foreignClass.getFullyQualifiedName());
                     *
                     * if(forignMap!=null) {
                     * Iterator foreignFields = forignMap.getFields().iterator();
                     * while (foreignFields.hasNext()) {
                     * Field ffield = (Field) foreignFields.next();
                     * if(ffield.isIdentifier()) {
                     * log.Debug("Trying to match " + ffield.getName() + " with " + field.getForeignKeys());
                     * }
                     * }
                     *
                     * } else {
                     * log.Error("Could not find foreign class's mapping - cannot provide bidirectional setters!");
                     * }
                     *
                     * string addAccessScope = getFieldScope(field, "scope", "scope-add");
                     * writer.println("    " + setAccessScope + " void add" + field.getAsSuffix() + StringHelper.OPEN + shortenType(trueforeign, classMapping.getImports()) + " a" + field.getName() + ") {");
                     * writer.println("        this." + getterType + field.getAsSuffix() + "().add(a" + field.getName() + ");");
                     * writer.println("        a" + field.getName() + ".setXXX(this);");
                     * writer.println("    }");
                     * writer.println();
                     *
                     *
                     * }
                     */
                }
            }
            return(fieldTypes);
        }
Beispiel #40
0
        public override void Render(string savedToPackage, string savedToClass, ClassMapping classMapping,
                                    IDictionary class2classmap, StreamWriter mainwriter)
        {
            mainwriter.WriteLine("using System;");
            mainwriter.WriteLine(
                @"//------------------------------------------------------------------------------
// <autogenerated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if 
//     the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
");
            GeneratePackageDelaration(savedToPackage, classMapping, mainwriter);
            mainwriter.WriteLine("{");

            // switch to another writer to be able to insert the actually
            // used imports when whole class has been rendered.
            StringWriter writer = new StringWriter();


            // class declaration
            if (classMapping.GetMeta("class-description") == null)
            {
                writer.WriteLine(
                    @" /// <summary>
 /// POJO for {0}
 /// </summary>
 /// <remark>
 /// This class is autogenerated
 /// </remark>
",
                    classMapping.ClassName);
            }
            else
            {
                writer.WriteLine("/// <summary>\n" + languageTool.ToJavaDoc(classMapping.GetMetaAsString("class-description"), 0) +
                                 "\n/// </summary>");
            }

            string classScope      = classMapping.Scope;
            string declarationType = classMapping.DeclarationType;


            //classMapping.addImport(typeof(System.Runtime.Serialization.ISerializable));
            //string modifiers = classMapping.getModifiers();
            if (classMapping.ShouldBeAbstract() && (classScope.IndexOf("abstract") == -1))
            {
                writer.Write("abstract " + classScope + " " + declarationType + " " + savedToClass);
            }
            else
            {
                writer.Write(classScope + " " + declarationType + " " + savedToClass);
            }
            if (languageTool.HasExtends(classMapping) || languageTool.HasImplements(classMapping))
            {
                writer.Write(" : ");
            }

            if (languageTool.HasExtends(classMapping))
            {
                writer.Write(languageTool.GetExtends(classMapping));
            }

            if (languageTool.HasExtends(classMapping) && languageTool.HasImplements(classMapping))
            {
                writer.Write(", ");
            }

            if (languageTool.HasImplements(classMapping))
            {
                writer.Write(languageTool.GetImplements(classMapping));
            }

            writer.WriteLine(" {");
            writer.WriteLine();

            // switch to another writer to be able to insert the
            // veto- and changeSupport fields
            StringWriter propWriter = new StringWriter();

            if (!classMapping.Interface)
            {
                DoFields(classMapping, class2classmap, propWriter);
                DoConstructors(savedToClass, classMapping, class2classmap, propWriter);
            }

            string vetoSupport   = MakeSupportField("vetos", classMapping.AllFields);
            string changeSupport = MakeSupportField("changes", classMapping.AllFields);
            int    fieldTypes    = DoFieldAccessors(classMapping, class2classmap, propWriter, vetoSupport, changeSupport);

            if (!classMapping.Interface)
            {
                DoSupportMethods(fieldTypes, vetoSupport, changeSupport, propWriter);

                DoToString(classMapping, propWriter);

                DoEqualsAndHashCode(savedToClass, classMapping, propWriter);
            }
            if (classMapping.GetMeta("class-code") != null)
            {
                propWriter.WriteLine("// The following is extra code specified in the hbm.xml files");
                SupportClass.ListCollectionSupport extras = classMapping.GetMeta("class-code");
                IEnumerator iter = extras.GetEnumerator();
                while (iter.MoveNext())
                {
                    string code = iter.Current.ToString();
                    propWriter.WriteLine(code);
                }

                propWriter.WriteLine("// end of extra code specified in the hbm.xml files");
            }

            propWriter.WriteLine("}");

            //insert change and VetoSupport
            if (!classMapping.Interface)
            {
                DoSupports(fieldTypes, classMapping, vetoSupport, changeSupport, writer);
            }

            writer.Write(propWriter.ToString());

            // finally write the imports
            DoImports(classMapping, mainwriter);
            mainwriter.Write(writer.ToString());
            mainwriter.WriteLine("\n}");
        }
Beispiel #41
0
        public virtual void DoEqualsAndHashCode(string savedToClass, ClassMapping classMapping, StringWriter writer)
        {
            if (classMapping.MustImplementEquals())
            {
                writer.WriteLine("    public override bool Equals(object obj) {");
                writer.WriteLine("        if(this == obj) return true;");
                writer.WriteLine("        if((obj == null) || (obj.GetType() != this.GetType())) return false;");
                writer.WriteLine("        " + savedToClass + " castObj = (" + savedToClass + ") obj;");
                writer.Write("        return (castObj != null) ");
                int usedFields = 0;
                SupportClass.ListCollectionSupport idFields = new SupportClass.ListCollectionSupport();
                for (IEnumerator fields = classMapping.Fields.GetEnumerator(); fields.MoveNext();)
                {
                    FieldProperty field = (FieldProperty)fields.Current;
                    if (field.GetMetaAsBool("use-in-equals"))
                    {
                        writer.Write(" && (this." + field.fieldcase + " == castObj." + field.fieldcase + ")");
                        usedFields++;
                    }
                    if (field.Identifier)
                    {
                        idFields.Add(field);
                    }
                }
                if (usedFields == 0)
                {
                    log.Warn("No properties has been marked as being used in equals/hashcode for " + classMapping.Name +
                             ". Using object identifier which is RARELY safe to use! See http://hibernate.org/109.html");
                    for (IEnumerator fields = idFields.GetEnumerator(); fields.MoveNext();)
                    {
                        FieldProperty field = (FieldProperty)fields.Current;
                        writer.Write(" && (this." + field.fieldcase + " == castObj." + field.fieldcase + ")");
                    }
                }
                writer.WriteLine(";");
                writer.WriteLine("    }");
                writer.WriteLine();

                writer.WriteLine("    public override int GetHashCode() {");
                writer.WriteLine("        int hash = 69;");
                //writer.Write("        return");

                for (IEnumerator fields = classMapping.Fields.GetEnumerator(); fields.MoveNext();)
                {
                    FieldProperty field = (FieldProperty)fields.Current;
                    if (field.GetMetaAsBool("use-in-equals"))
                    {
                        //writer.Write("\n            " + field.FieldName + ".GetHashCode() ^");
                        writer.WriteLine("        hash = 31 * hash + " + field.fieldcase + ".GetHashCode();");
                    }
                }
                if (usedFields == 0)
                {
                    for (IEnumerator fields = idFields.GetEnumerator(); fields.MoveNext();)
                    {
                        FieldProperty field = (FieldProperty)fields.Current;
                        //writer.Write("\n            " + field.FieldName + ".GetHashCode() ^");
                        writer.WriteLine("        hash = 31 * hash + " + field.fieldcase + ".GetHashCode();");
                    }
                }

                //writer.WriteLine(" 0;");
                writer.WriteLine("        return hash;");
                writer.WriteLine("    }");
                writer.WriteLine();
            }
        }
Beispiel #42
0
        public virtual void DoConstructors(string savedToClass, ClassMapping classMapping, IDictionary class2classmap,
                                           StringWriter writer)
        {
            // full constructor
            SupportClass.ListCollectionSupport allFieldsForFullConstructor = classMapping.AllFieldsForFullConstructor;

            writer.WriteLine("    /// <summary>\n    /// full constructor\n    /// </summary>");
            string fullCons = "    public " + savedToClass + StringHelper.OpenParen;

            fullCons += languageTool.FieldsAsParameters(allFieldsForFullConstructor, classMapping, class2classmap);

            writer.Write(fullCons + ")");
            //invoke super to initialize superclass...
            SupportClass.ListCollectionSupport supersConstructorFields = classMapping.FieldsForSupersFullConstructor;
            if (!(supersConstructorFields.Count == 0))
            {
                writer.Write(" : base(");
                bool first = true;
                for (IEnumerator fields = supersConstructorFields.GetEnumerator(); fields.MoveNext();)
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        writer.Write(", ");
                    }

                    FieldProperty field = (FieldProperty)fields.Current;
                    writer.Write(field.FieldName);
                }
                writer.Write(")");
            }
            writer.WriteLine();
            writer.WriteLine("    {");

            // initialisation of localfields
            for (IEnumerator fields = classMapping.LocalFieldsForFullConstructor.GetEnumerator(); fields.MoveNext();)
            {
                FieldProperty field = (FieldProperty)fields.Current;
                if (field.GeneratedAsProperty)
                {
                    writer.WriteLine("        this." + field.FieldName + " = " + field.FieldName + ";");
                }
            }
            writer.WriteLine("    }");
            writer.WriteLine();

            // no args constructor (if fullconstructor had any arguments!)
            if (allFieldsForFullConstructor.Count > 0)
            {
                writer.WriteLine("    /// <summary>\n    /// default constructor\n    /// </summary>");
                writer.WriteLine("    public " + savedToClass + "() {");
                writer.WriteLine("    }");
                writer.WriteLine();
            }

            // minimal constructor (only if the fullconstructor had any arguments)
            if ((allFieldsForFullConstructor.Count > 0) && classMapping.NeedsMinimalConstructor())
            {
                SupportClass.ListCollectionSupport allFieldsForMinimalConstructor = classMapping.AllFieldsForMinimalConstructor;
                writer.WriteLine("    /// <summary>\n    /// minimal constructor\n    /// </summary>");

                string minCons = "    public " + savedToClass + "(";
                bool   first   = true;
                for (IEnumerator fields = allFieldsForMinimalConstructor.GetEnumerator(); fields.MoveNext();)
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        minCons = minCons + ", ";
                    }

                    FieldProperty field = (FieldProperty)fields.Current;
                    minCons = minCons +
                              LanguageTool.ShortenType(LanguageTool.GetTrueTypeName(field, class2classmap), classMapping.Imports) + " " +
                              field.FieldName;
                }

                writer.Write(minCons + ")");
                // invoke super to initialize superclass...
                SupportClass.ListCollectionSupport supersMinConstructorFields = classMapping.FieldsForSupersMinimalConstructor;
                if (!(supersMinConstructorFields.Count == 0))
                {
                    writer.Write(" : base(");
                    bool first2 = true;
                    for (IEnumerator fields = supersMinConstructorFields.GetEnumerator(); fields.MoveNext();)
                    {
                        if (first2)
                        {
                            first2 = false;
                        }
                        else
                        {
                            writer.Write(StringHelper.CommaSpace);
                        }

                        FieldProperty field = (FieldProperty)fields.Current;
                        writer.Write(field.FieldName);
                    }
                    writer.Write(")");
                }
                writer.WriteLine();
                writer.WriteLine("    {");

                // initialisation of localfields
                for (IEnumerator fields = classMapping.LocalFieldsForMinimalConstructor.GetEnumerator(); fields.MoveNext();)
                {
                    FieldProperty field = (FieldProperty)fields.Current;
                    if (field.GeneratedAsProperty)
                    {
                        writer.WriteLine("        this." + field.FieldName + " = " + field.FieldName + ";");
                    }
                }
                writer.WriteLine("    }");
                writer.WriteLine();
            }
        }
 public override void because()
 {
     mappings      = model.BuildMappings().ToList();
     targetMapping = mappings.SelectMany(x => x.Classes).FirstOrDefault(x => x.Type == typeof(Root));
 }
Beispiel #44
0
 public virtual string GetSaveToPackage(ClassMapping classMapping)
 {
     return(classMapping.GeneratedPackageName);
 }
 public void AddClass(ClassMapping classMapping)
 {
     classes.Add(classMapping);
 }
Beispiel #46
0
 public virtual string GetSaveToClassName(ClassMapping classMapping)
 {
     return(classMapping.GeneratedName);
 }
Beispiel #47
0
        public virtual string FieldsAsParameters(SupportClass.ListCollectionSupport fieldslist, ClassMapping classMapping,
                                                 IDictionary class2classmap)
        {
            StringBuilder buf   = new StringBuilder();
            bool          first = true;

            for (IEnumerator fields = fieldslist.GetEnumerator(); fields.MoveNext();)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    buf.Append(", ");
                }
                FieldProperty field = (FieldProperty)fields.Current;
                buf.Append(ShortenType(field.FullyQualifiedTypeName, classMapping.Imports) + " " + field.fieldcase);
            }
            return(buf.ToString());
        }
Beispiel #48
0
        protected internal virtual void GeneratePackageDelaration(string savedToPackage, ClassMapping classMapping, StreamWriter w)
        {
            string string_Renamed = GetPackageDeclaration(savedToPackage, classMapping);

            if (string_Renamed.Length > 0)
            {
                w.WriteLine(string_Renamed);
            }
            else
            {
                w.WriteLine("// default package");
            }
        }
Beispiel #49
0
 public virtual void Render(string savedToPackage, string savedToClass, ClassMapping classMapping,
                            IDictionary class2classmap, StreamWriter writer)
 {
 }
Beispiel #50
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ListGeneratorBuilder{TEntity}"/> class.
 /// </summary>
 /// <param name="classMapping">The class mapping.</param>
 public ListGeneratorBuilder(ClassMapping classMapping) : base(classMapping)
 {
     Random(2, 10);
 }
        public void TestMixedDataTypeDetection()
        {
            var mapping = ClassMapping.Create(typeof(ComplexNumber));

            // cannot have a datatype with a profile....
        }
Beispiel #52
0
        private void read(ClassMapping mapping, IEnumerable <Tuple <string, IFhirReader> > members, Base existing)
        {
            //bool hasMember;

            foreach (var memberData in members)
            {
                //hasMember = true;
                var memberName = memberData.Item1;  // tuple: first is name of member

                // Find a property on the instance that matches the element found in the data
                // NB: This function knows how to handle suffixed names (e.g. xxxxBoolean) (for choice types).
                var mappedProperty = mapping.FindMappedElementByName(memberName);

                if (mappedProperty != null)
                {
                    //   Message.Info("Handling member {0}.{1}", mapping.Name, memberName);

                    object value = null;

                    // For primitive members we can save time by not calling the getter
                    if (!mappedProperty.IsPrimitive)
                    {
                        value = mappedProperty.GetValue(existing);

                        if (value != null && !mappedProperty.IsCollection)
                        {
                            throw Error.Format($"Element '{mappedProperty.Name}' must not repeat", _current);
                        }
                    }

                    var reader = new DispatchingReader(memberData.Item2, Settings, arrayMode: false);
                    value = reader.Deserialize(mappedProperty, memberName, value);

                    if (mappedProperty.RepresentsValueElement && mappedProperty.ElementType.IsEnum() && value is String)
                    {
                        if (!Settings.AllowUnrecognizedEnums)
                        {
                            if (EnumUtility.ParseLiteral((string)value, mappedProperty.ElementType) == null)
                            {
                                throw Error.Format("Literal '{0}' is not a valid value for enumeration '{1}'".FormatWith(value, mappedProperty.ElementType.Name), _current);
                            }
                        }

                        ((Primitive)existing).ObjectValue = value;
                        //var prop = ReflectionHelper.FindPublicProperty(mapping.NativeType, "RawValue");
                        //prop.SetValue(existing, value, null);
                        //mappedProperty.SetValue(existing, null);
                    }
                    else
                    {
                        mappedProperty.SetValue(existing, value);
                    }
                }
                else
                {
                    if (Settings.AcceptUnknownMembers == false)
                    {
                        throw Error.Format("Encountered unknown member '{0}' while de-serializing".FormatWith(memberName), _current);
                    }
                    else
                    {
                        Message.Info("Skipping unknown member " + memberName);
                    }
                }
            }
        }
Beispiel #53
0
 public void TestMixedDataTypeDetection()
 {
     Assert.ThrowsException <ArgumentException>(() => ClassMapping.Create(typeof(ComplexNumber)));
     // cannot have a datatype with a profile....
 }
 public FhirbaseJsonReader(object json, Type t)
 {
     m_reader  = new JsonTextReader(new StringReader(json as string));
     m_mapping = s_modelInspector.FindClassMappingByType(t);
 }
Beispiel #55
0
        public override IDesignModel GenerateDesignModel(IXmlElement xmlElement, DesignModelParseContext context)
        {
            var sourceDesignModelName         = xmlElement.GetStringAttributeValue("src");
            var sourceDesignModelNameSet      = !string.IsNullOrWhiteSpace(sourceDesignModelName);
            var destinationDesignModelName    = xmlElement.GetStringAttributeValue("dest");
            var destinationDesignModelNameSet = !string.IsNullOrWhiteSpace(destinationDesignModelName);

            if (sourceDesignModelNameSet && destinationDesignModelNameSet)
            {
                throw new ParseException(xmlElement.ParseLocation, $"Both 'src' and 'dest' attributes cannot be set.");
            }

            if (!sourceDesignModelNameSet && !destinationDesignModelNameSet)
            {
                throw new ParseException(xmlElement.ParseLocation, $"Either 'src' or 'dest' attribute must be set.");
            }

            var currentDesignModel = context.DesignModel;

            if (!(currentDesignModel is IClassModel currentClassModel))
            {
                throw new ParseException(xmlElement.ParseLocation, $"Mapping model '{currentDesignModel.FullyQualifiedName}' must be a class-like design model.");
            }

            var ns = currentDesignModel.Namespace;
            var sourceReference = sourceDesignModelNameSet
                ? _designModelCollection.CreateClassModelReference(ns, xmlElement.ParseLocation, sourceDesignModelName)
                : currentClassModel.CreateClassModelReference(xmlElement.ParseLocation);
            var destinationReference = destinationDesignModelNameSet
                ? _designModelCollection.CreateClassModelReference(ns, xmlElement.ParseLocation, destinationDesignModelName)
                : currentClassModel.CreateClassModelReference(xmlElement.ParseLocation);

            var classMapping = new ClassMapping
            {
                Name          = xmlElement.GetStringAttributeValue("name", null),
                Source        = sourceReference,
                Destination   = destinationReference,
                MapAttributes = xmlElement.GetBoolAttributeValue("attributes", true),
                MapRelations  = xmlElement.GetBoolAttributeValue("relations", true),
                AddMissing    = xmlElement.GetBoolAttributeValue("add-missing", true),
                TwoWay        = xmlElement.GetBoolAttributeValue("two-way", true),
                ParseLocation = xmlElement.ParseLocation
            };

            foreach (var attributeElement in xmlElement.GetChildElments("Attribute"))
            {
                var mapping = new AttributeMapping
                {
                    Source        = new ClassAttributeReference(attributeElement.GetStringAttributeValue("src"), attributeElement.ParseLocation),
                    Destination   = new ClassAttributeReference(attributeElement.GetStringAttributeValue("dest"), attributeElement.ParseLocation),
                    ParseLocation = attributeElement.ParseLocation
                };

                classMapping.AttributeMappings.Add(mapping);
            }

            foreach (var relationElement in xmlElement.GetChildElments("Relation"))
            {
                var relationMapping = new RelationMapping
                {
                    Source        = new ClassRelationReference(relationElement.GetStringAttributeValue("src"), relationElement.ParseLocation),
                    Destination   = new ClassRelationReference(relationElement.GetStringAttributeValue("dest"), relationElement.ParseLocation),
                    MapAttributes = relationElement.GetBoolAttributeValue("attributes", true),
                    AddMissing    = relationElement.GetBoolAttributeValue("add-missing", true),
                    TwoWay        = relationElement.GetBoolAttributeValue("two-way", true),
                    ParseLocation = relationElement.ParseLocation
                };

                foreach (var attributeElement in relationElement.GetChildElments("Attribute"))
                {
                    var relationAttributeMapping = new AttributeMapping
                    {
                        Source        = new ClassAttributeReference(attributeElement.GetStringAttributeValue("src"), attributeElement.ParseLocation),
                        Destination   = new ClassAttributeReference(attributeElement.GetStringAttributeValue("dest"), attributeElement.ParseLocation),
                        ParseLocation = attributeElement.ParseLocation
                    };

                    relationMapping.AttributeMappings.Add(relationAttributeMapping);
                }

                classMapping.RelationMappings.Add(relationMapping);
            }

            currentClassModel.SetClassMappingData(classMapping);

            return(null);
        }
Beispiel #56
0
        public void LoadSettingsFromXml()
        {
            #region load profiles
            cmbParserProfile.Items.Clear();
            cbTextExtractor.Items.Clear();
            ClientConfiguration = ConfigXmlDocument.Clients.Find(c => c.ClientName == ClientName);
            JobConfiguration    = ClientConfiguration.ETLs.Find(etl => etl.ETLName == ETLName);
            foreach (ClassMapping extractorMapping in EasyETLEnvironment.Extractors)
            {
                cbTextExtractor.Items.Add(extractorMapping.DisplayName);
            }

            foreach (ClassMapping classMapping in EasyETLEnvironment.Parsers)
            {
                if ((classMapping.Class.GetEasyFields().Count() == 0) || (!classMapping.Class.GetEasyFields().Select(p => p.Value.DefaultValue).Contains(null)))
                {
                    cmbParserProfile.Items.Add(classMapping.DisplayName);
                }
            }

            foreach (EasyETLParser easyETLParser in ClientConfiguration.Parsers)
            {
                cmbParserProfile.Items.Add(easyETLParser.ActionName);
            }
            #endregion


            #region load all available actions
            chkAvailableActions.Items.Clear();
            fpActions.Controls.Clear();
            foreach (EasyETLAction etlAction in ClientConfiguration.Actions)
            {
                string actionName = etlAction.ActionName;
                string className  = etlAction.ClassName;
                if (EasyETLEnvironment.Actions.Where(a => a.DisplayName == className).Count() > 0)
                {
                    ClassMapping cMapping = EasyETLEnvironment.Actions.Where(a => a.DisplayName == className).First();
                    chkAvailableActions.Items.Add(etlAction.ActionName);
                    Button btnControl = new Button
                    {
                        AutoSize = true,
                        Text     = etlAction.ActionName
                    };
                    btnControl.Click += btnControl_Click;
                    fpActions.Controls.Add(btnControl);
                }
            }

            #endregion

            #region load all available exports

            chkAvailableExports.Items.Clear();
            cmbExport.Items.Clear();

            foreach (EasyETLWriter easyETLWriter in ClientConfiguration.Writers)
            {
                string       actionName         = easyETLWriter.ActionName;
                string       className          = easyETLWriter.ClassName;
                ClassMapping exportClassMapping = EasyETLEnvironment.Writers.Find(w => w.DisplayName == className);
                if (exportClassMapping != null)
                {
                    chkAvailableExports.Items.Add(actionName);
                }
            }
            #endregion

            #region load all available data sources
            cmbDatasource.Items.Clear();
            foreach (EasyETLDatasource easyETLDatasource in ClientConfiguration.Datasources)
            {
                cmbDatasource.Items.Add(easyETLDatasource.ActionName);
            }
            #endregion

            #region load all available endpoints
            cmbEndpoint.Items.Clear();
            foreach (EasyETLEndpoint easyETLEndpoint in ClientConfiguration.Endpoints)
            {
                cmbEndpoint.Items.Add(easyETLEndpoint.ActionName);
            }
            #endregion


            #region Actions Load
            foreach (EasyETLJobAction easyETLJobAction in JobConfiguration.Actions)
            {
                int  loadIndex = chkAvailableActions.Items.IndexOf(easyETLJobAction.ActionName);
                bool toCheck   = (easyETLJobAction.IsEnabled);
                if (loadIndex >= 0)
                {
                    chkAvailableActions.SetItemChecked(loadIndex, toCheck);
                }
                if (easyETLJobAction.IsDefault)
                {
                    cmbDefaultAction.Text = easyETLJobAction.ActionName;
                }
            }

            DisplayActionButtonsAsNeeded();
            #endregion

            #region Transformations Load
            cbOnLoadProfiles.Text  = JobConfiguration.Transformations.DuringLoad.SaveProfileName;
            txtOnLoadFileName.Text = JobConfiguration.Transformations.DuringLoad.SaveFileName;
            txtOnLoadContents.Text = String.Join(Environment.NewLine, JobConfiguration.Transformations.DuringLoad.SettingsCommands);

            chkUseXsltTemplate.Checked = JobConfiguration.Transformations.AfterLoad.UseXslt;
            cbTransformProfiles.Text   = JobConfiguration.Transformations.AfterLoad.SaveProfileName;
            txtTransformFileName.Text  = JobConfiguration.Transformations.AfterLoad.SaveFileName;
            txtXsltFileName.Text       = JobConfiguration.Transformations.AfterLoad.XsltFileName;
            txtTransformText.Text      = String.Join(Environment.NewLine, JobConfiguration.Transformations.AfterLoad.SettingsCommands);

            rbUseDatasetLoad.Checked     = !JobConfiguration.Transformations.Dataset.UseCustom;
            rbUseCustomTableLoad.Checked = JobConfiguration.Transformations.Dataset.UseCustom;
            txtNodeMapping.Text          = String.Join(Environment.NewLine, JobConfiguration.Transformations.Dataset.SettingsCommands);

            #endregion

            #region ParserOptions Load
            cmbParserProfile.Text = JobConfiguration.ParseOptions.ProfileName;
            #endregion

            #region Output Settings Load
            foreach (EasyETLJobExport easyETLJobExport in JobConfiguration.Exports)
            {
                int  loadIndex = chkAvailableExports.Items.IndexOf(easyETLJobExport.ExportName);
                bool toCheck   = (easyETLJobExport.IsEnabled);
                if (loadIndex >= 0)
                {
                    chkAvailableExports.SetItemChecked(loadIndex, toCheck);
                }
            }
            #endregion

            #region Permissions Settings
            btnSaveSettings.Visible = false;
            EasyETLPermission etlPermission = JobConfiguration.DefaultPermission;
            chkCanEditConfiguration.Checked    = etlPermission.CanEditSettings;
            chkShowConfigurationOnLoad.Checked = etlPermission.DisplaySettingsOnLoad;
            chkCanAddData.Checked    = etlPermission.CanAddData;
            chkCanEditData.Checked   = etlPermission.CanEditData;
            chkCanDeleteData.Checked = etlPermission.CanDeleteData;
            chkCanExportData.Checked = etlPermission.CanExportData;

            ToggleDisplayConfigurationSection(chkShowConfigurationOnLoad.Checked && etlPermission.CanViewSettings);

            chkAutoRefresh.Visible  = chkCanEditConfiguration.Checked;
            btnSaveSettings.Visible = chkCanEditConfiguration.Checked;
            pnlExport.Visible       = chkCanExportData.Checked;
            #endregion

            #region Datasource Node Load
            if (!String.IsNullOrWhiteSpace(JobConfiguration.Datasource.SourceType))
            {
                tabDataSource.SelectTab("tabDatasource" + JobConfiguration.Datasource.SourceType);
            }
            cmbEndpoint.Text            = JobConfiguration.Datasource.Endpoint;
            txtFileName.Text            = JobConfiguration.Datasource.FileName;
            chkUseTextExtractor.Checked = JobConfiguration.Datasource.UseTextExtractor;
            cbTextExtractor.Text        = JobConfiguration.Datasource.TextExtractor;
            nudMaxRows.Value            = JobConfiguration.Datasource.MaxRows > 0 ? JobConfiguration.Datasource.MaxRows : 0;
            chkHasMaxRows.Checked       = JobConfiguration.Datasource.HasMaxRows;
            cmbDatasource.Text          = JobConfiguration.Datasource.DataSource;
            txtTextContents.Text        = JobConfiguration.Datasource.TextContents;
            txtDatabaseQuery.Text       = JobConfiguration.Datasource.Query;
            #endregion

            chkAutoRefresh.Checked = JobConfiguration.AutoRefresh; // (xNode.Attributes.GetNamedItem("autorefresh") == null) ? false : Boolean.Parse(xNode.Attributes.GetNamedItem("autorefresh").Value);
        }
        public void MutableShouldBeTrueByDefaultOnClassMapping()
        {
            var mapping = new ClassMapping();

            mapping.Mutable.ShouldBeTrue();
        }
Beispiel #58
0
        public void LoadDataToGridView()
        {
            if (stopWatch.IsRunning)
            {
                stopWatch.Stop();
            }
            if ((tabDataSource.SelectedTab == tabDatasourceText) && (txtTextContents.TextLength == 0))
            {
                return;
            }
            if ((tabDataSource.SelectedTab == tabDatasourceFile) && (txtFileName.TextLength == 0))
            {
                return;
            }
            if ((tabDataSource.SelectedTab == tabDatasourceDatabase) && (String.IsNullOrWhiteSpace(cmbDatasource.Text)))
            {
                return;
            }
            AbstractFileEasyEndpoint endpoint = null;

            if (tabDataSource.SelectedTab == tabDatasourceFile)
            {
                endpoint = GetEndpoint();
                if (endpoint == null)
                {
                    return;
                }
                if (endpoint.GetList(txtFileName.Text).Length == 0)
                {
                    return;
                }
            }
            stopWatch.Restart();
            intAutoNumber      = 0;
            this.UseWaitCursor = true;
            Application.DoEvents();
            lblRecordCount.Text   = "";
            txtRegexContents.Text = "";
            cmbTableName.Items.Clear();
            AbstractContentExtractor extractor = null;

            if ((chkUseTextExtractor.Checked) && (EasyETLEnvironment.Extractors.Find(e => e.DisplayName == cbTextExtractor.Text) != null))
            {
                extractor = (AbstractContentExtractor)Activator.CreateInstance(EasyETLEnvironment.Extractors.Find(e => e.DisplayName == cbTextExtractor.Text).Class);
            }
            try
            {
                EasyXmlDocument xDoc = new EasyXmlDocument();
                xDoc.OnProgress += xDoc_OnProgress;
                if (tabDataSource.SelectedTab == tabDatasourceDatabase)
                {
                    DatasourceEasyParser dbep = null;
                    if ((cmbDatasource.SelectedItem != null) && (ClientConfiguration.Datasources.Find(ds => ds.ActionName == cmbDatasource.SelectedItem.ToString()) != null))
                    {
                        dbep = ClientConfiguration.Datasources.Find(ds => ds.ActionName == cmbDatasource.SelectedItem.ToString()).CreateDatasource();
                        if (chkHasMaxRows.Checked)
                        {
                            dbep.MaxRecords = Convert.ToInt64(nudMaxRows.Value);
                        }
                        xDoc.LoadXml(dbep.Load(txtDatabaseQuery.Text).OuterXml);
                    }
                }
                else
                {
                    AbstractEasyParser ep = null;
                    if (ClientConfiguration.Parsers.Where(p => p.ActionName == cmbParserProfile.Text).Count() > 0)
                    {
                        ep = ClientConfiguration.Parsers.Find(p => p.ActionName == cmbParserProfile.Text).CreateParser();
                    }

                    if ((ep == null) && (EasyETLEnvironment.Parsers.Where(p => p.DisplayName == cmbParserProfile.Text).Count() > 0))
                    {
                        ClassMapping parserClassMapping = EasyETLEnvironment.Parsers.Where(p => p.DisplayName == cmbParserProfile.Text).First();
                        ep = (AbstractEasyParser)Activator.CreateInstance(parserClassMapping.Class);
                    }

                    if (ep != null)
                    {
                        ep.ProgressInterval = 100;
                        if (chkHasMaxRows.Checked)
                        {
                            ep.MaxRecords = Convert.ToInt64(nudMaxRows.Value);
                        }
                        if (!String.IsNullOrWhiteSpace(txtOnLoadContents.Text))
                        {
                            ep.OnLoadSettings = txtOnLoadContents.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                        }
                        if ((tabDataSource.SelectedTab == tabDatasourceFile))
                        {
                            Stream fileStream = endpoint.GetStream(txtFileName.Text);
                            if (extractor != null)
                            {
                                extractor.FileName = txtFileName.Text;
                            }
                            xDoc.Load(fileStream, ep, extractor);
                        }
                        else
                        {
                            xDoc.LoadStr(txtTextContents.Text, ep, extractor);
                        }
                        txtExceptions.Text = "";
                        if ((ep != null) && (ep.Exceptions.Count > 0))
                        {
                            MessageBox.Show("There were " + ep.Exceptions.Count + " Exceptions while loading the document");
                            foreach (MalformedLineException mep in ep.Exceptions)
                            {
                                txtExceptions.Text += String.Format("(Line {0} - {1}", mep.LineNumber, mep.Message) + Environment.NewLine;
                            }
                        }
                    }
                }
                ezDoc = xDoc;
                try
                {
                    TransformDataFromEzDoc();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error Transforming document." + Environment.NewLine + ex.Message);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error loading contents..." + Environment.NewLine + ex.Message);
            }
            endpoint           = null;
            this.UseWaitCursor = false;
        }
Beispiel #59
0
 public PassThroughMappingProvider(ClassMapping mapping)
 {
     this.mapping = mapping;
 }
 public PocoComplexTypeSerializationInfo(ClassMapping classMapping)
 {
     _classMapping = classMapping;
 }