Beispiel #1
0
        public void RemovePropertyTest()
        {
            var cls  = new ClassDefinition("Foo", "Bar");
            var prop = new DataPropertyDefinition("ID", "");

            prop.DataType        = DataPropertyType.Int32;
            prop.IsAutoGenerated = true;
            var prop2 = new DataPropertyDefinition("Prop1", "");

            cls.AddProperty(prop, true);
            cls.AddProperty(prop2);
            Assert.Equal(cls, prop.Parent);
            Assert.Equal(cls, prop2.Parent);
            Assert.Equal(2, cls.Properties.Count);
            Assert.Single(cls.IdentityProperties);

            cls.RemoveProperty("Prop1");
            Assert.Single(cls.Properties);
            Assert.Single(cls.IdentityProperties);
            Assert.True(cls.IndexOfProperty(prop2) < 0);

            cls.RemoveProperty(prop);
            Assert.Empty(cls.Properties);
            Assert.Empty(cls.IdentityProperties);
            Assert.True(cls.IndexOfProperty(prop) < 0);
        }
Beispiel #2
0
        public static DataPropertyDefinition get_alignment_property(string i)
        {
            DataPropertyDefinition alignment_property = new DataPropertyDefinition();

            switch (i)
            {
            case "starting_station":
                DataPropertyDefinition starting_station_prop = new DataPropertyDefinition("StartingStation", "StartingStation property");
                starting_station_prop.DataType = OSGeo.FDO.Schema.DataType.DataType_Double;
                starting_station_prop.ReadOnly = false;
                starting_station_prop.Nullable = true;
                alignment_property             = starting_station_prop;
                break;

            case "ending_station":
                DataPropertyDefinition ending_station_prop = new DataPropertyDefinition("EndingStation", "EndingStation property");
                ending_station_prop.DataType = OSGeo.FDO.Schema.DataType.DataType_Double;
                ending_station_prop.ReadOnly = false;
                ending_station_prop.Nullable = true;
                alignment_property           = ending_station_prop;
                break;

            case "design_speed":
                DataPropertyDefinition design_speed_prop = new DataPropertyDefinition("DesignSpeed", "DesignSpeed property");
                design_speed_prop.DataType = OSGeo.FDO.Schema.DataType.DataType_Double;
                design_speed_prop.ReadOnly = false;
                design_speed_prop.Nullable = true;
                alignment_property         = design_speed_prop;
                break;
            }

            return(alignment_property);
        }
        public void CloneTest()
        {
            var fs = new FeatureSchema("Foo", "Bar");

            Assert.AreEqual("Foo", fs.Name);
            Assert.AreEqual("Bar", fs.Description);
            Assert.AreEqual(0, fs.Classes.Count);

            var cls = new ClassDefinition("Class1", "Test Class");
            var id  = new DataPropertyDefinition("ID", "");

            id.DataType        = DataPropertyType.Int32;
            id.IsAutoGenerated = true;
            var name = new DataPropertyDefinition("Name", "");

            cls.AddProperty(id, true);
            cls.AddProperty(name);
            fs.AddClass(cls);

            var fs2 = FeatureSchema.Clone(fs);

            Assert.AreEqual(fs.Name, fs2.Name);
            Assert.AreEqual(fs.Description, fs2.Description);
            Assert.AreEqual(fs.Classes.Count, fs2.Classes.Count);
            Assert.AreNotSame(fs, fs2);
        }
        public void TestCloneProperty()
        {
            DataPropertyDefinition dp = new DataPropertyDefinition("Foo", "Bar");

            dp.DataType        = DataType.DataType_String;
            dp.DefaultValue    = "Whatever";
            dp.IsAutoGenerated = false;
            dp.Length          = 45;
            dp.Nullable        = true;
            dp.ReadOnly        = false;
            PropertyValueConstraintList list = new PropertyValueConstraintList();

            list.ConstraintList.Add(new StringValue("A"));
            list.ConstraintList.Add(new StringValue("B"));
            list.ConstraintList.Add(new StringValue("C"));
            dp.ValueConstraint = list;

            DataPropertyDefinition dp2 = FdoSchemaUtil.CloneProperty(dp) as DataPropertyDefinition;

            AssertHelper.EqualProperty(dp, dp2);

            GeometricPropertyDefinition gp = new GeometricPropertyDefinition("Sna", "Fu");

            gp.GeometryTypes             = (int)(GeometryType.GeometryType_LineString | GeometryType.GeometryType_MultiLineString | GeometryType.GeometryType_Polygon);
            gp.HasElevation              = true;
            gp.HasMeasure                = false;
            gp.ReadOnly                  = false;
            gp.SpatialContextAssociation = "LL84";

            GeometricPropertyDefinition gp2 = FdoSchemaUtil.CloneProperty(gp) as GeometricPropertyDefinition;

            AssertHelper.EqualProperty(gp, gp2);
        }
        public void TestCloneFeatureClassNoGeometry()
        {
            FeatureClass fc = new FeatureClass("Test", "Test Feature Class");
            DataPropertyDefinition id = new DataPropertyDefinition("ID", "");
            DataPropertyDefinition name = new DataPropertyDefinition("Name", "");
            id.DataType = DataType.DataType_Int32;
            id.IsAutoGenerated = true;
            id.ReadOnly = true;
            id.Nullable = false;

            name.DataType = DataType.DataType_String;
            name.Length = 255;
            name.Nullable = true;

            fc.Properties.Add(id);
            fc.Properties.Add(name);
            fc.IdentityProperties.Add(id);

            ClassDefinition cd = FdoSchemaUtil.CloneClass(fc);
            Assert.IsNotNull(cd);
            Assert.AreEqual(cd.Name, fc.Name);
            Assert.AreEqual(cd.Description, fc.Description);
            Assert.AreEqual(cd.Properties.Count, fc.Properties.Count);
            Assert.AreEqual(cd.IdentityProperties.Count, fc.IdentityProperties.Count);
        }
Beispiel #6
0
        public void CloneTest()
        {
            var cls  = new ClassDefinition("Foo", "Bar");
            var prop = new DataPropertyDefinition("ID", "");

            prop.DataType        = DataPropertyType.Int32;
            prop.IsAutoGenerated = true;
            var prop2 = new DataPropertyDefinition("Prop1", "");

            Assert.Null(cls.FindProperty("ID"));
            cls.AddProperty(prop, true);
            Assert.Null(cls.FindProperty("Prop1"));
            cls.AddProperty(prop2);
            Assert.AreEqual(cls, prop.Parent);
            Assert.AreEqual(cls, prop2.Parent);
            Assert.AreEqual(2, cls.Properties.Count);
            Assert.AreEqual(1, cls.IdentityProperties.Count);

            var cls2 = ClassDefinition.Clone(cls);

            Assert.AreEqual(cls.Name, cls2.Name);
            Assert.AreEqual(cls.Description, cls2.Description);
            Assert.AreEqual(cls.Properties.Count, cls2.Properties.Count);
            Assert.AreEqual(cls.IdentityProperties.Count, cls2.IdentityProperties.Count);
            Assert.AreNotSame(cls, cls2);
        }
        public void TestCloneFeatureClassNoGeometry()
        {
            FeatureClass           fc   = new FeatureClass("Test", "Test Feature Class");
            DataPropertyDefinition id   = new DataPropertyDefinition("ID", "");
            DataPropertyDefinition name = new DataPropertyDefinition("Name", "");

            id.DataType        = DataType.DataType_Int32;
            id.IsAutoGenerated = true;
            id.ReadOnly        = true;
            id.Nullable        = false;

            name.DataType = DataType.DataType_String;
            name.Length   = 255;
            name.Nullable = true;

            fc.Properties.Add(id);
            fc.Properties.Add(name);
            fc.IdentityProperties.Add(id);

            ClassDefinition cd = FdoSchemaUtil.CloneClass(fc);

            Assert.IsNotNull(cd);
            Assert.AreEqual(cd.Name, fc.Name);
            Assert.AreEqual(cd.Description, fc.Description);
            Assert.AreEqual(cd.Properties.Count, fc.Properties.Count);
            Assert.AreEqual(cd.IdentityProperties.Count, fc.IdentityProperties.Count);
        }
Beispiel #8
0
        public void RemovePropertyAtTest()
        {
            var cls  = new ClassDefinition("Foo", "Bar");
            var prop = new DataPropertyDefinition("ID", "");

            prop.DataType        = DataPropertyType.Int32;
            prop.IsAutoGenerated = true;
            var prop2 = new DataPropertyDefinition("Prop1", "");

            cls.AddProperty(prop, true);
            cls.AddProperty(prop2);
            Assert.AreEqual(cls, prop.Parent);
            Assert.AreEqual(cls, prop2.Parent);
            Assert.AreEqual(2, cls.Properties.Count);
            Assert.AreEqual(1, cls.IdentityProperties.Count);

            int idx1 = cls.GetOrdinal("Prop1");

            Assert.GreaterOrEqual(idx1, 0);
            cls.RemovePropertyAt(idx1);
            Assert.AreEqual(1, cls.Properties.Count);
            Assert.AreEqual(1, cls.IdentityProperties.Count);
            Assert.Less(cls.IndexOfProperty(prop2), 0);

            int idx2 = cls.GetOrdinal("ID");

            Assert.GreaterOrEqual(idx2, 0);
            cls.RemovePropertyAt(idx2);
            Assert.AreEqual(0, cls.Properties.Count);
            Assert.AreEqual(0, cls.IdentityProperties.Count);
            Assert.Less(cls.IndexOfProperty(prop), 0);
        }
        public void WriteXmlTest()
        {
            var fs = new FeatureSchema("Foo", "Bar");

            Assert.AreEqual("Foo", fs.Name);
            Assert.AreEqual("Bar", fs.Description);
            Assert.AreEqual(0, fs.Classes.Count);

            var cls = new ClassDefinition("Class1", "Test Class");
            var id  = new DataPropertyDefinition("ID", "");

            id.DataType        = DataPropertyType.Int32;
            id.IsAutoGenerated = true;
            var name = new DataPropertyDefinition("Name", "");

            cls.AddProperty(id, true);
            cls.AddProperty(name);
            fs.AddClass(cls);

            var doc = new XmlDocument();

            fs.WriteXml(doc, doc);

            string xml = doc.ToXmlString();

            Assert.False(String.IsNullOrEmpty(xml));
        }
Beispiel #10
0
        public void IsNumericTypeTest()
        {
            var prop = new DataPropertyDefinition("Foo", "Bar");

            Assert.AreEqual("Foo", prop.Name);
            Assert.AreEqual("Bar", prop.Description);
            Assert.AreEqual(DataPropertyType.String, prop.DataType);

            foreach (DataPropertyType dt in Enum.GetValues(typeof(DataPropertyType)))
            {
                prop.DataType = dt;
                if (dt == DataPropertyType.Blob ||
                    dt == DataPropertyType.Boolean ||
                    dt == DataPropertyType.Clob ||
                    dt == DataPropertyType.DateTime ||
                    dt == DataPropertyType.String)
                {
                    Assert.False(prop.IsNumericType());
                }
                else
                {
                    Assert.True(prop.IsNumericType());
                }
            }
        }
Beispiel #11
0
        public void DataPropertyDefinitionTest()
        {
            var prop = new DataPropertyDefinition("Foo", "Bar");

            Assert.AreEqual("Foo", prop.Name);
            Assert.AreEqual("Bar", prop.Description);
            Assert.AreEqual(DataPropertyType.String, prop.DataType);
        }
Beispiel #12
0
        /// <summary>
        /// Executes the operation
        /// </summary>
        /// <param name="rows"></param>
        /// <returns></returns>
        public override IEnumerable <FdoRow> Execute(IEnumerable <FdoRow> rows)
        {
            using (FdoFeatureService service = _conn.CreateFeatureService())
            {
                using (FdoFeatureReader reader = service.SelectFeatures(this.Query))
                {
                    ClassDefinition cd = reader.GetClassDefinition();
                    foreach (PropertyDefinition pd in cd.Properties)
                    {
                        if (pd.PropertyType == PropertyType.PropertyType_RasterProperty)
                        {
                            ignoreProperties.Add(pd.Name);
                        }
                        else if (pd.PropertyType == PropertyType.PropertyType_DataProperty)
                        {
                            DataPropertyDefinition dp = pd as DataPropertyDefinition;
                            if (dp.IsAutoGenerated || dp.ReadOnly)
                            {
                                ignoreProperties.Add(pd.Name);
                            }
                        }
                        else if (pd.PropertyType == PropertyType.PropertyType_GeometricProperty)
                        {
                            GeometricPropertyDefinition gp = pd as GeometricPropertyDefinition;
                            if (gp.ReadOnly)
                            {
                                ignoreProperties.Add(gp.Name);
                            }
                        }
                    }

                    while (reader.ReadNext())
                    {
                        FdoRow row = null;
                        try
                        {
                            row = CreateRowFromReader(reader);
                        }
                        catch (Exception ex)
                        {
                            if (row != null)
                            {
                                RaiseFailedFeatureProcessed(row, ex);
                            }
                            else
                            {
                                RaiseFailedReadFeature(ex.Message, ex);
                            }
                        }
                        if (row != null)
                        {
                            yield return(row);
                        }
                    }
                }
            }
        }
Beispiel #13
0
        internal FdoFeatureReader(IFeatureReader reader) : base(reader)
        {
            _internalFactory = new FgfGeometryFactory();
            _classDefinition = reader.GetClassDefinition();
            _ptypes          = new Dictionary <string, FdoPropertyType>();
            _associations    = new Dictionary <string, string>();
            _ordinals        = new Dictionary <string, int>();
            _types           = new Type[_classDefinition.Properties.Count];
            _names           = new string[_classDefinition.Properties.Count];
            List <string> geoms = new List <string>();

            for (int i = 0; i < _names.Length; i++)
            {
                PropertyDefinition pd = _classDefinition.Properties[i];
                _names[i] = pd.Name;
                string name = _names[i];
                _ordinals.Add(_names[i], i);

                DataPropertyDefinition      dp = pd as DataPropertyDefinition;
                GeometricPropertyDefinition gp = pd as GeometricPropertyDefinition;
                if (dp != null)
                {
                    _types[i]     = ExpressUtility.GetClrTypeFromFdoDataType(dp.DataType);
                    _ptypes[name] = ValueConverter.FromDataType(dp.DataType);
                }
                else if (gp != null)
                {
                    _types[i] = typeof(byte[]);
                    geoms.Add(gp.Name);
                    _ptypes[name]       = FdoPropertyType.Geometry;
                    _associations[name] = gp.SpatialContextAssociation;
                }
                else if (pd.PropertyType == PropertyType.PropertyType_ObjectProperty)
                {
                    _ptypes[name] = FdoPropertyType.Object;
                }
                else if (pd.PropertyType == PropertyType.PropertyType_RasterProperty)
                {
                    _ptypes[name] = FdoPropertyType.Raster;
                    _types[i]     = typeof(IRaster);
                }
                else if (pd.PropertyType == PropertyType.PropertyType_AssociationProperty)
                {
                    _ptypes[name] = FdoPropertyType.Association;
                }
            }
            _geometryNames = geoms.ToArray();
            if (_classDefinition is FeatureClass && (_classDefinition as FeatureClass).GeometryProperty != null)
            {
                _defaultGeometryName = (_classDefinition as FeatureClass).GeometryProperty.Name;
            }
            else if (geoms.Count > 0)
            {
                _defaultGeometryName = geoms[0];
            }
        }
Beispiel #14
0
        /// <summary>
        /// Creates a <see cref="ClassDefinition"/> from this instance
        /// </summary>
        /// <param name="createAutoGeneratedId">If true, will add an auto-generated id property to this class definition</param>
        /// <returns>The class definition</returns>
        public ClassDefinition CreateClassDefinition(bool createAutoGeneratedId)
        {
            ClassDefinition cd = null;

            if (!string.IsNullOrEmpty(this.GeometryColumn))
            {
                FeatureClass fc = new FeatureClass(this.TableName, string.Empty);
                GeometricPropertyDefinition gp = new GeometricPropertyDefinition(this.GeometryColumn, string.Empty);
                fc.Properties.Add(gp);
                fc.GeometryProperty = gp;
                cd = fc;
            }
            else
            {
                cd = new Class(this.TableName, string.Empty);
            }

            if (createAutoGeneratedId)
            {
                int    num     = 1;
                string name    = "AutoID";
                string genName = name + num;
                string theName = string.Empty;
                if (this.Columns[name] != null)
                {
                    while (this.Columns[genName] != null)
                    {
                        genName = name + (num++);
                    }
                    theName = genName;
                }
                else
                {
                    theName = name;
                }

                DataPropertyDefinition id = new DataPropertyDefinition(theName, string.Empty);
                id.IsAutoGenerated = true;
                id.DataType        = DataType.DataType_Int32;
                cd.Properties.Add(id);
                cd.IdentityProperties.Add(id);
            }

            //Now process columns
            foreach (DataColumn dc in this.Columns)
            {
                if (dc.ColumnName != this.GeometryColumn)
                {
                    DataPropertyDefinition dp = ExpressUtility.GetDataPropertyForColumn(dc);
                    cd.Properties.Add(dp);
                }
            }
            return(cd);
        }
Beispiel #15
0
        public void GetOrdinalTest()
        {
            var cls = new ClassDefinition("Foo", "Bar");

            Assert.Less(cls.GetOrdinal("Prop1"), 0);

            var prop = new DataPropertyDefinition("Prop1", "");

            prop.DataType = DataPropertyType.String;
            cls.AddProperty(prop);
            Assert.GreaterOrEqual(cls.GetOrdinal("Prop1"), 0);
        }
Beispiel #16
0
        public void GetOrdinalTest()
        {
            var cls = new ClassDefinition("Foo", "Bar");

            Assert.True(cls.GetOrdinal("Prop1") < 0);

            var prop = new DataPropertyDefinition("Prop1", "");

            prop.DataType = DataPropertyType.String;
            cls.AddProperty(prop);
            Assert.True(cls.GetOrdinal("Prop1") >= 0);
        }
        public void TestSchemaCannotBeApplied()
        {
            FeatureSchema schema = new FeatureSchema("Default", "");
            FeatureClass  fc     = new FeatureClass("Class1", "");

            DataPropertyDefinition id = new DataPropertyDefinition("ID", "");

            id.DataType        = DataType.DataType_Int32;
            id.IsAutoGenerated = true;

            fc.Properties.Add(id);
            fc.IdentityProperties.Add(id);

            //Unsupported property in SHP
            DataPropertyDefinition d1 = new DataPropertyDefinition("Unsupported", "");

            d1.DataType = DataType.DataType_Int64;
            d1.Nullable = true;

            fc.Properties.Add(d1);

            GeometricPropertyDefinition geom = new GeometricPropertyDefinition("Geometry", "");

            geom.GeometryTypes = (int)GeometryType.GeometryType_Point;

            fc.Properties.Add(geom);
            schema.Classes.Add(fc);

            /*
             * IConnection conn = FeatureAccessManager.GetConnectionManager().CreateConnection("OSGeo.SHP");
             * conn.ConnectionString = "DefaultFileLocation=" + AppGateway.RunningApplication.AppPath;
             * using (conn)
             * {
             *  conn.Open();
             *  using (FeatureService service = new FeatureService(conn))
             *  {
             *      IncompatibleSchema incSchema = null;
             *      bool result = service.CanApplySchema(schema, out incSchema);
             *      Assert.IsNotNull(incSchema);
             *      Assert.IsFalse(result);
             *
             *      foreach (IncompatibleClass incClass in incSchema.Classes)
             *      {
             *          foreach (IncompatibleProperty incProp in incClass.Properties)
             *          {
             *              Assert.AreEqual(incProp.Reasons.Count, incProp.ReasonCodes.Count);
             *          }
             *      }
             *  }
             *  conn.Close();
             * }*/
        }
        private static ContextMenuStrip BuildSelectedPropertyContextMenu(ClassDefinition cd, EventHandler mapHandler, EventHandler removeMappingHandler, EventHandler autoCreateHandler)
        {
            ContextMenuStrip ctxSelectedProperty = new ContextMenuStrip();

            ctxSelectedProperty.Items.Add("Remove Mapping", ResourceService.GetBitmap("cross"), removeMappingHandler);
            ctxSelectedProperty.Items.Add(new ToolStripSeparator());
            ctxSelectedProperty.Items.Add("Map to property of same name (create if necessary)", null, autoCreateHandler);
            ctxSelectedProperty.Items.Add(new ToolStripSeparator());

            SortedList <string, ToolStripMenuItem> items = new SortedList <string, ToolStripMenuItem>();

            if (cd != null)
            {
                foreach (PropertyDefinition p in cd.Properties)
                {
                    if (p.PropertyType == PropertyType.PropertyType_DataProperty || p.PropertyType == PropertyType.PropertyType_GeometricProperty)
                    {
                        DataPropertyDefinition      d = p as DataPropertyDefinition;
                        GeometricPropertyDefinition g = p as GeometricPropertyDefinition;
                        string name = p.Name;
                        string text = "Map to property: " + name;
                        Image  icon = null;
                        if (d != null)
                        {
                            if (d.IsAutoGenerated || d.ReadOnly)
                            {
                                continue;
                            }

                            icon = ResourceService.GetBitmap("table");
                        }
                        else if (g != null)
                        {
                            if (g.ReadOnly)
                            {
                                continue;
                            }

                            icon = ResourceService.GetBitmap("shape_handles");
                        }
                        ToolStripMenuItem itm1 = new ToolStripMenuItem(text, icon, mapHandler);
                        itm1.Tag = name;
                        items.Add(name, itm1);
                    }
                }
            }
            foreach (ToolStripMenuItem item in items.Values)
            {
                ctxSelectedProperty.Items.Add(item);
            }
            return(ctxSelectedProperty);
        }
Beispiel #19
0
        public void ClearIdentityPropertiesTest()
        {
            var cls  = new ClassDefinition("Foo", "Bar");
            var prop = new DataPropertyDefinition("ID", "");

            prop.DataType        = DataPropertyType.Int32;
            prop.IsAutoGenerated = true;
            cls.AddProperty(prop, true);
            Assert.Equal(cls, prop.Parent);
            Assert.Single(cls.Properties);
            Assert.Single(cls.IdentityProperties);
            Assert.True(cls.GetOrdinal("ID") >= 0);
            cls.ClearIdentityProperties();
            Assert.Empty(cls.IdentityProperties);
        }
Beispiel #20
0
        public void ClearIdentityPropertiesTest()
        {
            var cls  = new ClassDefinition("Foo", "Bar");
            var prop = new DataPropertyDefinition("ID", "");

            prop.DataType        = DataPropertyType.Int32;
            prop.IsAutoGenerated = true;
            cls.AddProperty(prop, true);
            Assert.AreEqual(cls, prop.Parent);
            Assert.AreEqual(1, cls.Properties.Count);
            Assert.AreEqual(1, cls.IdentityProperties.Count);
            Assert.GreaterOrEqual(cls.GetOrdinal("ID"), 0);
            cls.ClearIdentityProperties();
            Assert.AreEqual(0, cls.IdentityProperties.Count);
        }
Beispiel #21
0
        /// <summary>
        /// Converts a <see cref="DataPropertyDefinition"/> into a <see cref="DataColumn"/>
        /// </summary>
        /// <param name="dp">The data property definition</param>
        /// <returns>The converted data column</returns>
        public static DataColumn GetDataColumnForProperty(DataPropertyDefinition dp)
        {
            DataColumn col = new DataColumn(dp.Name, GetClrTypeFromFdoDataType(dp.DataType));
            col.AllowDBNull = dp.Nullable;
            col.AutoIncrement = dp.IsAutoGenerated;
            col.ReadOnly = dp.ReadOnly;
            if (dp.DataType == DataType.DataType_String)
            {
                if (!string.IsNullOrEmpty(dp.DefaultValue))
                    col.DefaultValue = dp.DefaultValue;

                if (dp.Length > 0)
                    col.MaxLength = dp.Length;
            }
            return col;
        }
Beispiel #22
0
        private static DataPropertyDefinition ConvertDataProperty(MgDataPropertyDefinition dataProp)
        {
            var dp = new DataPropertyDefinition(dataProp.Name, dataProp.Description);

            dp.DataType        = (DataPropertyType)dataProp.DataType;
            dp.DefaultValue    = dataProp.DefaultValue;
            dp.Description     = dataProp.Description;
            dp.IsAutoGenerated = dataProp.IsAutoGenerated();
            dp.IsNullable      = dataProp.Nullable;
            dp.IsReadOnly      = dataProp.ReadOnly;
            dp.Length          = dataProp.Length;
            dp.Precision       = dataProp.Precision;
            dp.Scale           = dataProp.Scale;

            return(dp);
        }
Beispiel #23
0
        public static DataPropertyDefinition get_point_property(string i)
        {
            //add properties here
            DataPropertyDefinition point_property = new DataPropertyDefinition();

            switch (i)
            {
            case "number":
                DataPropertyDefinition number_prop = new DataPropertyDefinition("Number", "Number property");
                number_prop.DataType = OSGeo.FDO.Schema.DataType.DataType_Int16;
                number_prop.ReadOnly = false;
                number_prop.Nullable = true;
                point_property       = number_prop;
                break;
            }
            return(point_property);
        }
Beispiel #24
0
        /// <summary>
        /// Gets the clr type for the specified property definition
        /// </summary>
        /// <param name="prop"></param>
        /// <returns></returns>
        public static Type GetClrType(PropertyDefinition prop)
        {
            switch (prop.Type)
            {
            case PropertyDefinitionType.Data:
            {
                DataPropertyDefinition dp = (DataPropertyDefinition)prop;
                return(GetClrType(dp.DataType));
            };

            case PropertyDefinitionType.Geometry:
                return(typeof(IGeometry));

            case PropertyDefinitionType.Object:
                return(typeof(IFeature[]));
                //case PropertyDefinitionType.Raster:
            }
            throw new ArgumentException();
        }
Beispiel #25
0
        public void FindPropertyTest()
        {
            var cls  = new ClassDefinition("Foo", "Bar");
            var prop = new DataPropertyDefinition("ID", "");

            prop.DataType        = DataPropertyType.Int32;
            prop.IsAutoGenerated = true;
            var prop2 = new DataPropertyDefinition("Prop1", "");

            Assert.Null(cls.FindProperty("ID"));
            cls.AddProperty(prop, true);
            Assert.Null(cls.FindProperty("Prop1"));
            cls.AddProperty(prop2);
            Assert.AreEqual(cls, prop.Parent);
            Assert.AreEqual(cls, prop2.Parent);
            Assert.AreEqual(2, cls.Properties.Count);
            Assert.AreEqual(1, cls.IdentityProperties.Count);

            Assert.NotNull(cls.FindProperty("ID"));
            Assert.NotNull(cls.FindProperty("Prop1"));
        }
Beispiel #26
0
        /// <summary>
        /// Converts a <see cref="DataColumn"/> object into a <see cref="DataPropertyDefinition"/>
        /// </summary>
        /// <param name="col">The data column</param>
        /// <returns>The converted data property definition</returns>
        public static DataPropertyDefinition GetDataPropertyForColumn(DataColumn col)
        {
            DataPropertyDefinition dp = new DataPropertyDefinition(col.ColumnName, string.Empty);

            dp.DataType        = GetFdoDataTypeFromClrType(col.DataType);
            dp.Nullable        = col.AllowDBNull;
            dp.IsAutoGenerated = col.AutoIncrement;
            dp.ReadOnly        = col.ReadOnly;
            if (dp.DataType == DataType.DataType_String)
            {
                if (col.MaxLength > 0)
                {
                    dp.Length = col.MaxLength;
                }
                else
                {
                    dp.Length = DEFAULT_STRING_LENGTH;
                }
            }
            return(dp);
        }
Beispiel #27
0
        public object GetValue(string attribute)
        {
            PropertyDefinition pd = _fields[attribute];

            if (pd == null)
            {
                throw new IndexOutOfRangeException(string.Format("The attribute field '{0}' was not found."));
            }
            else
            {
                DataPropertyDefinition dpd = pd as DataPropertyDefinition;
                if (dpd == null)
                {
                    throw new InvalidOperationException(string.Format("The attribute field definition for {0} could not be converted to 'DataPropertyDefinition'.", attribute));
                }
                else
                {
                    return(GetValue(_featureReader, dpd.Name, dpd.DataType));
                }
            }
        }
Beispiel #28
0
        /// <summary>
        /// Converts a <see cref="DataPropertyDefinition"/> into a <see cref="DataColumn"/>
        /// </summary>
        /// <param name="dp">The data property definition</param>
        /// <returns>The converted data column</returns>
        public static DataColumn GetDataColumnForProperty(DataPropertyDefinition dp)
        {
            DataColumn col = new DataColumn(dp.Name, GetClrTypeFromFdoDataType(dp.DataType));

            col.AllowDBNull   = dp.Nullable;
            col.AutoIncrement = dp.IsAutoGenerated;
            col.ReadOnly      = dp.ReadOnly;
            if (dp.DataType == DataType.DataType_String)
            {
                if (!string.IsNullOrEmpty(dp.DefaultValue))
                {
                    col.DefaultValue = dp.DefaultValue;
                }

                if (dp.Length > 0)
                {
                    col.MaxLength = dp.Length;
                }
            }
            return(col);
        }
Beispiel #29
0
        private static void PrepareClass(ClassDefinition cls, ICollection <string> propNames, ICollection <string> joinProps, string prefix, string geomProp)
        {
            var props  = cls.Properties;
            var remove = new List <PropertyDefinition>();

            foreach (PropertyDefinition p in props)
            {
                if (!propNames.Contains(p.Name) && !joinProps.Contains(p.Name))
                {
                    if (!string.IsNullOrEmpty(geomProp) && p.Name == geomProp)
                    {
                        continue;
                    }

                    remove.Add(p);
                }
            }
            foreach (PropertyDefinition p in remove)
            {
                props.Remove(p);
            }

            //Strip auto-generation because we want to preserve all original values (even from auto-generated properties)
            foreach (PropertyDefinition p in props)
            {
                if (p.PropertyType == PropertyType.PropertyType_DataProperty)
                {
                    DataPropertyDefinition dp = (DataPropertyDefinition)p;
                    dp.IsAutoGenerated = false;
                }
            }

            if (!string.IsNullOrEmpty(prefix))
            {
                foreach (PropertyDefinition p in props)
                {
                    p.Name = prefix + p.Name;
                }
            }
        }
        /// <summary>
        /// Initializes this instance
        /// </summary>
        /// <param name="pipelineExecuter"></param>
        public override void PrepareForExecution(IPipelineExecuter pipelineExecuter)
        {
            //Omit read-only properties
            using (FdoFeatureService service = _conn.CreateFeatureService())
            {
                ClassDefinition c = service.GetClassByName(this.ClassName);
                foreach (PropertyDefinition p in c.Properties)
                {
                    string name = p.Name;
                    if (p.PropertyType != PropertyType.PropertyType_DataProperty && p.PropertyType != PropertyType.PropertyType_GeometricProperty)
                    {
                        _unWritableProperties.Add(name);
                    }
                    else
                    {
                        if (p.PropertyType == PropertyType.PropertyType_GeometricProperty)
                        {
                            GeometricPropertyDefinition g = p as GeometricPropertyDefinition;
                            if (g.ReadOnly)
                            {
                                _unWritableProperties.Add(name);
                            }
                        }
                        else
                        {
                            DataPropertyDefinition d = p as DataPropertyDefinition;
                            if (d.ReadOnly) //|| d.IsAutoGenerated)
                            {
                                _unWritableProperties.Add(name);
                            }
                        }
                    }
                }
                c.Dispose();
            }

            base.PrepareForExecution(pipelineExecuter);
        }
        public void TestSchemaCanBeApplied()
        {
            FeatureSchema schema = new FeatureSchema("Default", "");
            FeatureClass  fc     = new FeatureClass("Class1", "");

            DataPropertyDefinition id = new DataPropertyDefinition("ID", "");

            id.DataType        = DataType.DataType_Int32;
            id.IsAutoGenerated = true;

            fc.Properties.Add(id);
            fc.IdentityProperties.Add(id);

            GeometricPropertyDefinition geom = new GeometricPropertyDefinition("Geometry", "");

            geom.GeometryTypes = (int)GeometryType.GeometryType_Point;

            fc.Properties.Add(geom);
            schema.Classes.Add(fc);

            /*
             * IConnection conn = FeatureAccessManager.GetConnectionManager().CreateConnection("OSGeo.SHP");
             * conn.ConnectionString = "DefaultFileLocation=" + AppGateway.RunningApplication.AppPath;
             * using (conn)
             * {
             *  conn.Open();
             *  using (FeatureService service = new FeatureService(conn))
             *  {
             *      IncompatibleSchema incSchema = null;
             *      bool result = service.CanApplySchema(schema, out incSchema);
             *      Assert.IsNull(incSchema);
             *      Assert.IsTrue(result);
             *  }
             *  conn.Close();
             * }*/
        }
        /// <summary>
        /// Adds the data property.
        /// </summary>
        /// <param name="dataDef">The data def.</param>
        /// <param name="szClassHierarchy">The class name hierarchy.</param>
        public void AddDataProperty(DataPropertyDefinition dataDef, String szClassHierarchy)
        {
            if (dataDef.IsAutoGenerated || dataDef.ReadOnly)
                return;

            DataGridViewRow row = new DataGridViewRow();
            DataGridViewTextBoxCell nameCell = new DataGridViewTextBoxCell();

            if (!String.IsNullOrEmpty(szClassHierarchy))
                nameCell.Value = szClassHierarchy + ".";
            nameCell.Value += dataDef.Name;

            nameCell.ToolTipText = "Type: " + dataDef.DataType;
            nameCell.Tag = dataDef;

            DataGridViewCell valueCell = null;
            if (dataDef.ValueConstraint != null && dataDef.ValueConstraint.ConstraintType == PropertyValueConstraintType.PropertyValueConstraintType_List)
            {
                PropertyValueConstraintList list = (dataDef.ValueConstraint as PropertyValueConstraintList);
                DataGridViewComboBoxCell cc = new DataGridViewComboBoxCell();
                List<string> values = new List<string>();
                foreach (DataValue value in list.ConstraintList)
                {
                    values.Add(value.ToString());
                }
                cc.DataSource = values;
                valueCell = cc;
            }
            else
            {
                switch (dataDef.DataType)
                {
                    case DataType.DataType_BLOB:
                        {
                            DataGridViewTextBoxCell tc = new DataGridViewTextBoxCell();
                            tc.MaxInputLength = dataDef.Length;
                            valueCell = tc;
                        }
                        break;
                    case DataType.DataType_Boolean:
                        valueCell = new DataGridViewTextBoxCell();
                        break;
                    case DataType.DataType_Byte:
                        valueCell = new DataGridViewTextBoxCell();
                        break;
                    case DataType.DataType_CLOB:
                        {
                            DataGridViewTextBoxCell tc = new DataGridViewTextBoxCell();
                            tc.MaxInputLength = dataDef.Length;
                            valueCell = tc;
                        }
                        break;
                    case DataType.DataType_DateTime:
                        valueCell = new DataGridViewTextBoxCell();
                        break;
                    case DataType.DataType_Decimal:
                        valueCell = new DataGridViewTextBoxCell();
                        break;
                    case DataType.DataType_Double:
                        valueCell = new DataGridViewTextBoxCell();
                        break;
                    case DataType.DataType_Int16:
                        valueCell = new DataGridViewTextBoxCell();
                        break;
                    case DataType.DataType_Int32:
                        valueCell = new DataGridViewTextBoxCell();
                        break;
                    case DataType.DataType_Int64:
                        valueCell = new DataGridViewTextBoxCell();
                        break;
                    case DataType.DataType_Single:
                        valueCell = new DataGridViewTextBoxCell();
                        break;
                    case DataType.DataType_String:
                        {
                            DataGridViewTextBoxCell tc = new DataGridViewTextBoxCell();
                            tc.MaxInputLength = dataDef.Length;
                            valueCell = tc;
                        }
                        break;
                }
            }
            valueCell.Style.BackColor = dataDef.Nullable ? Color.YellowGreen : Color.White;
            valueCell.Value = dataDef.DefaultValue;
            valueCell.ToolTipText = dataDef.Description;

            row.Cells.Add(nameCell);
            row.Cells.Add(valueCell);

            nameCell.ReadOnly = true;

            grdProperties.Rows.Add(row);
        }
 /// <summary>
 /// Adds the data property.
 /// </summary>
 /// <param name="dataDef">The data def.</param>
 public void AddDataProperty(DataPropertyDefinition dataDef)
 {
     AddDataProperty(dataDef, null);
 }
        public void TestAlterSchemaBaseClass()
        {
            MockRepository mocks = new MockRepository();
            FeatureSchema schema = new FeatureSchema("Default", "");
            IConnection conn = mocks.DynamicMock<IConnection>();
            ISchemaCapabilities caps = mocks.DynamicMock<ISchemaCapabilities>();

            using (mocks.Record())
            {
                SetupResult.For(conn.ConnectionState).Return(ConnectionState.ConnectionState_Open);
                SetupResult.For(conn.SchemaCapabilities).Return(caps);
                SetupResult.For(caps.ClassTypes).Return((ClassType[])Enum.GetValues(typeof(ClassType)));
                SetupResult.For(caps.DataTypes).Return((DataType[])Enum.GetValues(typeof(DataType)));
                SetupResult.For(caps.MaximumDecimalPrecision).Return(20);
                SetupResult.For(caps.MaximumDecimalScale).Return(20);
                SetupResult.For(caps.ReservedCharactersForName).Return(string.Empty);
                SetupResult.For(caps.SupportedAutoGeneratedTypes).Return(new DataType[] { DataType.DataType_Int32, DataType.DataType_Int64 });
                SetupResult.For(caps.SupportedIdentityPropertyTypes).Return(new DataType[] { DataType.DataType_Int32, DataType.DataType_Int64 });
                SetupResult.For(caps.SupportsAssociationProperties).Return(false);
                SetupResult.For(caps.SupportsAutoIdGeneration).Return(true);
                SetupResult.For(caps.SupportsCompositeId).Return(false);
                SetupResult.For(caps.SupportsCompositeUniqueValueConstraints).Return(false);
                SetupResult.For(caps.SupportsDataStoreScopeUniqueIdGeneration).Return(false);
                SetupResult.For(caps.SupportsDefaultValue).Return(true);
                SetupResult.For(caps.SupportsExclusiveValueRangeConstraints).Return(false);
                SetupResult.For(caps.SupportsInclusiveValueRangeConstraints).Return(false);
                SetupResult.For(caps.SupportsMultipleSchemas).Return(false);
                SetupResult.For(caps.SupportsNetworkModel).Return(false);
                SetupResult.For(caps.SupportsNullValueConstraints).Return(true);
                SetupResult.For(caps.SupportsObjectProperties).Return(false);
                SetupResult.For(caps.SupportsSchemaModification).Return(true);
                SetupResult.For(caps.SupportsSchemaOverrides).Return(false);
                SetupResult.For(caps.SupportsUniqueValueConstraints).Return(false);
                SetupResult.For(caps.SupportsValueConstraintsList).Return(false);

                SetupResult.For(caps.SupportsInheritance).Return(false);
            }
            FdoFeatureService service = mocks.DynamicMock<FdoFeatureService>(conn);
            mocks.ReplayAll();

            ClassDefinition baseClass = new Class("Base", "");

            //ID
            DataPropertyDefinition id = new DataPropertyDefinition("ID", "");
            id.DataType = DataType.DataType_Int64;
            id.Nullable = false;

            baseClass.Properties.Add(id);
            baseClass.IdentityProperties.Add(id);

            //Name
            DataPropertyDefinition name = new DataPropertyDefinition("Name", "");
            name.DataType = DataType.DataType_String;
            name.Nullable = true;
            name.Length = 100;

            baseClass.Properties.Add(name);

            ClassDefinition derivedClass = new Class("Derived", "");
            derivedClass.BaseClass = baseClass;

            //DOB
            DataPropertyDefinition dob = new DataPropertyDefinition("DOB", "");
            dob.DataType = DataType.DataType_DateTime;
            dob.Nullable = true;

            derivedClass.Properties.Add(dob);

            schema.Classes.Add(baseClass);
            schema.Classes.Add(derivedClass);

            IncompatibleSchema incSchema = null;
            bool canApply = service.CanApplySchema(schema, out incSchema);
            Assert.IsFalse(canApply);
            Assert.IsNotNull(incSchema);

            FeatureSchema newSchema = service.AlterSchema(schema, incSchema);

            ClassDefinition newClass = newSchema.Classes[newSchema.Classes.IndexOf("Derived")];

            //Base class properties should be copied to derived class
            Assert.AreEqual("BASE_ID", newClass.IdentityProperties[0].Name);
            Assert.AreEqual(3, newClass.Properties.Count);
            Assert.IsTrue(newClass.Properties.IndexOf("BASE_ID") >= 0);
            Assert.IsTrue(newClass.Properties.IndexOf("BASE_Name") >= 0);
        }
 /// <summary>
 /// Adds the data property.
 /// </summary>
 /// <param name="dataDef">The data def.</param>
 /// <param name="value">The update value</param>
 public void AddDataProperty(DataPropertyDefinition dataDef, object value)
 {
     AddDataProperty(dataDef, value, null);
 }
Beispiel #36
0
        void RunExport(string fileName)
        {
            CadastralMapModel mapModel = CadastralMapModel.Current;

            using (ICreateDataStore cmd = m_Connection.CreateCommand(CommandType.CommandType_CreateDataStore) as ICreateDataStore)
            {
                try
                {
                    cmd.DataStoreProperties.SetProperty("File", fileName);
                    cmd.Execute();
                }
                catch (OSGeo.FDO.Common.Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            // The connection after the created is ConnectionState_Closed, so open it!
            m_Connection.ConnectionInfo.ConnectionProperties.SetProperty("File", fileName);
            m_Connection.Open();

            // Define coordinate system
            using (ICreateSpatialContext cmd = m_Connection.CreateCommand(CommandType.CommandType_CreateSpatialContext) as ICreateSpatialContext)
            {
                ISpatialSystem ss = mapModel.SpatialSystem;
                cmd.CoordinateSystem = ss.Name; // CSMap key name
                cmd.ExtentType = SpatialContextExtentType.SpatialContextExtentType_Static;
                IWindow mapExtent = mapModel.Extent;
                IDirectPosition minxy = m_Factory.CreatePositionXY(mapExtent.Min.X, mapExtent.Min.Y);
                IDirectPosition maxxy = m_Factory.CreatePositionXY(mapExtent.Max.X, mapExtent.Max.Y);
                IEnvelope extent = m_Factory.CreateEnvelope(minxy, maxxy);
                IGeometry gx = m_Factory.CreateGeometry(extent);
                cmd.Extent = m_Factory.GetFgf(gx);
                cmd.XYTolerance = 0.000001; // resolution?
                cmd.CoordinateSystemWkt = EditingController.Current.GetCoordinateSystemText();
                cmd.Execute();
            }

            // Define feature schema
            FeatureSchema fs = new FeatureSchema("Steve", "This is a test");

            FeatureClass fc = new FeatureClass("FC", "Test feature class");
            fs.Classes.Add(fc);
            GeometricPropertyDefinition gp = new GeometricPropertyDefinition("Geometry", "Polygon property");

            // When you stick more than one geometric type into the output, you can't
            // convert to SHP (not with FDO Toolbox anyway).
            //gp.GeometryTypes = (int)GeometricType.GeometricType_Surface;
            gp.GeometryTypes = (int)GeometricType.GeometricType_All;
            fc.Properties.Add(gp);
            fc.GeometryProperty = gp;

            // c.f. FdoToolbox ExpressUtility
            DataPropertyDefinition dp = new DataPropertyDefinition("ID", "Test ID");
            dp.DataType = DataType.DataType_Int32;
            dp.Nullable = false;
            dp.ReadOnly = true;
            dp.IsAutoGenerated = true;
            fc.Properties.Add(dp);

            // Feature class requires an identity column for the insert
            fc.IdentityProperties.Add(dp);

            using (IApplySchema cmd = m_Connection.CreateCommand(CommandType.CommandType_ApplySchema) as IApplySchema)
            {
                cmd.FeatureSchema = fs;
                cmd.Execute();
            }

            mapModel.Index.QueryWindow(null, SpatialType.Polygon | SpatialType.Point, ExportFeature);

            m_Connection.Flush();
            m_Connection.Close();
        }
        public void TestCloneClass()
        {
            ClassDefinition c1 = new FeatureClass("Test", "Test Feature Class");
            DataPropertyDefinition id = new DataPropertyDefinition("ID", "");
            DataPropertyDefinition name = new DataPropertyDefinition("Name", "");
            id.DataType = DataType.DataType_Int32;
            id.IsAutoGenerated = true;
            id.ReadOnly = true;
            id.Nullable = false;

            name.DataType = DataType.DataType_String;
            name.Length = 255;
            name.Nullable = true;

            GeometricPropertyDefinition geom = new GeometricPropertyDefinition("Geometry", "");
            geom.GeometryTypes = (int)GeometryType.GeometryType_Polygon;
            geom.ReadOnly = false;

            c1.Properties.Add(id);
            c1.Properties.Add(name);
            c1.Properties.Add(geom);
            c1.IdentityProperties.Add(id);

            ((FeatureClass)c1).GeometryProperty = geom;

            ClassDefinition cd = FdoSchemaUtil.CloneClass(c1);
            Assert.IsNotNull(cd);
            FeatureClass fc = cd as FeatureClass;
            Assert.IsNotNull(fc);
            Assert.AreEqual(cd.Name, c1.Name);
            Assert.AreEqual(cd.ClassType, c1.ClassType);
            Assert.IsNotNull(fc.GeometryProperty);
            Assert.IsNotNull(((FeatureClass)c1).GeometryProperty);
            Assert.AreEqual(fc.GeometryProperty.Name, ((FeatureClass)c1).GeometryProperty.Name);
            Assert.AreEqual(cd.Description, c1.Description);
            Assert.AreEqual(cd.Properties.Count, c1.Properties.Count);
            Assert.AreEqual(cd.IdentityProperties.Count, c1.IdentityProperties.Count);

            c1.Dispose();
            c1 = new Class("TestClass", "Test Class");
            id = new DataPropertyDefinition("ID", "");
            name = new DataPropertyDefinition("Name", "");

            id.DataType = DataType.DataType_Int32;
            id.IsAutoGenerated = true;
            id.ReadOnly = true;
            id.Nullable = false;

            name.DataType = DataType.DataType_String;
            name.Length = 255;
            name.Nullable = true;

            cd = FdoSchemaUtil.CloneClass(c1);
            Assert.IsNotNull(cd);
            Assert.AreEqual(cd.Name, c1.Name);
            Assert.AreEqual(cd.Description, c1.Description);
            Assert.AreEqual(cd.Properties.Count, c1.Properties.Count);
            Assert.AreEqual(cd.IdentityProperties.Count, c1.IdentityProperties.Count);
        }
        public void TestSchemaCannotBeApplied()
        {
            FeatureSchema schema = new FeatureSchema("Default", "");
            FeatureClass fc = new FeatureClass("Class1", "");

            DataPropertyDefinition id = new DataPropertyDefinition("ID", "");
            id.DataType = DataType.DataType_Int32;
            id.IsAutoGenerated = true;

            fc.Properties.Add(id);
            fc.IdentityProperties.Add(id);

            //Unsupported property in SHP
            DataPropertyDefinition d1 = new DataPropertyDefinition("Unsupported", "");
            d1.DataType = DataType.DataType_Int64;
            d1.Nullable = true;

            fc.Properties.Add(d1);

            GeometricPropertyDefinition geom = new GeometricPropertyDefinition("Geometry", "");
            geom.GeometryTypes = (int)GeometryType.GeometryType_Point;

            fc.Properties.Add(geom);
            schema.Classes.Add(fc);

            /*
            IConnection conn = FeatureAccessManager.GetConnectionManager().CreateConnection("OSGeo.SHP");
            conn.ConnectionString = "DefaultFileLocation=" + AppGateway.RunningApplication.AppPath;
            using (conn)
            {
                conn.Open();
                using (FeatureService service = new FeatureService(conn))
                {
                    IncompatibleSchema incSchema = null;
                    bool result = service.CanApplySchema(schema, out incSchema);
                    Assert.IsNotNull(incSchema);
                    Assert.IsFalse(result);

                    foreach (IncompatibleClass incClass in incSchema.Classes)
                    {
                        foreach (IncompatibleProperty incProp in incClass.Properties)
                        {
                            Assert.AreEqual(incProp.Reasons.Count, incProp.ReasonCodes.Count);
                        }
                    }
                }
                conn.Close();
            }*/
        }
        /// <summary>
        /// Creates a <see cref="ClassDefinition"/> from this instance
        /// </summary>
        /// <param name="createAutoGeneratedId">If true, will add an auto-generated id property to this class definition</param>
        /// <returns>The class definition</returns>
        public ClassDefinition CreateClassDefinition(bool createAutoGeneratedId)
        {
            ClassDefinition cd = null;
            if (!string.IsNullOrEmpty(this.GeometryColumn))
            {
                FeatureClass fc = new FeatureClass(this.TableName, string.Empty);
                GeometricPropertyDefinition gp = new GeometricPropertyDefinition(this.GeometryColumn, string.Empty);
                fc.Properties.Add(gp);
                fc.GeometryProperty = gp;
                cd = fc;
            }
            else
            {
                cd = new Class(this.TableName, string.Empty);
            }

            if (createAutoGeneratedId)
            {
                int num = 1;
                string name = "AutoID";
                string genName = name + num;
                string theName = string.Empty;
                if (this.Columns[name] != null)
                {
                    while (this.Columns[genName] != null)
                    {
                        genName = name + (num++);
                    }
                    theName = genName;
                }
                else
                {
                    theName = name;
                }

                DataPropertyDefinition id = new DataPropertyDefinition(theName, string.Empty);
                id.IsAutoGenerated = true;
                id.DataType = DataType.DataType_Int32;
                cd.Properties.Add(id);
                cd.IdentityProperties.Add(id);
            }

            //Now process columns
            foreach (DataColumn dc in this.Columns)
            {
                if (dc.ColumnName != this.GeometryColumn)
                {
                    DataPropertyDefinition dp = ExpressUtility.GetDataPropertyForColumn(dc);
                    cd.Properties.Add(dp);
                }
            }
            return cd;
        }
Beispiel #40
0
 /// <summary>
 /// Converts a <see cref="DataColumn"/> object into a <see cref="DataPropertyDefinition"/>
 /// </summary>
 /// <param name="col">The data column</param>
 /// <returns>The converted data property definition</returns>
 public static DataPropertyDefinition GetDataPropertyForColumn(DataColumn col)
 {
     DataPropertyDefinition dp = new DataPropertyDefinition(col.ColumnName, string.Empty);
     dp.DataType = GetFdoDataTypeFromClrType(col.DataType);
     dp.Nullable = col.AllowDBNull;
     dp.IsAutoGenerated = col.AutoIncrement;
     dp.ReadOnly = col.ReadOnly;
     if (dp.DataType == DataType.DataType_String)
     {
         if (col.MaxLength > 0)
             dp.Length = col.MaxLength;
         else
             dp.Length = DEFAULT_STRING_LENGTH;
     }
     return dp;
 }
Beispiel #41
0
        private ClassDefinition CreateMergedClass(ClassDefinition leftCls, ClassDefinition rightCls)
        {
            ClassDefinition cls = null;

            if (!string.IsNullOrEmpty(_options.GeometryProperty))
                cls = new FeatureClass(_options.Target.ClassName, "");
            else
                cls = new Class(_options.Target.ClassName, "");

            var props = cls.Properties;
            foreach (PropertyDefinition p in leftCls.Properties)
            {
                int idx = props.IndexOf(p.Name);
                if (idx < 0)
                {
                    var prop = FdoSchemaUtil.CloneProperty(p);
                    props.Add(prop);
                }
            }
            foreach (PropertyDefinition p in rightCls.Properties)
            {
                int idx = props.IndexOf(p.Name);
                if (idx < 0)
                {
                    var prop = FdoSchemaUtil.CloneProperty(p);
                    props.Add(prop);
                }
            }

            //Strip off autogeneration because we want to preserve original values
            foreach (PropertyDefinition p in props)
            {
                if (p.PropertyType == PropertyType.PropertyType_DataProperty)
                {
                    DataPropertyDefinition dp = (DataPropertyDefinition)p;
                    dp.IsAutoGenerated = false;
                }
            }

            DataPropertyDefinition fid = new DataPropertyDefinition("FID", "Autogenerated ID");
            fid.DataType = DataType.DataType_Int32;
            fid.IsAutoGenerated = true;
            fid.Nullable = false;

            props.Add(fid);
            cls.IdentityProperties.Add(fid);

            if (!string.IsNullOrEmpty(_options.GeometryProperty))
            {
                //If prefixed, we need to qualify it to match what's in the merged class
                string pn = _options.GeometryProperty;
                if (_options.Side == JoinSide.Left)
                {
                    if (!string.IsNullOrEmpty(_options.LeftPrefix))
                        pn = _options.LeftPrefix + pn;
                }
                else
                {
                    if (!string.IsNullOrEmpty(_options.RightPrefix))
                        pn = _options.RightPrefix + pn;
                }

                int idx = props.IndexOf(pn);
                if (idx < 0)
                {
                    throw new FdoETLException("Property not found in merged class: " + _options.GeometryProperty);
                }
                else
                {
                    var p = props[idx];
                    if (p.PropertyType != PropertyType.PropertyType_GeometricProperty)
                        throw new FdoETLException("Designated property is not a geometry property: " + _options.GeometryProperty);

                    ((FeatureClass)cls).GeometryProperty = (GeometricPropertyDefinition)p;
                }
            }

            return cls;
        }
 private void WriteDataProperty(DataPropertyDefinition data)
 {
     Console.WriteLine("\tData Type: {0}", data.DataType);
     Console.WriteLine("\tNullable: {0}\n\tAuto-Generated: {1}\n\tRead-Only: {2}", data.Nullable, data.IsAutoGenerated, data.ReadOnly);
     Console.WriteLine("\tLength: {0}\n\tPrecision: {1}\n\tScale: {2}", data.Length, data.Precision, data.Scale);
 }
        public void TestSchemaCanBeApplied()
        {
            FeatureSchema schema = new FeatureSchema("Default", "");
            FeatureClass fc = new FeatureClass("Class1", "");

            DataPropertyDefinition id = new DataPropertyDefinition("ID", "");
            id.DataType = DataType.DataType_Int32;
            id.IsAutoGenerated = true;

            fc.Properties.Add(id);
            fc.IdentityProperties.Add(id);

            GeometricPropertyDefinition geom = new GeometricPropertyDefinition("Geometry", "");
            geom.GeometryTypes = (int)GeometryType.GeometryType_Point;

            fc.Properties.Add(geom);
            schema.Classes.Add(fc);

            /*
            IConnection conn = FeatureAccessManager.GetConnectionManager().CreateConnection("OSGeo.SHP");
            conn.ConnectionString = "DefaultFileLocation=" + AppGateway.RunningApplication.AppPath;
            using (conn)
            {
                conn.Open();
                using (FeatureService service = new FeatureService(conn))
                {
                    IncompatibleSchema incSchema = null;
                    bool result = service.CanApplySchema(schema, out incSchema);
                    Assert.IsNull(incSchema);
                    Assert.IsTrue(result);
                }
                conn.Close();
            }*/
        }
        public void TestAlterSchemaPassValueConstraints()
        {
            MockRepository mocks = new MockRepository();
            IConnection conn = mocks.DynamicMock<IConnection>();
            ISchemaCapabilities caps = mocks.DynamicMock<ISchemaCapabilities>();

            using (mocks.Record())
            {
                SetupResult.For(conn.ConnectionState).Return(ConnectionState.ConnectionState_Open);
                SetupResult.For(conn.SchemaCapabilities).Return(caps);
                SetupResult.For(caps.ClassTypes).Return((ClassType[])Enum.GetValues(typeof(ClassType)));
                SetupResult.For(caps.DataTypes).Return((DataType[])Enum.GetValues(typeof(DataType)));
                SetupResult.For(caps.MaximumDecimalPrecision).Return(20);
                SetupResult.For(caps.MaximumDecimalScale).Return(20);
                SetupResult.For(caps.ReservedCharactersForName).Return(string.Empty);
                SetupResult.For(caps.SupportedAutoGeneratedTypes).Return(new DataType[] { DataType.DataType_Int64 });
                SetupResult.For(caps.SupportedIdentityPropertyTypes).Return(new DataType[] { DataType.DataType_Int32, DataType.DataType_Int64 });
                SetupResult.For(caps.SupportsAssociationProperties).Return(false);
                SetupResult.For(caps.SupportsAutoIdGeneration).Return(true);
                SetupResult.For(caps.SupportsCompositeId).Return(false);
                SetupResult.For(caps.SupportsCompositeUniqueValueConstraints).Return(false);
                SetupResult.For(caps.SupportsDataStoreScopeUniqueIdGeneration).Return(false);
                SetupResult.For(caps.SupportsDefaultValue).Return(true);
                //--
                SetupResult.For(caps.SupportsExclusiveValueRangeConstraints).Return(false);
                SetupResult.For(caps.SupportsInclusiveValueRangeConstraints).Return(false);
                //--
                SetupResult.For(caps.SupportsMultipleSchemas).Return(false);
                SetupResult.For(caps.SupportsNetworkModel).Return(false);
                SetupResult.For(caps.SupportsNullValueConstraints).Return(true);
                SetupResult.For(caps.SupportsObjectProperties).Return(false);
                SetupResult.For(caps.SupportsSchemaModification).Return(true);
                SetupResult.For(caps.SupportsSchemaOverrides).Return(false);
                SetupResult.For(caps.SupportsUniqueValueConstraints).Return(false);
                //--
                SetupResult.For(caps.SupportsValueConstraintsList).Return(false);
                //--
                SetupResult.For(caps.SupportsInheritance).Return(false);
            }
            FdoFeatureService service = mocks.StrictMock<FdoFeatureService>(conn);
            mocks.ReplayAll();

            FeatureSchema schema = new FeatureSchema("Default", "");

            ClassDefinition cls = new Class("Test", "");

            //ID
            DataPropertyDefinition id = new DataPropertyDefinition("ID", "");
            id.DataType = DataType.DataType_Int64;
            id.IsAutoGenerated = true; //Should be converted to int64
            id.ReadOnly = true;
            id.Nullable = false;

            cls.Properties.Add(id);
            cls.IdentityProperties.Add(id);

            //Age
            DataPropertyDefinition age = new DataPropertyDefinition("Age", "");
            PropertyValueConstraintRange range = new PropertyValueConstraintRange();
            range.MinValue = new Int32Value(0);
            range.MinInclusive = true;
            range.MaxValue = new Int32Value(100);
            range.MaxInclusive = true;
            age.ValueConstraint = range;
            age.DataType = DataType.DataType_Int32;
            age.Nullable = true;

            cls.Properties.Add(age);

            //Gender
            DataPropertyDefinition gender = new DataPropertyDefinition("Gender", "");
            PropertyValueConstraintList list = new PropertyValueConstraintList();
            list.ConstraintList.Add(new StringValue("M"));
            list.ConstraintList.Add(new StringValue("F"));
            gender.ValueConstraint = list;
            age.DataType = DataType.DataType_String;
            age.Nullable = false;
            age.Length = 1;

            cls.Properties.Add(gender);

            schema.Classes.Add(cls);

            IncompatibleSchema incSchema = null;
            bool canApply = service.CanApplySchema(schema, out incSchema);
            Assert.IsFalse(canApply);
            Assert.IsNotNull(incSchema);

            FeatureSchema newSchema = service.AlterSchema(schema, incSchema);

            ClassDefinition newClass = newSchema.Classes[0];

            DataPropertyDefinition age2 = newClass.Properties[newClass.Properties.IndexOf("Age")] as DataPropertyDefinition;

            //Should have constraint removed
            Assert.IsNull(age2.ValueConstraint);

            DataPropertyDefinition gender2 = newClass.Properties[newClass.Properties.IndexOf("Gender")] as DataPropertyDefinition;
            //Should have constraint removed
            Assert.IsNull(gender2.ValueConstraint);
        }
Beispiel #45
0
        /// <summary>
        /// Clones a given property definition
        /// </summary>
        /// <param name="pd"></param>
        /// <returns></returns>
        public static PropertyDefinition CloneProperty(PropertyDefinition pd)
        {
            PropertyDefinition propDef = null;
            switch (pd.PropertyType)
            {
                case PropertyType.PropertyType_DataProperty:
                    {
                        DataPropertyDefinition srcData = pd as DataPropertyDefinition;
                        DataPropertyDefinition dataDef = new DataPropertyDefinition(srcData.Name, srcData.Description);
                        dataDef.DataType = srcData.DataType;
                        dataDef.DefaultValue = srcData.DefaultValue;
                        dataDef.IsAutoGenerated = srcData.IsAutoGenerated;
                        dataDef.IsSystem = srcData.IsSystem;
                        dataDef.Length = srcData.Length;
                        dataDef.Nullable = srcData.Nullable;
                        dataDef.Precision = srcData.Precision;
                        dataDef.ReadOnly = srcData.ReadOnly;
                        //Copy constraints
                        if (srcData.ValueConstraint != null)
                        {
                            if (srcData.ValueConstraint.ConstraintType == PropertyValueConstraintType.PropertyValueConstraintType_Range)
                            {
                                PropertyValueConstraintRange range = (PropertyValueConstraintRange)srcData.ValueConstraint;
                                PropertyValueConstraintRange constraint = new PropertyValueConstraintRange(range.MinValue, range.MaxValue);
                                constraint.MaxInclusive = range.MaxInclusive;
                                constraint.MinInclusive = range.MinInclusive;
                                dataDef.ValueConstraint = constraint;
                            }
                            else if (srcData.ValueConstraint.ConstraintType == PropertyValueConstraintType.PropertyValueConstraintType_List)
                            {
                                PropertyValueConstraintList list = (PropertyValueConstraintList)srcData.ValueConstraint;
                                PropertyValueConstraintList constraint = new PropertyValueConstraintList();
                                foreach (DataValue dval in list.ConstraintList)
                                {
                                    constraint.ConstraintList.Add(dval);
                                }
                                dataDef.ValueConstraint = constraint;
                            }
                        }
                        CopyPropertyAttributes(srcData, dataDef);
                        propDef = dataDef;
                    }
                    break;
                case PropertyType.PropertyType_GeometricProperty:
                    {
                        GeometricPropertyDefinition srcData = pd as GeometricPropertyDefinition;
                        GeometricPropertyDefinition geomDef = new GeometricPropertyDefinition(srcData.Name, srcData.Description);
                        geomDef.GeometryTypes = srcData.GeometryTypes;
                        geomDef.HasElevation = srcData.HasElevation;
                        geomDef.HasMeasure = srcData.HasMeasure;
                        geomDef.IsSystem = srcData.IsSystem;
                        geomDef.ReadOnly = srcData.ReadOnly;
                        geomDef.SpatialContextAssociation = srcData.SpatialContextAssociation;
                        CopyPropertyAttributes(srcData, geomDef);
                        propDef = geomDef;
                    }
                    break;
                case PropertyType.PropertyType_RasterProperty:
                    {
                        RasterPropertyDefinition srcData = pd as RasterPropertyDefinition;
                        RasterPropertyDefinition rastDef = new RasterPropertyDefinition(srcData.Name, srcData.Description);
                        if (srcData.DefaultDataModel != null)
                        {
                            rastDef.DefaultDataModel = new OSGeo.FDO.Raster.RasterDataModel();
                            rastDef.DefaultDataModel.BitsPerPixel = srcData.DefaultDataModel.BitsPerPixel;
                            rastDef.DefaultDataModel.DataModelType = srcData.DefaultDataModel.DataModelType;
                            rastDef.DefaultDataModel.DataType = srcData.DefaultDataModel.DataType;
                            rastDef.DefaultDataModel.Organization = srcData.DefaultDataModel.Organization;
                            rastDef.DefaultDataModel.TileSizeX = srcData.DefaultDataModel.TileSizeX;
                            rastDef.DefaultDataModel.TileSizeY = srcData.DefaultDataModel.TileSizeY;
                        }
                        rastDef.DefaultImageXSize = srcData.DefaultImageXSize;
                        rastDef.DefaultImageYSize = srcData.DefaultImageYSize;
                        rastDef.IsSystem = srcData.IsSystem;
                        rastDef.Nullable = srcData.Nullable;
                        rastDef.ReadOnly = srcData.ReadOnly;
                        rastDef.SpatialContextAssociation = srcData.SpatialContextAssociation;
                        CopyPropertyAttributes(srcData, rastDef);
                        propDef = rastDef;
                    }
                    break;
                case PropertyType.PropertyType_AssociationProperty:
                    throw new UnsupportedException(Res.GetString("ERR_UNSUPPORTED_CLONE_ASSOCIATION"));
                case PropertyType.PropertyType_ObjectProperty:
                    throw new UnsupportedException(Res.GetString("ERR_UNSUPPORTED_CLONE_OBJECT"));

            }
            return propDef;
        }
Beispiel #46
0
        internal static PropertyDefinition CreatePropertyFromExpressionType(string exprText, ClassDefinition clsDef, FunctionDefinitionCollection functionDefs, string defaultSpatialContextName)
        {
            string name = string.Empty;
            using (var expr = Expression.Parse(exprText))
            {
                var et = expr.GetType();
                if (typeof(ComputedIdentifier).IsAssignableFrom(et))
                {
                    var subExpr = ((ComputedIdentifier)expr).Expression;
                    return CreatePropertyFromExpressionType(subExpr.ToString(), clsDef, functionDefs, defaultSpatialContextName);
                }
                else if (typeof(Identifier).IsAssignableFrom(et))
                {
                    var id = (Identifier)expr;
                    return CloneProperty(clsDef.Properties[id.Name]);
                }
                else if (typeof(Function).IsAssignableFrom(et))
                {
                    var func = (Function)expr;
                    if (functionDefs != null)
                    {
                        var fidx = functionDefs.IndexOf(func.Name);
                        if (fidx >= 0)
                        {
                            var funcDef = functionDefs[fidx];
                            switch (funcDef.ReturnPropertyType)
                            {
                                case PropertyType.PropertyType_DataProperty:
                                    {
                                        var dp = new DataPropertyDefinition(name, "");
                                        dp.DataType = funcDef.ReturnType;
                                        dp.Nullable = true;
                                        if (dp.DataType == DataType.DataType_String)
                                            dp.Length = 255;

                                        return dp;
                                    }
                                    break;
                                case PropertyType.PropertyType_GeometricProperty:
                                    {
                                        var geom = new GeometricPropertyDefinition(name, "");
                                        geom.SpatialContextAssociation = defaultSpatialContextName;
                                        geom.GeometryTypes = (int)GeometricType.GeometricType_All;

                                        return geom;
                                    }
                                    break;

                            }
                        }
                    }
                }
                else if (typeof(BinaryExpression).IsAssignableFrom(et))
                {
                    var dp = new DataPropertyDefinition(name, "");
                    dp.DataType = DataType.DataType_Boolean;
                    dp.Nullable = true;

                    return dp;
                }
                else if (typeof(DataValue).IsAssignableFrom(et))
                {
                    var dv = (DataValue)expr;
                    var dp = new DataPropertyDefinition(name, "");
                    dp.DataType = dv.DataType;
                    if (dp.DataType == DataType.DataType_String)
                        dp.Length = 255;

                    dp.Nullable = true;
                    return dp;
                }
                else if (typeof(GeometryValue).IsAssignableFrom(et))
                {
                    var geom = new GeometricPropertyDefinition(name, "");
                    geom.GeometryTypes = (int)GeometricType.GeometricType_All;

                    return geom;
                }
            }
            return null;
        }
        public void TestAlterSchemaPassIdentityType()
        {
            MockRepository mocks = new MockRepository();
            IConnection conn = mocks.DynamicMock<IConnection>();
            ISchemaCapabilities caps = mocks.DynamicMock<ISchemaCapabilities>();

            using (mocks.Record())
            {
                SetupResult.For(conn.ConnectionState).Return(ConnectionState.ConnectionState_Open);
                SetupResult.For(conn.SchemaCapabilities).Return(caps);
                SetupResult.For(caps.ClassTypes).Return((ClassType[])Enum.GetValues(typeof(ClassType)));
                SetupResult.For(caps.DataTypes).Return((DataType[])Enum.GetValues(typeof(DataType)));
                SetupResult.For(caps.MaximumDecimalPrecision).Return(20);
                SetupResult.For(caps.MaximumDecimalScale).Return(20);
                SetupResult.For(caps.ReservedCharactersForName).Return(string.Empty);
                SetupResult.For(caps.SupportedAutoGeneratedTypes).Return(new DataType[] { DataType.DataType_Int64 });
                //--
                SetupResult.For(caps.SupportedIdentityPropertyTypes).Return(new DataType[] { DataType.DataType_Int32, DataType.DataType_Int64, DataType.DataType_String });
                //--
                SetupResult.For(caps.SupportsAssociationProperties).Return(false);
                SetupResult.For(caps.SupportsAutoIdGeneration).Return(true);
                SetupResult.For(caps.SupportsCompositeId).Return(false);
                SetupResult.For(caps.SupportsCompositeUniqueValueConstraints).Return(false);
                SetupResult.For(caps.SupportsDataStoreScopeUniqueIdGeneration).Return(false);
                SetupResult.For(caps.SupportsDefaultValue).Return(true);
                SetupResult.For(caps.SupportsExclusiveValueRangeConstraints).Return(false);
                SetupResult.For(caps.SupportsInclusiveValueRangeConstraints).Return(false);
                SetupResult.For(caps.SupportsMultipleSchemas).Return(false);
                SetupResult.For(caps.SupportsNetworkModel).Return(false);
                SetupResult.For(caps.SupportsNullValueConstraints).Return(true);
                SetupResult.For(caps.SupportsObjectProperties).Return(false);
                SetupResult.For(caps.SupportsSchemaModification).Return(true);
                SetupResult.For(caps.SupportsSchemaOverrides).Return(false);
                SetupResult.For(caps.SupportsUniqueValueConstraints).Return(false);
                SetupResult.For(caps.SupportsValueConstraintsList).Return(false);

                SetupResult.For(caps.SupportsInheritance).Return(false);
            }
            FdoFeatureService service = mocks.StrictMock<FdoFeatureService>(conn);
            mocks.ReplayAll();

            FeatureSchema schema = new FeatureSchema("Default", "");

            ClassDefinition cls = new Class("Test", "");

            //ID - float
            DataPropertyDefinition id = new DataPropertyDefinition("ID", "");
            id.DataType = DataType.DataType_Single;
            id.Nullable = false;

            cls.Properties.Add(id);
            cls.IdentityProperties.Add(id);

            //Name
            DataPropertyDefinition name = new DataPropertyDefinition("Name", "");
            name.DataType = DataType.DataType_String;
            name.Nullable = true;
            name.Length = 100;

            cls.Properties.Add(name);

            schema.Classes.Add(cls);

            IncompatibleSchema incSchema = null;
            bool canApply = service.CanApplySchema(schema, out incSchema);
            Assert.IsFalse(canApply);
            Assert.IsNotNull(incSchema);

            FeatureSchema newSchema = service.AlterSchema(schema, incSchema);

            ClassDefinition newClass = newSchema.Classes[0];

            //Should have been "promoted" to string
            Assert.AreEqual(DataType.DataType_String, newClass.IdentityProperties[0].DataType);
        }
            public override IEnumerable <FdoRow> Execute(IEnumerable <FdoRow> rows)
            {
                if (_counter < 1) //Shouldn't be reentrant, but just play it safe.
                {
                    /*
                     * Check and apply the following rules for all geometry properties to be created
                     *
                     * Target supports multiple spatial contexts:
                     * -------------------------------------------
                     * If there is no spatial contexts of the specified (source) name. Create a copy of the source spatial context.
                     * If there is a spatial context of the same name, using the same WKT. Do nothing
                     * If there is a spatial context of the same name, but using a different WKT. Create a new spatial context using the source WKT, but use a different name.
                     *
                     * Target only supports one spatial context:
                     * If there is no spatial context already. Create a copy of the source spatial context.
                     * If there is a spatial context of the same WKT. Change the association to match the name of this spatial context.
                     * If there is a spatial context not using the source WKT. Change the association to match the name of this spatial context. This may not be ideal, but there is no other option at this point.
                     *
                     * The regular schema compatibility fixes will handle the other properties
                     */
                    bool targetSupportsMultipleSpatialContexts      = _target.Capability.GetBooleanCapability(CapabilityType.FdoCapabilityType_SupportsMultipleSpatialContexts);
                    List <SpatialContextInfo> targetSpatialContexts = null;
                    List <SpatialContextInfo> sourceSpatialContexts = null;

                    if (typeof(CreateTargetClassFromSource).IsAssignableFrom(_opts.PreCopyTargetModifier.GetType()))
                    {
                        using (var tsvc = _target.CreateFeatureService())
                            using (var ssvc = _source.CreateFeatureService())
                            {
                                targetSpatialContexts = new List <SpatialContextInfo>(tsvc.GetSpatialContexts());
                                sourceSpatialContexts = new List <SpatialContextInfo>(ssvc.GetSpatialContexts());
                                var ct = (CreateTargetClassFromSource)_opts.PreCopyTargetModifier;

                                Info("Getting current schema from target");
                                var schema = tsvc.GetSchemaByName(_opts.TargetSchema);
                                if (schema.Classes.IndexOf(ct.Name) >= 0)
                                {
                                    Info("Class " + _opts.TargetSchema + ":" + ct.Name + " already exists. Nothing to do here");
                                }
                                else
                                {
                                    List <SpatialContextInfo> createScs = new List <SpatialContextInfo>();

                                    var cls = ssvc.GetClassByName(ct.Schema, ct.Name);
                                    Info("Creating a cloned copy of source class " + ct.Schema + ":" + ct.Name);

                                    var cloned     = FdoSchemaUtil.CloneClass(cls);
                                    var propList   = new List <string>(_opts.CheckSourceProperties);
                                    var removeList = new List <string>();
                                    foreach (PropertyDefinition prop in cloned.Properties)
                                    {
                                        string propName = prop.Name;
                                        if (!propList.Contains(propName))
                                        {
                                            removeList.Add(propName);
                                        }
                                    }

                                    if (removeList.Count > 0)
                                    {
                                        Info("Removing " + removeList.Count + " unused properties from cloned class");
                                        var props = cloned.Properties;
                                        var ids   = cloned.IdentityProperties;
                                        foreach (var name in removeList)
                                        {
                                            if (ids.Contains(name))
                                            {
                                                ids.RemoveAt(ids.IndexOf(name));
                                            }

                                            if (props.Contains(name))
                                            {
                                                props.RemoveAt(props.IndexOf(name));
                                            }
                                        }
                                        Info(removeList.Count + " unused properties removed");
                                    }

                                    foreach (var prop in ct.PropertiesToCreate)
                                    {
                                        Info("Adding property to cloned class: " + prop.Name);
                                        PropertyDefinition clonedProp = FdoSchemaUtil.CloneProperty(prop);
                                        cloned.Properties.Add(clonedProp);
                                    }

                                    //Add an auto-generated identity property if none exist
                                    if (cloned.IdentityProperties.Count == 0)
                                    {
                                        var id = new DataPropertyDefinition("FID", "Auto-Generated Feature Id");
                                        id.IsAutoGenerated = true;
                                        id.Nullable        = false;
                                        //This may not be valid for target connection, but FdoFeatureService
                                        //will fix this for us.
                                        id.DataType = DataType.DataType_Int32;

                                        cloned.Properties.Add(id);
                                        cloned.IdentityProperties.Add(id);

                                        Info("Adding an auto-generated id (FID) to this cloned class");
                                    }

                                    Info("Checking this class for incompatibilities");
                                    IncompatibleClass ic;
                                    if (!tsvc.CanApplyClass(cloned, out ic))
                                    {
                                        Info("Altering this class to become compatible with target connection");
                                        cloned = tsvc.AlterClassDefinition(cloned, ic);
                                        Info("Class successfully altered");
                                    }

                                    Info("Checking if any spatial contexts need to be created and/or references modified");
                                    foreach (PropertyDefinition pd in cloned.Properties)
                                    {
                                        if (pd.PropertyType == PropertyType.PropertyType_GeometricProperty)
                                        {
                                            AddSpatialContextsToCreate(targetSupportsMultipleSpatialContexts, targetSpatialContexts, sourceSpatialContexts, createScs, (GeometricPropertyDefinition)pd);
                                        }
                                    }

                                    //We have to create spatial contexts first before applying the schema
                                    if (createScs.Count > 0)
                                    {
                                        //The ones we create should be unique so no overwriting needed
                                        ExpressUtility.CopyAllSpatialContexts(createScs, _target, false);

                                        foreach (var sc in createScs)
                                        {
                                            Info("Created spatial context: " + sc.Name);
                                        }
                                    }

                                    Info("Adding cloned class to target schema");
                                    schema.Classes.Add(cloned);
                                    Info("Applying schema back to target connection");
                                    tsvc.ApplySchema(schema);
                                    Info("Updated schema applied to target connection");
                                }
                            }
                    }
                    else if (typeof(UpdateTargetClass).IsAssignableFrom(_opts.PreCopyTargetModifier.GetType()))
                    {
                        var ut = (UpdateTargetClass)_opts.PreCopyTargetModifier;
                        using (var tsvc = _target.CreateFeatureService())
                            using (var ssvc = _source.CreateFeatureService())
                            {
                                targetSpatialContexts = new List <SpatialContextInfo>(tsvc.GetSpatialContexts());
                                sourceSpatialContexts = new List <SpatialContextInfo>(ssvc.GetSpatialContexts());
                                var schema = tsvc.GetSchemaByName(_opts.TargetSchema);
                                var cidx   = schema.Classes.IndexOf(ut.Name);
                                if (cidx < 0)
                                {
                                    throw new InvalidOperationException("Target class to be updated " + _opts.TargetSchema + ":" + ut.Name + " not found");
                                }
                                else
                                {
                                    List <SpatialContextInfo> createScs = new List <SpatialContextInfo>();

                                    var cls = schema.Classes[cidx];
                                    foreach (var prop in ut.PropertiesToCreate)
                                    {
                                        if (cls.Properties.IndexOf(prop.Name) < 0)
                                        {
                                            Info("Adding property to class: " + prop.Name);
                                            var clonedProp = FdoSchemaUtil.CloneProperty(prop);
                                            if (clonedProp.PropertyType == PropertyType.PropertyType_GeometricProperty)
                                            {
                                                AddSpatialContextsToCreate(targetSupportsMultipleSpatialContexts, targetSpatialContexts, sourceSpatialContexts, createScs, (GeometricPropertyDefinition)clonedProp);
                                            }
                                            cls.Properties.Add(clonedProp);
                                        }
                                        else
                                        {
                                            Info("Skipping property " + prop.Name + " because it already exists");
                                        }
                                    }

                                    //We have to create spatial contexts first before applying the schema
                                    if (createScs.Count > 0)
                                    {
                                        //The ones we create should be unique so no overwriting needed
                                        ExpressUtility.CopyAllSpatialContexts(createScs, _target, false);

                                        foreach (var sc in createScs)
                                        {
                                            Info("Created spatial context: " + sc.Name);
                                        }
                                    }

                                    Info("Applying modified schema " + schema.Name + " to target connection");
                                    tsvc.ApplySchema(schema);
                                    Info("Modified schema " + schema.Name + " applied to target connection");
                                }
                            }
                    }

                    _counter++;
                }
                return(rows);
            }
            public override IEnumerable<FdoRow> Execute(IEnumerable<FdoRow> rows)
            {
                if (_counter < 1) //Shouldn't be reentrant, but just play it safe.
                {
                    /*
                     * Check and apply the following rules for all geometry properties to be created
                     *
                     * Target supports multiple spatial contexts:
                     * -------------------------------------------
                     * If there is no spatial contexts of the specified (source) name. Create a copy of the source spatial context.
                     * If there is a spatial context of the same name, using the same WKT. Do nothing
                     * If there is a spatial context of the same name, but using a different WKT. Create a new spatial context using the source WKT, but use a different name.
                     *
                     * Target only supports one spatial context:
                     * If there is no spatial context already. Create a copy of the source spatial context.
                     * If there is a spatial context of the same WKT. Change the association to match the name of this spatial context.
                     * If there is a spatial context not using the source WKT. Change the association to match the name of this spatial context. This may not be ideal, but there is no other option at this point.
                     *
                     * The regular schema compatibility fixes will handle the other properties
                     */
                    bool targetSupportsMultipleSpatialContexts = _target.Capability.GetBooleanCapability(CapabilityType.FdoCapabilityType_SupportsMultipleSpatialContexts);
                    List<SpatialContextInfo> targetSpatialContexts = null;
                    List<SpatialContextInfo> sourceSpatialContexts = null;

                    if (typeof(CreateTargetClassFromSource).IsAssignableFrom(_opts.PreCopyTargetModifier.GetType()))
                    {
                        using (var tsvc = _target.CreateFeatureService())
                        using (var ssvc = _source.CreateFeatureService())
                        {
                            targetSpatialContexts = new List<SpatialContextInfo>(tsvc.GetSpatialContexts());
                            sourceSpatialContexts = new List<SpatialContextInfo>(ssvc.GetSpatialContexts());
                            var ct = (CreateTargetClassFromSource)_opts.PreCopyTargetModifier;

                            Info("Getting current schema from target");
                            var schema = tsvc.GetSchemaByName(_opts.TargetSchema);
                            if (schema.Classes.IndexOf(ct.Name) >= 0)
                            {
                                Info("Class " + _opts.TargetSchema + ":" + ct.Name + " already exists. Nothing to do here");
                            }
                            else
                            {
                                List<SpatialContextInfo> createScs = new List<SpatialContextInfo>();

                                var cls = ssvc.GetClassByName(ct.Schema, ct.Name);
                                Info("Creating a cloned copy of source class " + ct.Schema + ":" + ct.Name);

                                var cloned = FdoSchemaUtil.CloneClass(cls);
                                var propList = new List<string>(_opts.CheckSourceProperties);
                                var removeList = new List<string>();
                                foreach (PropertyDefinition prop in cloned.Properties)
                                {
                                    string propName = prop.Name;
                                    if (!propList.Contains(propName))
                                    {
                                        removeList.Add(propName);
                                    }
                                }

                                if (removeList.Count > 0)
                                {
                                    Info("Removing " + removeList.Count + " unused properties from cloned class");
                                    var props = cloned.Properties;
                                    var ids = cloned.IdentityProperties;
                                    foreach (var name in removeList)
                                    {
                                        if (ids.Contains(name))
                                            ids.RemoveAt(ids.IndexOf(name));

                                        if (props.Contains(name))
                                            props.RemoveAt(props.IndexOf(name));
                                    }
                                    Info(removeList.Count + " unused properties removed");
                                }

                                foreach (var prop in ct.PropertiesToCreate)
                                {
                                    Info("Adding property to cloned class: " + prop.Name);
                                    PropertyDefinition clonedProp = FdoSchemaUtil.CloneProperty(prop);
                                    cloned.Properties.Add(clonedProp);
                                }

                                //Add an auto-generated identity property if none exist
                                if (cloned.IdentityProperties.Count == 0)
                                {
                                    var id = new DataPropertyDefinition("FID", "Auto-Generated Feature Id");
                                    id.IsAutoGenerated = true;
                                    id.Nullable = false;
                                    //This may not be valid for target connection, but FdoFeatureService
                                    //will fix this for us.
                                    id.DataType = DataType.DataType_Int32;

                                    cloned.Properties.Add(id);
                                    cloned.IdentityProperties.Add(id);

                                    Info("Adding an auto-generated id (FID) to this cloned class");
                                }

                                Info("Checking this class for incompatibilities");
                                IncompatibleClass ic;
                                if (!tsvc.CanApplyClass(cloned, out ic))
                                {
                                    Info("Altering this class to become compatible with target connection");
                                    cloned = tsvc.AlterClassDefinition(cloned, ic);
                                    Info("Class successfully altered");
                                }

                                Info("Checking if any spatial contexts need to be created and/or references modified");
                                foreach (PropertyDefinition pd in cloned.Properties)
                                {
                                    if (pd.PropertyType == PropertyType.PropertyType_GeometricProperty)
                                        AddSpatialContextsToCreate(targetSupportsMultipleSpatialContexts, targetSpatialContexts, sourceSpatialContexts, createScs, (GeometricPropertyDefinition)pd);
                                }

                                //We have to create spatial contexts first before applying the schema
                                if (createScs.Count > 0)
                                {
                                    //The ones we create should be unique so no overwriting needed
                                    ExpressUtility.CopyAllSpatialContexts(createScs, _target, false);

                                    foreach (var sc in createScs)
                                    {
                                        Info("Created spatial context: " + sc.Name);
                                    }
                                }

                                Info("Adding cloned class to target schema");
                                schema.Classes.Add(cloned);
                                Info("Applying schema back to target connection");
                                tsvc.ApplySchema(schema);
                                Info("Updated schema applied to target connection");
                            }
                        }
                    }
                    else if (typeof(UpdateTargetClass).IsAssignableFrom(_opts.PreCopyTargetModifier.GetType()))
                    {
                        var ut = (UpdateTargetClass)_opts.PreCopyTargetModifier;
                        using (var tsvc = _target.CreateFeatureService())
                        using (var ssvc = _source.CreateFeatureService())
                        {
                            targetSpatialContexts = new List<SpatialContextInfo>(tsvc.GetSpatialContexts());
                            sourceSpatialContexts = new List<SpatialContextInfo>(ssvc.GetSpatialContexts());
                            var schema = tsvc.GetSchemaByName(_opts.TargetSchema);
                            var cidx = schema.Classes.IndexOf(ut.Name);
                            if (cidx < 0)
                            {
                                throw new InvalidOperationException("Target class to be updated " + _opts.TargetSchema + ":" + ut.Name + " not found");
                            }
                            else
                            {
                                List<SpatialContextInfo> createScs = new List<SpatialContextInfo>();

                                var cls = schema.Classes[cidx];
                                foreach (var prop in ut.PropertiesToCreate)
                                {
                                    if (cls.Properties.IndexOf(prop.Name) < 0)
                                    {
                                        Info("Adding property to class: " + prop.Name);
                                        var clonedProp = FdoSchemaUtil.CloneProperty(prop);
                                        if (clonedProp.PropertyType == PropertyType.PropertyType_GeometricProperty)
                                        {
                                            AddSpatialContextsToCreate(targetSupportsMultipleSpatialContexts, targetSpatialContexts, sourceSpatialContexts, createScs, (GeometricPropertyDefinition)clonedProp);
                                        }
                                        cls.Properties.Add(clonedProp);
                                    }
                                    else
                                    {
                                        Info("Skipping property " + prop.Name + " because it already exists");
                                    }
                                }

                                //We have to create spatial contexts first before applying the schema
                                if (createScs.Count > 0)
                                {
                                    //The ones we create should be unique so no overwriting needed
                                    ExpressUtility.CopyAllSpatialContexts(createScs, _target, false);

                                    foreach (var sc in createScs)
                                    {
                                        Info("Created spatial context: " + sc.Name);
                                    }
                                }

                                Info("Applying modified schema " + schema.Name + " to target connection");
                                tsvc.ApplySchema(schema);
                                Info("Modified schema " + schema.Name + " applied to target connection");
                            }
                        }
                    }

                    _counter++;
                }
                return rows;
            }
        public void TestCloneProperty()
        {
            DataPropertyDefinition dp = new DataPropertyDefinition("Foo", "Bar");
            dp.DataType = DataType.DataType_String;
            dp.DefaultValue = "Whatever";
            dp.IsAutoGenerated = false;
            dp.Length = 45;
            dp.Nullable = true;
            dp.ReadOnly = false;
            PropertyValueConstraintList list = new PropertyValueConstraintList();
            list.ConstraintList.Add(new StringValue("A"));
            list.ConstraintList.Add(new StringValue("B"));
            list.ConstraintList.Add(new StringValue("C"));
            dp.ValueConstraint = list;

            DataPropertyDefinition dp2 = FdoSchemaUtil.CloneProperty(dp) as DataPropertyDefinition;
            AssertHelper.EqualProperty(dp, dp2);

            GeometricPropertyDefinition gp = new GeometricPropertyDefinition("Sna", "Fu");
            gp.GeometryTypes = (int)(GeometryType.GeometryType_LineString | GeometryType.GeometryType_MultiLineString | GeometryType.GeometryType_Polygon);
            gp.HasElevation = true;
            gp.HasMeasure = false;
            gp.ReadOnly = false;
            gp.SpatialContextAssociation = "LL84";

            GeometricPropertyDefinition gp2 = FdoSchemaUtil.CloneProperty(gp) as GeometricPropertyDefinition;
            AssertHelper.EqualProperty(gp, gp2);
        }
Beispiel #51
0
            internal void AddProperty(PropertyType type)
            {
                TreeNode node = _view.schemaTree.SelectedNode;
                if (node.Level == LEVEL_CLASS)
                {
                    if (type == PropertyType.PropertyType_AssociationProperty || type == PropertyType.PropertyType_ObjectProperty)
                    {
                        var sn = node.Parent;
                        if (sn.Nodes.Count == 1) //The selected class is the only one
                        {
                            MessageService.ShowError("No other class definitions exist in the current schema");
                            return;
                        }
                    }

                    string schema = node.Parent.Name;
                    string clsName = node.Name;
                    string prefix = "Property";

                    switch (type)
                    {
                        case PropertyType.PropertyType_AssociationProperty:
                            prefix = "AssociationProperty";
                            break;
                        case PropertyType.PropertyType_DataProperty:
                            prefix = "DataProperty";
                            break;
                        case PropertyType.PropertyType_GeometricProperty:
                            prefix = "GeometricProperty";
                            break;
                        case PropertyType.PropertyType_ObjectProperty:
                            prefix = "ObjectProperty";
                            break;
                        case PropertyType.PropertyType_RasterProperty:
                            prefix = "RasterProperty";
                            break;
                    }

                    string name = _context.GenerateName(prefix);
                    while (_context.PropertyNameExists(schema, clsName, name))
                    {
                        name = _context.GenerateName(prefix);
                    }

                    PropertyDefinition pd = null;
                    switch (type)
                    { 
                        case PropertyType.PropertyType_AssociationProperty:
                            pd = new AssociationPropertyDefinition(name, "");
                            break;
                        case PropertyType.PropertyType_DataProperty:
                            var dp = new DataPropertyDefinition(name, "");
                            if (dp.DataType == DataType.DataType_String)
                                dp.Length = 255;
                            pd = dp;
                            break;
                        case PropertyType.PropertyType_GeometricProperty:
                            pd = new GeometricPropertyDefinition(name, "");
                            break;
                        case PropertyType.PropertyType_ObjectProperty:
                            pd = new ObjectPropertyDefinition(name, "");
                            break;
                        case PropertyType.PropertyType_RasterProperty:
                            break;
                    }

                    if (pd != null)
                        _context.AddProperty(schema, clsName, pd);
                }
            }