Ejemplo n.º 1
0
        public virtual SpatialContextInfo CreateDefaultSpatialContext()
        {
            var sc = new SpatialContextInfo();

            sc.Name             = "Default";
            sc.XYTolerance      = sc.ZTolerance = this.Tolerance;
            sc.CoordinateSystem = this.CSName;
            if (_presenter.RequiresWKT)
            {
                sc.CoordinateSystemWkt = this.CSWkt;
            }

            sc.IsActive   = true;
            sc.ExtentType = this.ExtentType;
            if (sc.ExtentType == OSGeo.FDO.Commands.SpatialContext.SpatialContextExtentType.SpatialContextExtentType_Static)
            {
                string wktfmt = "POLYGON (({0} {1}, {2} {3}, {4} {5}, {6} {7}, {0} {1}))";
                double llx    = Convert.ToDouble(this.LowerLeftX);
                double lly    = Convert.ToDouble(this.LowerLeftY);
                double urx    = Convert.ToDouble(this.UpperRightX);
                double ury    = Convert.ToDouble(this.UpperRightY);
                sc.ExtentGeometryText = string.Format(wktfmt,
                                                      llx, lly,
                                                      urx, lly,
                                                      urx, ury,
                                                      llx, ury);
            }
            return(sc);
        }
Ejemplo n.º 2
0
        public static SpatialContextInfo Edit(FdoConnection conn, SpatialContextInfo ctx)
        {
            FdoSpatialContextDialog diag = new FdoSpatialContextDialog(conn, ctx);

            if (diag.ShowDialog() == DialogResult.OK)
            {
                SpatialContextInfo sci = new SpatialContextInfo();
                sci.Name                = diag.ContextName;
                sci.Description         = diag.Description;
                sci.CoordinateSystem    = diag.CoordinateSystem;
                sci.CoordinateSystemWkt = diag.CoordinateSystemWkt;
                sci.XYTolerance         = Convert.ToDouble(diag.XYTolerance);
                sci.ZTolerance          = Convert.ToDouble(diag.ZTolerance);
                sci.ExtentType          = diag.SelectedExtentType;
                //Only consider extent if all 4 values are defined
                if (diag.IsExtentDefined)
                {
                    string wktfmt = "POLYGON (({0} {1}, {2} {3}, {4} {5}, {6} {7}, {0} {1}))";
                    double llx    = Convert.ToDouble(diag.LowerLeftX);
                    double lly    = Convert.ToDouble(diag.LowerLeftY);
                    double urx    = Convert.ToDouble(diag.UpperRightX);
                    double ury    = Convert.ToDouble(diag.UpperRightY);
                    sci.ExtentGeometryText = string.Format(wktfmt,
                                                           llx, lly,
                                                           urx, lly,
                                                           urx, ury,
                                                           llx, ury,
                                                           llx, lly);
                }
                return(sci);
            }
            return(null);
        }
        public void CopySpatialContexts()
        {
            List <SpatialContextInfo> contexts   = new List <SpatialContextInfo>();
            FdoConnection             srcConn    = _connMgr.GetConnection(_view.SourceConnectionName);
            FdoConnection             targetConn = _connMgr.GetConnection(_view.SelectedTargetConnectionName);

            using (FdoFeatureService service = srcConn.CreateFeatureService())
            {
                foreach (string ctxName in _view.SpatialContexts)
                {
                    SpatialContextInfo sc = service.GetSpatialContext(ctxName);
                    if (sc != null)
                    {
                        contexts.Add(sc);
                    }
                }
            }

            if (contexts.Count == 0)
            {
                _view.ShowMessage(null, ResourceService.GetString("MSG_NO_SPATIAL_CONTEXTS_COPIED"));
                return;
            }

            ExpressUtility.CopyAllSpatialContexts(contexts, targetConn, _view.Overwrite);
            _view.ShowMessage(null, ResourceService.GetString("MSG_SPATIAL_CONTEXTS_COPIED"));
            _view.Close();
        }
Ejemplo n.º 4
0
        internal void UpdateSpatialContext(SpatialContextInfo sc)
        {
            this.SpatialContextsChanged = true;
            SpatialContextInfo edit = null;

            foreach (var context in _spatialContexts)
            {
                if (context.Name == sc.Name)
                {
                    edit = context;
                }
            }

            if (edit != null)
            {
                edit.CoordinateSystem    = sc.CoordinateSystem;
                edit.CoordinateSystemWkt = sc.CoordinateSystemWkt;
                edit.Description         = sc.Description;
                edit.ExtentGeometryText  = sc.ExtentGeometryText;
                edit.ExtentType          = sc.ExtentType;
                edit.XYTolerance         = sc.XYTolerance;
                edit.ZTolerance          = sc.ZTolerance;
            }
            else
            {
                _spatialContexts.Add(sc);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Copies all spatial contexts
        /// </summary>
        /// <param name="spatialContexts">The spatial contexts.</param>
        /// <param name="target">The target.</param>
        /// <param name="overwrite">if set to <c>true</c> [overwrite].</param>
        public virtual void Execute(ICollection <SpatialContextInfo> spatialContexts, FdoConnection target, bool overwrite)
        {
            bool supportsMultipleScs = target.Capability.GetBooleanCapability(CapabilityType.FdoCapabilityType_SupportsMultipleSpatialContexts);
            bool supportsDestroySc   = target.Capability.HasArrayCapability(CapabilityType.FdoCapabilityType_CommandList, (int)OSGeo.FDO.Commands.CommandType.CommandType_DestroySpatialContext);

            using (FdoFeatureService service = target.CreateFeatureService())
            {
                if (supportsMultipleScs)
                {
                    if (overwrite && supportsDestroySc)
                    {
                        ReadOnlyCollection <SpatialContextInfo> targetContexts = service.GetSpatialContexts();

                        foreach (SpatialContextInfo sc in spatialContexts)
                        {
                            //Only destroy spatial context if it exists in target connection
                            if (SpatialContextExists(targetContexts, sc))
                            {
                                service.DestroySpatialContext(sc);
                            }
                        }
                    }
                    foreach (SpatialContextInfo sc in spatialContexts)
                    {
                        service.CreateSpatialContext(sc, overwrite);
                    }
                }
                else
                {
                    List <SpatialContextInfo> contexts = new List <SpatialContextInfo>(spatialContexts);
                    //Copy either the active spatial context in the list or the first
                    //spatial context (if no active one is found)
                    SpatialContextInfo active = null;
                    if (contexts.Count > 0)
                    {
                        foreach (SpatialContextInfo sc in contexts)
                        {
                            if (sc.IsActive)
                            {
                                active = sc;
                                break;
                            }
                        }
                        if (active == null)
                        {
                            active = contexts[0];
                        }
                    }
                    if (active != null)
                    {
                        service.CreateSpatialContext(active, overwrite);
                    }
                }
            }
        }
Ejemplo n.º 6
0
        public double?GetXYTolerance()
        {
            SpatialContextInfo ctx = _data.ActiveSpatialContext;

            if (ctx != null)
            {
                return(ctx.XYTolerance);
            }

            return(null);
        }
 public void SetSpatialContext(SpatialContextInfo sci)
 {
     _view.NameEnabled         = false;
     _view.ContextName         = sci.Name;
     _view.CoordinateSystem    = sci.CoordinateSystem;
     _view.CoordinateSystemWkt = sci.CoordinateSystemWkt;
     _view.Description         = sci.Description;
     if (!string.IsNullOrEmpty(sci.ExtentGeometryText))
     {
         using (FdoFeatureService service = _conn.CreateFeatureService())
         {
             using (IGeometry geom = service.GeometryFactory.CreateGeometry(sci.ExtentGeometryText))
             {
                 _view.LowerLeftX  = geom.Envelope.MinX.ToString();
                 _view.UpperRightX = geom.Envelope.MaxX.ToString();
                 _view.LowerLeftY  = geom.Envelope.MinY.ToString();
                 _view.UpperRightY = geom.Envelope.MaxY.ToString();
             }
         }
     }
     _view.XYTolerance = sci.XYTolerance.ToString();
     _view.ZTolerance  = sci.ZTolerance.ToString();
 }
        /// <summary>
        /// Copies the spatial contexts given in the list
        /// </summary>
        /// <param name="source">The source connection</param>
        /// <param name="target">The target connection</param>
        /// <param name="overwrite">If true will overwrite any existing spatial contexts</param>
        /// <param name="spatialContextNames">The list of spatial contexts to copy</param>
        public override void Execute(FdoConnection source, FdoConnection target, bool overwrite, string[] spatialContextNames)
        {
            if (spatialContextNames.Length == 0)
            {
                return;
            }

            FdoFeatureService srcService  = source.CreateFeatureService();
            FdoFeatureService destService = target.CreateFeatureService();
            ReadOnlyCollection <SpatialContextInfo> srcContexts  = srcService.GetSpatialContexts();
            ReadOnlyCollection <SpatialContextInfo> destContexts = destService.GetSpatialContexts();

            foreach (SpatialContextInfo ctx in srcContexts)
            {
                if (SpatialContextInSpecifiedList(ctx, spatialContextNames))
                {
                    try
                    {
                        //Find target spatial context of the same name
                        SpatialContextInfo sci = destService.GetSpatialContext(ctx.Name);
                        if (sci != null && overwrite)
                        {
                            //If found, destroy then create
                            destService.DestroySpatialContext(ctx.Name);
                            destService.CreateSpatialContext(ctx, false);
                        }
                        else
                        {
                            destService.CreateSpatialContext(ctx, false);
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }
        /// <summary>
        /// Copies the spatial contexts given in the list
        /// </summary>
        /// <param name="source">The source connection</param>
        /// <param name="target">The target connection</param>
        /// <param name="overwrite">If true will overwrite any existing spatial contexts</param>
        /// <param name="spatialContextNames">The list of spatial contexts to copy</param>
        public override void Execute(FdoConnection source, FdoConnection target, bool overwrite, string [] spatialContextNames)
        {
            if (spatialContextNames.Length == 0)
            {
                return;
            }

            string             srcName     = spatialContextNames[0];
            FdoFeatureService  srcService  = source.CreateFeatureService();
            FdoFeatureService  destService = target.CreateFeatureService();
            SpatialContextInfo context     = srcService.GetSpatialContext(srcName);

            if (context != null)
            {
                //Make sure that CSName != Spatial Context Name
                WKTParser parser = new WKTParser(context.CoordinateSystemWkt);
                if (!string.IsNullOrEmpty(parser.CSName))
                {
                    context.CoordinateSystem = parser.CSName;
                    context.Name             = parser.CSName;
                    destService.CreateSpatialContext(context, overwrite);
                }
            }
        }
Ejemplo n.º 10
0
 internal void RemoveSpatialContext(SpatialContextInfo sc)
 {
     _spatialContexts.Remove(sc);
     this.SpatialContextsChanged = true;
 }
Ejemplo n.º 11
0
            private void AddSpatialContextsToCreate(bool targetSupportsMultipleSpatialContexts, List <SpatialContextInfo> targetSpatialContexts, List <SpatialContextInfo> sourceSpatialContexts, List <SpatialContextInfo> createScs, GeometricPropertyDefinition geom)
            {
                if (targetSupportsMultipleSpatialContexts)
                {
                    // NOTE:
                    //
                    // There's a defect in the PostgreSQL provider regarding spatial context creation.
                    //  - WKT is disregarded
                    //  - Extents are disregarded when creating
                    //
                    // What this means is that when the PostgreSQL provider is the target connection, multiple
                    // copies of the same spatial context will be created because the WKT comparison check will fail
                    // because of the above point.

                    if (!string.IsNullOrEmpty(geom.SpatialContextAssociation))
                    {
                        //See if the source spatial context has a matching target (by name)
                        SpatialContextInfo matchingTargetSc = FindMatchingSpatialContextByName(targetSpatialContexts, geom.SpatialContextAssociation);
                        if (matchingTargetSc == null)
                        {
                            //The source spatial context name doesn't exist in target
                            //We are free to create a copy of the source one as target supports multiple SCs
                            SpatialContextInfo sourceSc = FindMatchingSpatialContextByName(sourceSpatialContexts, geom.SpatialContextAssociation);
                            if (sourceSc != null)
                            {
                                Info("Adding source spatial context (" + sourceSc.Name + ") to list to be copied to target");
                                var sc = sourceSc.Clone();
                                //Add to list of ones to create
                                createScs.Add(sc);
                                //So that subsequent travels along this code path take into account
                                //spatial context we will create as well
                                targetSpatialContexts.Add(sc);
                            }
                            else
                            {
                                /* UNCOMMON CODE PATH. WE'RE WORKING WITH SOME MESSED UP DATA IF WE GET HERE */

                                //We have a source geom property with an invalid spatial context association reference
                                //So which SC should we assign?

                                SpatialContextInfo sc = null;
                                if (targetSpatialContexts.Count > 0)
                                {
                                    //Try first active SC on target
                                    sc = FindFirstActiveSpatialContext(targetSpatialContexts);
                                    //Otherwise first one on target
                                    if (sc == null)
                                    {
                                        sc = targetSpatialContexts[0];
                                    }

                                    if (sc != null)
                                    {
                                        //Update reference only. No need to create
                                        geom.SpatialContextAssociation = sc.Name;
                                        return;
                                    }
                                }
                                if (sourceSpatialContexts.Count > 0)
                                {
                                    //Try first active SC on source
                                    sc = FindFirstActiveSpatialContext(sourceSpatialContexts);
                                    //Otherwise first one on target
                                    if (sc == null)
                                    {
                                        sc = sourceSpatialContexts[0];
                                    }

                                    //Still nothing????
                                    if (sc == null)
                                    {
                                        throw new Exception("Could not find a suitable replacement spatial context for geometry property" + geom.Name);
                                    }

                                    sc = sc.Clone();
                                    //
                                    string prefix = "SC" + geom.Name;
                                    string name   = prefix;
                                    while (SpatialContextExistsByName(targetSpatialContexts, name))
                                    {
                                        _counter++;
                                        name = prefix + _counter;
                                    }
                                    sc.Name = name;
                                    //Add to list of ones to create
                                    createScs.Add(sc);
                                    //So that subsequent travels along this code path take into account
                                    //spatial context we will create as well
                                    targetSpatialContexts.Add(sc);
                                    //Update reference to point to this sc we will create
                                    geom.SpatialContextAssociation = sc.Name;
                                }
                            }
                        }
                        else //There is a matching target spatial context of the same name
                        {
                            //Compare target spatial context with source spatial context
                            SpatialContextInfo sourceSc = FindMatchingSpatialContextByName(sourceSpatialContexts, geom.SpatialContextAssociation);
                            if (sourceSc != null)
                            {
                                //Compare WKTs
                                if (!sourceSc.CoordinateSystemWkt.Equals(matchingTargetSc.CoordinateSystemWkt))
                                {
                                    //WKTs do not match. Create a clone of the source but with a different name
                                    var sc = sourceSc.Clone();
                                    //
                                    string prefix = "SC" + geom.SpatialContextAssociation;
                                    string name   = prefix;
                                    while (SpatialContextExistsByName(targetSpatialContexts, name))
                                    {
                                        _counter++;
                                        name = prefix + _counter;
                                    }
                                    sc.Name = name;
                                    //Add to list of ones to create
                                    createScs.Add(sc);
                                    //So that subsequent travels along this code path take into account
                                    //spatial context we will create as well
                                    targetSpatialContexts.Add(sc);
                                    //Update reference to point to this sc we will create
                                    geom.SpatialContextAssociation = sc.Name;
                                }
                                //Otherwise matches both in name and WKT. Nothing needs to be done
                            }
                            else //No source spatial context to compare with
                            {
                                /* UNCOMMON CODE PATH. WE'RE WORKING WITH SOME MESSED UP DATA IF WE GET HERE */

                                //We have a source geom property with an invalid spatial context association reference
                                //So which SC should we assign?

                                geom.SpatialContextAssociation = matchingTargetSc.Name;
                            }
                        }
                    }
                    else
                    {
                        /* UNCOMMON CODE PATH. WE'RE WORKING WITH SOME MESSED UP DATA IF WE GET HERE */

                        //No spatial context association found on the cloned geometry property we created
                        //Which SC should we assign?

                        SpatialContextInfo sc = null;
                        if (targetSpatialContexts.Count > 0)
                        {
                            //Try first active SC on target
                            sc = FindFirstActiveSpatialContext(targetSpatialContexts);
                            //Otherwise first one on target
                            if (sc == null)
                            {
                                sc = targetSpatialContexts[0];
                            }

                            //Still nothing????
                            if (sc != null)
                            {
                                //Update reference only. No need to create
                                geom.SpatialContextAssociation = sc.Name;
                                return;
                            }
                        }

                        if (sourceSpatialContexts.Count > 0)
                        {
                            //Try first active SC on source
                            sc = FindFirstActiveSpatialContext(sourceSpatialContexts);
                            //Otherwise first one on target
                            if (sc == null)
                            {
                                sc = sourceSpatialContexts[0];
                            }

                            //Still nothing????
                            if (sc == null)
                            {
                                throw new Exception("Could not find a suitable replacement spatial context for geometry property" + geom.Name);
                            }

                            sc = sc.Clone();
                            //
                            string prefix = "SC" + geom.Name;
                            string name   = prefix;
                            int    scc    = 0;
                            while (SpatialContextExistsByName(targetSpatialContexts, name))
                            {
                                _counter++;
                                name = prefix + scc;
                            }
                            sc.Name = name;
                            //Add to list of ones to create
                            createScs.Add(sc);
                            //So that subsequent travels along this code path take into account
                            //spatial context we will create as well
                            targetSpatialContexts.Add(sc);
                            //Update reference to point to this sc we will create
                            geom.SpatialContextAssociation = sc.Name;
                        }
                    }
                }
                else //Only supports one spatial context
                {
                    System.Diagnostics.Debug.Assert(targetSpatialContexts.Count <= 1);
                    if (targetSpatialContexts.Count == 1)
                    {
                        //Coerce to the target spatial context. We can't do anything else
                        geom.SpatialContextAssociation = targetSpatialContexts[0].Name;
                    }
                    else
                    {
                        //We can create one, but only one!
                        SpatialContextInfo sourceSc = FindMatchingSpatialContextByName(sourceSpatialContexts, geom.SpatialContextAssociation);
                        if (sourceSc != null)
                        {
                            //You're it!
                            var sc = sourceSc.Clone();
                            createScs.Add(sc);
                            geom.SpatialContextAssociation = sc.Name;
                        }
                        else
                        {
                            /* UNCOMMON CODE PATH. WE'RE WORKING WITH SOME MESSED UP DATA IF WE GET HERE */

                            //No spatial contexts on target and the source reference points to
                            //nowhere! Now what?
                            if (sourceSpatialContexts.Count == 0)
                            {
                                throw new Exception("Could not find source spatial context with name " + geom.SpatialContextAssociation + " and target has no spatial context");
                            }

                            //Try first active source spatial context
                            sourceSc = FindFirstActiveSpatialContext(sourceSpatialContexts);

                            //Last resort. First known source spatial context
                            if (sourceSc == null)
                            {
                                sourceSc = sourceSpatialContexts[0];
                            }

                            var sc = sourceSc.Clone();
                            createScs.Add(sc);
                            geom.SpatialContextAssociation = sc.Name;
                        }
                    }
                }
            }
Ejemplo n.º 12
0
        /// <summary>
        /// Determines if a given spatial context exists in the given collection (comparison is by name).
        /// </summary>
        /// <param name="targetContexts">The target spatial context list</param>
        /// <param name="sc">The spatial context to look for</param>
        /// <returns></returns>
        protected static bool SpatialContextExists(ReadOnlyCollection <SpatialContextInfo> targetContexts, SpatialContextInfo sc)
        {
            bool found = false;

            foreach (SpatialContextInfo tsc in targetContexts)
            {
                if (tsc.Name == sc.Name)
                {
                    found = true;
                    break;
                }
            }
            return(found);
        }
Ejemplo n.º 13
0
 public FdoSpatialContextDialog(FdoConnection conn, SpatialContextInfo sci)
     : this(conn)
 {
     _presenter.SetSpatialContext(sci);
 }
Ejemplo n.º 14
0
 /// <summary>
 /// Determines if the given spatial context in the list of spatial context names
 /// </summary>
 /// <param name="ctx">The spatial context</param>
 /// <param name="names">The spatial context name list</param>
 /// <returns></returns>
 protected bool SpatialContextInSpecifiedList(SpatialContextInfo ctx, string[] names)
 {
     return(Array.Exists <string>(names, delegate(string s) { return s == ctx.Name; }));
 }
Ejemplo n.º 15
0
        internal static FdoClassCopyOptions FromElement(FdoCopyTaskElement el, FeatureSchemaCache cache, FdoConnection sourceConn, FdoConnection targetConn, out TargetClassModificationItem mod)
        {
            mod = null;
            if (!cache.HasConnection(el.Source.connection))
            {
                throw new TaskLoaderException("The referenced source connection is not defined");
            }

            if (!cache.HasConnection(el.Target.connection))
            {
                throw new TaskLoaderException("The referenced target connection is not defined");
            }

            FdoClassCopyOptions opts = new FdoClassCopyOptions(el.Source.connection, el.Target.connection, el.Source.schema, el.Source.@class, el.Target.schema, el.Target.@class);

            opts.DeleteTarget = el.Options.DeleteTarget;
            opts.SourceFilter = el.Options.Filter;
            if (!el.Options.FlattenGeometriesSpecified)
            {
                opts.FlattenGeometries = false;
            }
            else
            {
                opts.FlattenGeometries = el.Options.FlattenGeometries;
            }

            if (!el.Options.ForceWKBSpecified)
            {
                opts.ForceWkb = false;
            }
            else
            {
                opts.ForceWkb = el.Options.ForceWKB;
            }

            if (!string.IsNullOrEmpty(el.Options.BatchSize))
            {
                opts.BatchSize = Convert.ToInt32(el.Options.BatchSize);
            }
            opts.Name = el.name;
            opts.CreateIfNotExists = el.createIfNotExists;

            ClassDefinition srcClass = cache.GetClassByName(el.Source.connection, el.Source.schema, el.Source.@class);
            ClassDefinition dstClass = cache.GetClassByName(el.Target.connection, el.Target.schema, el.Target.@class);

            if (!el.createIfNotExists && dstClass == null)
            {
                throw new InvalidOperationException("Target class " + el.Target.@class + " does not exist and the createIfNotExist option is false");
            }

            SpatialContextInfo           defaultSc          = null;
            FunctionDefinitionCollection availableFunctions = (FunctionDefinitionCollection)sourceConn.Capability.GetObjectCapability(CapabilityType.FdoCapabilityType_ExpressionFunctions);

            using (var svc = targetConn.CreateFeatureService())
            {
                defaultSc = svc.GetActiveSpatialContext();
            }

            if (dstClass != null)
            {
                foreach (FdoPropertyMappingElement propMap in el.PropertyMappings)
                {
                    if (srcClass.Properties.IndexOf(propMap.source) < 0)
                    {
                        throw new TaskLoaderException("The property mapping (" + propMap.source + " -> " + propMap.target + ") in task (" + el.name + ") contains a source property not found in the source class definition (" + el.Source.@class + ")");
                    }

                    //Add to list of properties to check for
                    if (propMap.createIfNotExists && dstClass.Properties.IndexOf(propMap.target) < 0)
                    {
                        if (mod == null)
                        {
                            mod = new UpdateTargetClass(dstClass.Name);
                        }

                        opts.AddSourcePropertyToCheck(propMap.source);

                        //Clone copy of source property of same name
                        var srcProp = srcClass.Properties[srcClass.Properties.IndexOf(propMap.source)];
                        srcProp = FdoSchemaUtil.CloneProperty(srcProp);
                        mod.AddProperty(srcProp);
                    }
                    else
                    {
                        if (dstClass.Properties.IndexOf(propMap.target) < 0)
                        {
                            throw new TaskLoaderException("The property mapping (" + propMap.source + " -> " + propMap.target + ") in task (" + el.name + ") contains a target property not found in the target class definition (" + el.Target.@class + ")");
                        }

                        PropertyDefinition sp = srcClass.Properties[propMap.source];
                        PropertyDefinition tp = dstClass.Properties[propMap.target];

                        if (sp.PropertyType != tp.PropertyType)
                        {
                            throw new TaskLoaderException("The properties in the mapping (" + propMap.source + " -> " + propMap.target + ") are of different types");
                        }

                        //if (sp.PropertyType != PropertyType.PropertyType_DataProperty)
                        //    throw new TaskLoaderException("One or more properties in the mapping (" + propMap.source + " -> " + propMap.target + ") is not a data property");

                        DataPropertyDefinition sdp = sp as DataPropertyDefinition;
                        DataPropertyDefinition tdp = tp as DataPropertyDefinition;

                        opts.AddPropertyMapping(propMap.source, propMap.target);

                        //Property mapping is between two data properties
                        if (sdp != null && tdp != null)
                        {
                            //Types not equal, so add a conversion rule
                            if (sdp.DataType != tdp.DataType)
                            {
                                FdoDataPropertyConversionRule rule = new FdoDataPropertyConversionRule(
                                    propMap.source,
                                    propMap.target,
                                    sdp.DataType,
                                    tdp.DataType,
                                    propMap.nullOnFailedConversion,
                                    propMap.truncate);
                                opts.AddDataConversionRule(propMap.source, rule);
                            }
                        }
                    }
                }

                //
                foreach (FdoExpressionMappingElement exprMap in el.ExpressionMappings)
                {
                    if (string.IsNullOrEmpty(exprMap.target))
                    {
                        continue;
                    }

                    opts.AddSourceExpression(exprMap.alias, exprMap.Expression, exprMap.target);
                    //Add to list of properties to check for
                    if (exprMap.createIfNotExists)
                    {
                        //Class exists but property doesn't
                        if (dstClass.Properties.IndexOf(exprMap.target) < 0)
                        {
                            if (mod == null)
                            {
                                mod = new UpdateTargetClass(el.Target.@class);
                            }

                            var prop = FdoSchemaUtil.CreatePropertyFromExpressionType(exprMap.Expression, srcClass, availableFunctions, defaultSc.Name);
                            if (prop == null)
                            {
                                throw new InvalidOperationException("Could not derive a property definition from the expression: " + exprMap.Expression);
                            }

                            prop.Name = exprMap.target;
                            mod.AddProperty(prop);
                        }
                    }
                    else //Conversion rules can only apply if both properties exist.
                    {
                        FdoPropertyType?pt = ExpressionUtility.ParseExpressionType(exprMap.Expression, sourceConn);
                        if (pt.HasValue)
                        {
                            DataType?srcDt = ValueConverter.GetDataType(pt.Value);
                            if (srcDt.HasValue)
                            {
                                PropertyDefinition     tp  = dstClass.Properties[exprMap.target];
                                DataPropertyDefinition tdp = tp as DataPropertyDefinition;
                                if (tdp != null)
                                {
                                    if (srcDt.Value != tdp.DataType)
                                    {
                                        FdoDataPropertyConversionRule rule = new FdoDataPropertyConversionRule(
                                            exprMap.alias,
                                            exprMap.target,
                                            srcDt.Value,
                                            tdp.DataType,
                                            exprMap.nullOnFailedConversion,
                                            exprMap.truncate);
                                        opts.AddDataConversionRule(exprMap.alias, rule);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else //class doesn't exist
            {
                mod = new CreateTargetClassFromSource(el.Source.schema, el.Target.@class);

                foreach (var propMap in el.PropertyMappings)
                {
                    opts.AddPropertyMapping(propMap.source, propMap.target);

                    if (propMap.createIfNotExists)
                    {
                        opts.AddSourcePropertyToCheck(propMap.source);
                    }
                }

                foreach (var exprMap in el.ExpressionMappings)
                {
                    opts.AddSourceExpression(exprMap.alias, exprMap.Expression, exprMap.target);

                    if (exprMap.createIfNotExists)
                    {
                        opts.AddSourcePropertyToCheck(exprMap.alias);
                    }

                    var prop = FdoSchemaUtil.CreatePropertyFromExpressionType(exprMap.Expression, srcClass, availableFunctions, defaultSc.Name);
                    if (prop == null)
                    {
                        throw new InvalidOperationException("Could not derive a property definition from the expression: " + exprMap.Expression);
                    }
                    prop.Name = exprMap.target;
                    mod.AddProperty(prop);
                }
            }

            return(opts);
        }
        void DoWork(object sender, DoWorkEventArgs e)
        {
            IFdoReader reader = null;

            using (FdoFeatureService service = _connection.CreateFeatureService())
            {
                try
                {
                    if (e.Argument is FeatureAggregateOptions)
                    {
                        reader = service.SelectAggregates((FeatureAggregateOptions)e.Argument);
                    }
                    else if (e.Argument is StandardQuery)
                    {
                        var stdArg = (e.Argument as StandardQuery);
                        reader = service.SelectFeatures(stdArg.query, stdArg.Limit, stdArg.UseExtendedSelect);
                    }
                    else if (e.Argument is string)
                    {
                        reader = service.ExecuteSQLQuery(e.Argument.ToString());
                    }

                    //Init the data grid view
                    FdoFeatureTable table = new FdoFeatureTable();

                    table.RequestSpatialContext += delegate(object o, string name)
                    {
                        SpatialContextInfo c = service.GetSpatialContext(name);
                        if (c != null)
                        {
                            table.AddSpatialContext(c);
                        }
                    };

                    ClassDefinition clsDef   = null;
                    bool            hasJoins = false;
                    if (e.Argument is StandardQuery)
                    {
                        var qry = ((StandardQuery)e.Argument).query;
                        clsDef   = service.GetClassByName(qry.ClassName); //TODO: Should really qualify this, but our input parameters do not specify a schema
                        hasJoins = qry.JoinCriteria.Count > 0;
                    }
                    table.InitTable(reader, clsDef, hasJoins);

                    // need to store object class defn outside loop
                    ClassDefinition classDefObject = null;
                    ClassDefinition classDefAssoc  = null;

                    while (reader.ReadNext() && !_queryWorker.CancellationPending)
                    {
                        //Pass processed feature to data grid view
                        FdoFeature feat = table.NewRow();
                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            string name = reader.GetName(i);
                            if (!reader.IsNull(name))
                            {
                                FdoPropertyType pt = reader.GetFdoPropertyType(name);

                                switch (pt)
                                {
                                case FdoPropertyType.Association:
                                    // TODO: how to handle for non-StandardQuery
                                    if (e.Argument is StandardQuery)
                                    {
                                        // because the original code used an iterator over the reader.FieldCount
                                        // it is a bit of a hack to get another definition of the class and check
                                        // we are at the right property with a name comparison
                                        // TODO: code review to see if this can be implemented better
                                        FdoFeatureReader readerFeature = (FdoFeatureReader)reader;
                                        ClassDefinition  classDef      = readerFeature.GetClassDefinition();

                                        foreach (PropertyDefinition propertyDef in classDef.Properties)
                                        {
                                            // only looking for the right association
                                            if ((PropertyType.PropertyType_AssociationProperty == propertyDef.PropertyType) &&
                                                (propertyDef.Name.Equals(name)))
                                            {
                                                AssociationPropertyDefinition assocProp = (AssociationPropertyDefinition)propertyDef;
                                                ClassDefinition classAssoc = assocProp.AssociatedClass;

                                                // get a reader from the association - nice!
                                                IFeatureReader readerAssoc = readerFeature.GetFeatureObject(name);
                                                if ((null != readerAssoc) && (readerAssoc.ReadNext()))
                                                {
                                                    // TODO: this should be an iterative function

                                                    // the simple reassignment on each instance fails
                                                    //  (classDefObject.Properties is always zero after first record)
                                                    //  so have set classDefObject higher-up and re-use/
                                                    //   - problem will occur if more than one association
                                                    // ClassDefinition classDefObject = readerObject.GetClassDefinition();
                                                    if (null == classDefAssoc)
                                                    {
                                                        classDefAssoc = readerAssoc.GetClassDefinition();
                                                    }

                                                    foreach (PropertyDefinition propertyDefAssoc in classDefAssoc.Properties)
                                                    {
                                                        String nameAssoc = propertyDefAssoc.Name;

                                                        // TODO: only "data" type handled at present
                                                        if (PropertyType.PropertyType_DataProperty == propertyDefAssoc.PropertyType)
                                                        {
                                                            DataPropertyDefinition datapropertyDefAssoc = (DataPropertyDefinition)propertyDefAssoc;

                                                            String   szFullName = name + "." + nameAssoc;
                                                            DataType ptAssoc    = datapropertyDefAssoc.DataType;
                                                            // TODO: handle all types
                                                            switch (ptAssoc)
                                                            {
                                                            case DataType.DataType_String:
                                                                feat[szFullName] = readerAssoc.GetString(nameAssoc);
                                                                break;

                                                            case DataType.DataType_Int16:
                                                                feat[szFullName] = readerAssoc.GetInt16(nameAssoc);
                                                                break;

                                                            case DataType.DataType_Int32:
                                                                feat[szFullName] = readerAssoc.GetInt32(nameAssoc);
                                                                break;

                                                            case DataType.DataType_Int64:
                                                                feat[szFullName] = readerAssoc.GetInt64(nameAssoc);
                                                                break;
                                                            }
                                                        }
                                                    }
                                                    readerAssoc.Close();
                                                }
                                            }
                                        }
                                    }
                                    break;

                                case FdoPropertyType.BLOB:
                                    feat[name] = reader.GetLOB(name).Data;
                                    break;

                                case FdoPropertyType.Boolean:
                                    feat[name] = reader.GetBoolean(name);
                                    break;

                                case FdoPropertyType.Byte:
                                    feat[name] = reader.GetByte(name);
                                    break;

                                case FdoPropertyType.CLOB:
                                    feat[name] = reader.GetLOB(name).Data;
                                    break;

                                case FdoPropertyType.DateTime:
                                {
                                    try
                                    {
                                        feat[name] = reader.GetDateTime(name);
                                    }
                                    catch         //Unrepresentable dates
                                    {
                                        feat[name] = DBNull.Value;
                                    }
                                }
                                break;

                                case FdoPropertyType.Decimal:     //We should probably remove this as FDO coerces decimals to doubles (otherwise why is there not a GetDecimal() method in FdoIReader?)
                                {
                                    double val = reader.GetDouble(name);
                                    if (Double.IsNaN(val))
                                    {
                                        feat[name] = DBNull.Value;
                                    }
                                    else
                                    {
                                        feat[name] = Convert.ToDecimal(val);
                                    }
                                }
                                break;

                                case FdoPropertyType.Double:
                                    feat[name] = reader.GetDouble(name);
                                    break;

                                case FdoPropertyType.Geometry:
                                {
                                    try
                                    {
                                        byte[] fgf = reader.GetGeometry(name);
                                        OSGeo.FDO.Geometry.IGeometry geom = service.GeometryFactory.CreateGeometryFromFgf(fgf);
                                        var fg = new FdoGeometry(geom);
                                        //OGR geometry trap
                                        using (var env = fg.Envelope) { }
                                        feat[name] = fg;
                                    }
                                    catch
                                    {
                                        feat[name] = DBNull.Value;
                                    }
                                }
                                break;

                                case FdoPropertyType.Int16:
                                    feat[name] = reader.GetInt16(name);
                                    break;

                                case FdoPropertyType.Int32:
                                    feat[name] = reader.GetInt32(name);
                                    break;

                                case FdoPropertyType.Int64:
                                    feat[name] = reader.GetInt64(name);
                                    break;

                                case FdoPropertyType.Object:
                                    // TODO: how to handle for non-StandardQuery
                                    if (e.Argument is StandardQuery)
                                    {
                                        // because the original code used an iterator over the reader.FieldCount
                                        // it is a bit of a hack to get another definition of the class and check
                                        // we are at the right property with a name comparison
                                        // TODO: code review to see if this can be implemented better
                                        FdoFeatureReader readerFeature = (FdoFeatureReader)reader;
                                        ClassDefinition  classDef      = readerFeature.GetClassDefinition();

                                        foreach (PropertyDefinition propertyDef in classDef.Properties)
                                        {
                                            // only looking for the right object
                                            if ((PropertyType.PropertyType_ObjectProperty == propertyDef.PropertyType) &&
                                                (propertyDef.Name.Equals(name)))
                                            {
                                                ObjectPropertyDefinition assocProp  = (ObjectPropertyDefinition)propertyDef;
                                                ClassDefinition          classAssoc = assocProp.Class;

                                                // get a reader from the object - nice!
                                                IFeatureReader readerObject = readerFeature.GetFeatureObject(name);
                                                if ((null != readerObject) && (readerObject.ReadNext()))
                                                {
                                                    // TODO: this should be an iterative function

                                                    // the simple reassignment on each instance fails
                                                    //  (classDefObject.Properties is always zero after first record)
                                                    //  so have set classDefObject higher-up and re-use/
                                                    //   - problem will occur if more than one association
                                                    // ClassDefinition classDefObject = readerObject.GetClassDefinition();
                                                    if (null == classDefObject)
                                                    {
                                                        classDefObject = readerObject.GetClassDefinition();
                                                    }

                                                    foreach (PropertyDefinition propertyDefObject in classDefObject.Properties)
                                                    {
                                                        String nameObject = propertyDefObject.Name;

                                                        // TODO: only "data" type handled at present
                                                        if (PropertyType.PropertyType_DataProperty == propertyDefObject.PropertyType)
                                                        {
                                                            DataPropertyDefinition datapropertyDefObject = (DataPropertyDefinition)propertyDefObject;

                                                            String   szFullName = name + "." + nameObject;
                                                            DataType ptAssoc    = datapropertyDefObject.DataType;
                                                            // TODO: handle all types
                                                            switch (ptAssoc)
                                                            {
                                                            case DataType.DataType_String:
                                                                feat[szFullName] = readerObject.GetString(nameObject);
                                                                break;

                                                            case DataType.DataType_Int16:
                                                                feat[szFullName] = readerObject.GetInt16(nameObject);
                                                                break;

                                                            case DataType.DataType_Int32:
                                                                feat[szFullName] = readerObject.GetInt32(nameObject);
                                                                break;

                                                            case DataType.DataType_Int64:
                                                                feat[szFullName] = readerObject.GetInt64(nameObject);
                                                                break;
                                                            }
                                                        }
                                                    }
                                                    readerObject.Close();
                                                    readerObject = null;
                                                }
                                            }
                                        }
                                    }
                                    break;

                                //case FdoPropertyType.Raster:
                                case FdoPropertyType.Single:
                                    feat[name] = reader.GetSingle(name);
                                    break;

                                case FdoPropertyType.String:
                                    feat[name] = reader.GetString(name);
                                    break;
                                }
                            }
                            else
                            {
                                feat[name] = DBNull.Value;
                            }
                        }
                        table.AddRow(feat);

                        if (table.Rows.Count % 50 == 0)
                        {
                            System.Threading.Thread.Sleep(50);
                        }
                    }

                    if (_queryWorker.CancellationPending)
                    {
                        e.Cancel      = true;
                        _cancelResult = table;
                    }
                    else
                    {
                        e.Result = table;
                    }
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
            }
        }
Ejemplo n.º 17
0
        public override int Execute()
        {
            CommandStatus retCode;

            FdoConnection srcConn  = new FdoConnection(_srcProvider, _srcConnStr);
            FdoConnection destConn = null;

            //Directory given, assume SHP
            if (Directory.Exists(_destPath))
            {
                destConn = new FdoConnection("OSGeo.SHP", "DefaultFileLocation=" + _destPath);
            }
            else
            {
                if (ExpressUtility.CreateFlatFileDataSource(_destPath))
                {
                    destConn = ExpressUtility.CreateFlatFileConnection(_destPath);
                }
                else
                {
                    throw new FdoException("Could not create data source: " + _destPath);
                }
            }

            try
            {
                srcConn.Open();
                destConn.Open();

                string srcName = "SOURCE";
                string dstName = "TARGET";

                FdoBulkCopyOptions options = new FdoBulkCopyOptions();
                options.RegisterConnection(srcName, srcConn);
                options.RegisterConnection(dstName, destConn);
                using (FdoFeatureService srcService = srcConn.CreateFeatureService())
                    using (FdoFeatureService destService = destConn.CreateFeatureService())
                    {
                        //See if spatial context needs to be copied to target
                        if (!string.IsNullOrEmpty(_srcSpatialContext))
                        {
                            SpatialContextInfo srcCtx = srcService.GetSpatialContext(_srcSpatialContext);
                            if (srcCtx != null)
                            {
                                Console.WriteLine("Copying spatial context: " + srcCtx.Name);
                                ExpressUtility.CopyAllSpatialContexts(new SpatialContextInfo[] { srcCtx }, destConn, true);
                            }
                        }
                        else
                        {
                            //Copy all
                            ExpressUtility.CopyAllSpatialContexts(srcConn, destConn, true);
                        }

                        FeatureSchema srcSchema = null;
                        //See if partial class list is needed
                        if (_srcClasses.Count > 0)
                        {
                            WriteLine("Checking if partial schema discovery is supported: " + srcService.SupportsPartialSchemaDiscovery());

                            srcSchema = srcService.PartialDescribeSchema(_srcSchema, _srcClasses);
                        }
                        else //Full copy
                        {
                            WriteLine("No classes specified, reading full source schema");
                            srcSchema = srcService.GetSchemaByName(_srcSchema);
                        }

                        if (srcSchema == null)
                        {
                            WriteError("Could not find source schema: " + _srcSchema);
                            retCode = CommandStatus.E_FAIL_SCHEMA_NOT_FOUND;
                        }
                        else
                        {
                            WriteLine("Checking source schema for incompatibilities");
                            FeatureSchema      targetSchema = null;
                            IncompatibleSchema incSchema;
                            if (destService.CanApplySchema(srcSchema, out incSchema))
                            {
                                int clsCount = srcSchema.Classes.Count;
                                WriteLine("Applying source schema (containing " + clsCount + " classes) to target");
                                destService.ApplySchema(srcSchema, null, true);
                                targetSchema = srcSchema;
                            }
                            else
                            {
                                WriteWarning("Incompatibilities were detected in source schema. Applying a modified version to target");
                                FeatureSchema fixedSchema = destService.AlterSchema(srcSchema, incSchema);
                                int           clsCount    = fixedSchema.Classes.Count;
                                WriteLine("Applying modified source schema (containing " + clsCount + " classes) to target");
                                destService.ApplySchema(fixedSchema, null, true);
                                targetSchema = fixedSchema;
                            }

                            //Now set class copy options
                            foreach (ClassDefinition cd in srcSchema.Classes)
                            {
                                FdoClassCopyOptions copt = new FdoClassCopyOptions(srcName, dstName, srcSchema.Name, cd.Name, targetSchema.Name, cd.Name);
                                copt.FlattenGeometries = _flatten;
                                options.AddClassCopyOption(copt);
                            }

                            if (_flatten)
                            {
                                WriteWarning("The switch -flatten has been defined. Geometries that are copied will have any Z or M coordinates removed");
                            }

                            FdoBulkCopy copy = new FdoBulkCopy(options);
                            copy.ProcessMessage   += new MessageEventHandler(OnMessage);
                            copy.ProcessCompleted += new EventHandler(OnCompleted);
                            Console.WriteLine("Executing bulk copy");
                            copy.Execute();
                            List <Exception> errors = new List <Exception>(copy.GetAllErrors());
                            if (errors.Count > 0)
                            {
                                string file = GenerateLogFileName("bcp-error-");
                                LogErrors(errors, file);
                                base.WriteError("Errors were encountered during bulk copy.");
                                retCode = CommandStatus.E_FAIL_BULK_COPY_WITH_ERRORS;
                            }
                            else
                            {
                                retCode = CommandStatus.E_OK;
                            }
                            retCode = CommandStatus.E_OK;
                        }
                    }
            }
            catch (Exception ex)
            {
                WriteException(ex);
                retCode = CommandStatus.E_FAIL_UNKNOWN;
            }
            finally
            {
                srcConn.Dispose();
                destConn.Dispose();
            }
            return((int)retCode);
        }
Ejemplo n.º 18
0
 internal void AddSpatialContext(SpatialContextInfo sc)
 {
     _spatialContexts.Add(sc);
 }