/// <summary>
        /// Sets the initial state of this editor and sets up any databinding
        /// within such that user interface changes will propagate back to the
        /// model.
        /// </summary>
        /// <param name="service"></param>
        public override void Bind(IEditorService service)
        {
            _edsvc = service;
            _vl = (IVectorLayerDefinition)((ILayerDefinition)service.GetEditedResource()).SubLayer;

            service.RegisterCustomNotifier(this);
            resSettings.Bind(service);
            layerProperties.Bind(service);
            layerStyles.Bind(service);

            //Add watermark component if supported
            var sl2 = _vl as ISubLayerDefinition2;
            if (sl2 != null)
            {
                this.Controls.Remove(resSettings);
                this.Controls.Remove(layerProperties);
                this.Controls.Remove(layerStyles);

                var wm = new WatermarkCollectionEditorCtrl(service, sl2);
                wm.Dock = DockStyle.Top;

                this.Controls.Add(wm);
                this.Controls.Add(layerStyles);
                this.Controls.Add(layerProperties);
                this.Controls.Add(resSettings);
            }
        }
        private RestSourceContext GetSourceContext(dynamic conf)
        {
            var source = conf.Source as IDictionary <string, object>;

            if (source.ContainsKey("LayerDefinition")) //NOXLATE
            {
                string                 resId = conf.Source.LayerDefinition;
                ILayerDefinition       ldf   = (ILayerDefinition)_conn.ResourceService.GetResource(resId);
                IVectorLayerDefinition vl    = ldf.SubLayer as IVectorLayerDefinition;
                if (vl == null)
                {
                    throw new InvalidOperationException(string.Format(Strings.NotAVectorLayer, resId));
                }

                return(new RestSourceContext(_conn, new RestSource()
                {
                    FeatureSource = vl.ResourceId,
                    ClassName = vl.FeatureName
                }));
            }
            else if (source.ContainsKey("FeatureSource")) //NOXLATE
            {
                string resId = conf.Source.FeatureSource;

                return(new RestSourceContext(_conn, new RestSource()
                {
                    FeatureSource = resId,
                    ClassName = conf.Source.FeatureClass
                }));
            }

            throw new InvalidOperationException(Strings.InvalidSourceConfiguration);
        }
Exemple #3
0
        private void InitIdentityProperties(IVectorLayerDefinition vl, bool suppressErrors)
        {
            try
            {
                var fs  = (IFeatureSource)this.Parent.ResourceService.GetResource(vl.ResourceId);
                var cls = this.Parent.FeatureService.GetClassDefinition(fs.ResourceID, vl.FeatureName);
                if (cls == null)
                {
                    throw new Exception(string.Format(Strings.ERR_CLASS_NOT_FOUND, vl.FeatureName));
                }

                var idProps  = cls.IdentityProperties;
                var propInfo = new PropertyInfo[idProps.Count];

                int i = 0;
                foreach (var prop in idProps)
                {
                    propInfo[i] = new PropertyInfo(prop.Name, ClrFdoTypeMap.GetClrType(prop.DataType));
                    i++;
                }

                this.IdentityProperties = propInfo;
            }
            catch (Exception ex) //Has to be a bug in MapGuide or in the FDO provider
            {
                //If not suppressing, rethrow with original stack trace
                if (!suppressErrors)
                {
                    throw;
                }

                this.IdentityProperties = new PropertyInfo[0];
                Trace.TraceWarning(string.Format(Strings.ERR_INIT_IDENTITY_PROPS, Environment.NewLine, this.Name, ex.ToString()));
            }
        }
        public override void Bind(IEditorService service)
        {
            _edsvc = service;
            _edsvc.RegisterCustomNotifier(this);

            _parent = service.GetEditedResource() as ILayerDefinition;
            Debug.Assert(_parent != null);

            _vl = _parent.SubLayer as IVectorLayerDefinition;
            Debug.Assert(_vl != null);

            if (service.IsNew)
            {
                //Let's try to auto-assign a feature class
                string[] classNames = _edsvc.FeatureService.GetClassNames(_vl.ResourceId, null);
                if (classNames.Length == 1) //Only one class in this Feature Source
                {
                    var clsDef = _edsvc.FeatureService.GetClassDefinition(_vl.ResourceId, classNames[0]);
                    if (!string.IsNullOrEmpty(clsDef.DefaultGeometryPropertyName)) //It has a default geometry
                    {
                        _vl.FeatureName = classNames[0];
                        _vl.Geometry = clsDef.DefaultGeometryPropertyName;
                    }
                }
            }

            _props = new List<INameStringPair>(_vl.PropertyMapping);
            //Modifying the visibility constitutes a change in the resource
            //_props.ListChanged += OnPropertyListChanged;
            PopulatePropertyList();
            _vl.PropertyChanged += OnVectorLayerPropertyChanged;
        }
        /// <summary>
        /// Gets the number of scale ranges in this vector layer
        /// </summary>
        /// <param name="vl"></param>
        /// <returns></returns>
        public static int GetScaleRangeCount(this IVectorLayerDefinition vl)
        {
            Check.NotNull(vl, "vl"); //NOXLATE
            var list = new List <IVectorScaleRange>(vl.VectorScaleRange);

            return(list.Count);
        }
        /// <summary>
        /// Sets the initial state of this editor and sets up any databinding
        /// within such that user interface changes will propagate back to the
        /// model.
        /// </summary>
        /// <param name="service"></param>
        public override void Bind(IEditorService service)
        {
            _edsvc = service;
            _vl    = (IVectorLayerDefinition)((ILayerDefinition)service.GetEditedResource()).SubLayer;

            service.RegisterCustomNotifier(this);
            resSettings.Bind(service);
            layerProperties.Bind(service);
            layerStyles.Bind(service);

            //A prompt to repair the feature source may have changed this, so update it.
            resSettings.SetFeatureSource(_vl.ResourceId);

            //Add watermark component if supported
            var sl2 = _vl as ISubLayerDefinition2;

            if (sl2 != null)
            {
                this.Controls.Remove(resSettings);
                this.Controls.Remove(layerProperties);
                this.Controls.Remove(layerStyles);

                var wm = new WatermarkCollectionEditorCtrl(service, sl2);
                wm.Dock = DockStyle.Top;

                this.Controls.Add(wm);
                this.Controls.Add(layerStyles);
                this.Controls.Add(layerProperties);
                this.Controls.Add(resSettings);
            }
        }
Exemple #7
0
        private void InitScaleRanges(IVectorLayerDefinition vl)
        {
            List <double> scales = new List <double>();

            foreach (var vsr in vl.VectorScaleRange)
            {
                if (vsr.MinScale.HasValue)
                {
                    scales.Add(vsr.MinScale.Value);
                }
                else
                {
                    scales.Add(0.0);
                }

                if (vsr.MaxScale.HasValue)
                {
                    scales.Add(vsr.MaxScale.Value);
                }
                else
                {
                    scales.Add(InfinityScale);
                }
            }
            _scaleRanges = scales.ToArray();
            EnsureOrderedMinMaxScales();
        }
        public override void Bind(IEditorService service)
        {
            _edsvc = service;
            _edsvc.RegisterCustomNotifier(this);

            _parent = service.GetEditedResource() as ILayerDefinition;
            Debug.Assert(_parent != null);

            _vl = _parent.SubLayer as IVectorLayerDefinition;
            Debug.Assert(_vl != null);

            if (service.IsNew)
            {
                //Let's try to auto-assign a feature class
                string[] classNames = _edsvc.CurrentConnection.FeatureService.GetClassNames(_vl.ResourceId, null);
                if (classNames.Length == 1) //Only one class in this Feature Source
                {
                    var clsDef = _edsvc.CurrentConnection.FeatureService.GetClassDefinition(_vl.ResourceId, classNames[0]);
                    if (!string.IsNullOrEmpty(clsDef.DefaultGeometryPropertyName)) //It has a default geometry
                    {
                        _vl.FeatureName = classNames[0];
                        _vl.Geometry    = clsDef.DefaultGeometryPropertyName;
                    }
                }
            }

            _props = new List <INameStringPair>(_vl.PropertyMapping);
            PopulatePropertyList();
            _vl.PropertyChanged += WeakEventHandler.Wrap <PropertyChangedEventHandler>(OnVectorLayerPropertyChanged, (eh) => _vl.PropertyChanged -= eh);
        }
 private ClassDefinition GetLayerClass()
 {
     if (_layerClass == null)
     {
         IVectorLayerDefinition vl = (IVectorLayerDefinition)_editedLayer.SubLayer;
         _layerClass = _edSvc.CurrentConnection.FeatureService.GetClassDefinition(vl.ResourceId, vl.FeatureName);
     }
     return(_layerClass);
 }
 private string GetLayerProvider()
 {
     if (_providerName == null)
     {
         IVectorLayerDefinition vl = (IVectorLayerDefinition)_editedLayer.SubLayer;
         IFeatureSource         fs = (IFeatureSource)_edSvc.CurrentConnection.ResourceService.GetResource(vl.ResourceId);
         _providerName = fs.Provider;
     }
     return(_providerName);
 }
Exemple #11
0
        public override void Bind(IEditorService service)
        {
            _edsvc = service;
            _edsvc.RegisterCustomNotifier(this);
            var res = (ILayerDefinition)service.GetEditedResource();

            _vl      = (IVectorLayerDefinition)res.SubLayer;
            _factory = (ILayerElementFactory)res;
            BindScaleList(_vl.VectorScaleRange);
            EvaluateCommands();
        }
 /// <summary>
 /// Gets the referenced schema of this vector layer
 /// </summary>
 /// <param name="vl"></param>
 /// <returns></returns>
 public static string GetSchema(this IVectorLayerDefinition vl)
 {
     if (string.IsNullOrEmpty(vl.FeatureName) || !vl.FeatureName.Contains(":")) //NOXLATE
     {
         return(string.Empty);
     }
     else
     {
         return(vl.FeatureName.Split(':')[0]); //NOXLATE
     }
 }
Exemple #13
0
        private async Task <DownloadedFeaturesRef> DownloadFeatureDataAsync(IVectorLayerDefinition vl, int layerNumber, string name, Stream stream, bool generateVtIndex)
        {
            var dataFilePath   = Path.GetFullPath(Path.Combine(_options.OutputDirectory, "vector_overlays", $"{GetFileName(layerNumber)}_data.js"));
            var configFilePath = Path.GetFullPath(Path.Combine(_options.OutputDirectory, "vector_overlays", $"{GetFileName(layerNumber)}_config.js"));
            var dir            = Path.GetDirectoryName(dataFilePath);

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            using (var sw = new StreamWriter(configFilePath))
            {
                await sw.WriteLineAsync($"//Vector overlay configuration for: {name}");
                await WritePopupConfigurationAsync(vl, layerNumber, name, sw);
                await WriteStyleConfigurationAsync(vl, layerNumber, name, sw);

                if (generateVtIndex)
                {
                    await sw.WriteLineAsync($"\n\n//GeoJSON Vector Tile index for: {name}");

                    await sw.WriteLineAsync($@"
var {GetVariableName(layerNumber)}_vtindex = geojsonvt({GetVariableName(layerNumber)}, {{
    extent: 4096,
    maxZoom: 19,
    debug: 1
}});");
                }
            }

            using (var sw = new StreamWriter(dataFilePath))
            {
                await sw.WriteLineAsync($"//GeoJSON vector data for: {name}");

                await sw.WriteLineAsync($"//Downloaded features for: {name}");

                await sw.WriteAsync($"var {GetVariableName(layerNumber)} = ");
            }

            //Download the GeoJSON and append to the JS
            using (var fw = new FileStream(dataFilePath, FileMode.Append, FileAccess.Write))
            {
                await stream.CopyToAsync(fw);
            }

            return(new DownloadedFeaturesRef(name,
                                             $"vector_overlays/{GetFileName(layerNumber)}_data.js",
                                             $"vector_overlays/{GetFileName(layerNumber)}_config.js",
                                             GetVariableName(layerNumber)));
        }
Exemple #14
0
        private static void CreateTracksLayer(IServerConnection conn, string resId, string layerId)
        {
            //We use the Utility class to create our layer. You can also use ObjectFactory, but
            //that requires explicitly specifying the resource version. Using Utility will pick
            //the latest supported version
            ILayerDefinition       ldf  = Utility.CreateDefaultLayer(conn, LayerType.Vector);
            IVectorLayerDefinition vldf = (IVectorLayerDefinition)ldf.SubLayer;

            //Set feature source
            vldf.ResourceId = resId;

            //Set the feature class
            vldf.FeatureName = "SHP_Schema:Rail";

            //Set the designated geometry
            vldf.Geometry = "SHPGEOM";

            //Get the first vector scale range. This will have been created for us and is 0 to infinity
            IVectorScaleRange vsr = vldf.GetScaleRangeAt(0);

            //Get the line style
            ILineVectorStyle lstyle = vsr.LineStyle;

            //Get the first rule (a created one will only have one)
            ILineRule rule = lstyle.GetRuleAt(0);

            //What are we doing here? We're checking if this vector scale range is a
            //IVectorScaleRange2 instance. If it is, it means this layer definition
            //has a composite style attached, which takes precedence over point/area/line
            //styles. We don't want this, so this removes the composite styles if they
            //exist.
            IVectorScaleRange2 vsr2 = vsr as IVectorScaleRange2;

            if (vsr2 != null)
            {
                vsr2.CompositeStyle = null;
            }

            //There's only one stroke here, but iteration is the only
            //way to go through
            foreach (var stroke in rule.Strokes)
            {
                //Set color to red
                stroke.Color = "ffff0000";
            }

            //Now save it
            conn.ResourceService.SaveResourceAs(ldf, layerId);
        }
        /// <summary>
        /// Returns the associated spatial context for this Layer Definition
        /// </summary>
        /// <param name="layer"></param>
        /// <returns></returns>
        public static IFdoSpatialContext GetSpatialContext(this ILayerDefinition layer)
        {
            Check.NotNull(layer, "layer"); //NOXLATE
            if (layer.CurrentConnection == null)
            {
                throw new System.Exception(OSGeo.MapGuide.MaestroAPI.Strings.ErrorNoServerConnectionAttached);
            }

            var conn  = layer.CurrentConnection;
            var ltype = layer.SubLayer.LayerType;

            if (ltype == LayerType.Vector ||
                ltype == LayerType.Raster)
            {
                var sContexts = conn.FeatureService.GetSpatialContextInfo(layer.SubLayer.ResourceId, false);
                if (ltype == LayerType.Vector)
                {
                    IVectorLayerDefinition vl = (IVectorLayerDefinition)layer.SubLayer;
                    var clsDef = conn.FeatureService.GetClassDefinition(vl.ResourceId, vl.FeatureName);
                    var geom   = clsDef.FindProperty(vl.Geometry) as GeometricPropertyDefinition;
                    if (geom != null)
                    {
                        var sc = FindSpatialContext(sContexts, geom.SpatialContextAssociation);
                        return(sc);
                    }
                    return(null);
                }
                else if (ltype == LayerType.Raster)
                {
                    IRasterLayerDefinition rl = (IRasterLayerDefinition)layer.SubLayer;
                    var clsDef = conn.FeatureService.GetClassDefinition(rl.ResourceId, rl.FeatureName);
                    var geom   = clsDef.FindProperty(rl.Geometry) as RasterPropertyDefinition;
                    if (geom != null)
                    {
                        var sc = FindSpatialContext(sContexts, geom.SpatialContextAssociation);
                        return(sc);
                    }
                    return(null);
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
Exemple #16
0
            /// <summary>
            /// Returns the associated spatial context for this Layer Definition
            /// </summary>
            /// <param name="layer">The layer definition</param>
            /// <param name="conn">The server connection</param>
            /// <returns>The associated spatial context</returns>
            public static IFdoSpatialContext GetSpatialContext(this ILayerDefinition layer, IServerConnection conn)
            {
                Check.ArgumentNotNull(layer, nameof(layer));
                Check.ArgumentNotNull(conn, nameof(conn));
                var ltype = layer.SubLayer.LayerType;

                if (ltype == LayerType.Vector ||
                    ltype == LayerType.Raster)
                {
                    var sContexts = conn.FeatureService.GetSpatialContextInfo(layer.SubLayer.ResourceId, false);
                    if (ltype == LayerType.Vector)
                    {
                        IVectorLayerDefinition vl = (IVectorLayerDefinition)layer.SubLayer;
                        var clsDef = conn.FeatureService.GetClassDefinition(vl.ResourceId, vl.FeatureName);
                        var geom   = clsDef.FindProperty(vl.Geometry) as GeometricPropertyDefinition;
                        if (geom != null)
                        {
                            var sc = FindSpatialContext(sContexts, geom.SpatialContextAssociation);
                            return(sc);
                        }
                        return(null);
                    }
                    else if (ltype == LayerType.Raster)
                    {
                        IRasterLayerDefinition rl = (IRasterLayerDefinition)layer.SubLayer;
                        var clsDef = conn.FeatureService.GetClassDefinition(rl.ResourceId, rl.FeatureName);
                        var geom   = clsDef.FindProperty(rl.Geometry) as RasterPropertyDefinition;
                        if (geom != null)
                        {
                            var sc = FindSpatialContext(sContexts, geom.SpatialContextAssociation);
                            return(sc);
                        }
                        return(null);
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    return(null);
                }
            }
Exemple #17
0
        /// <summary>
        /// Performs base resource validation
        /// </summary>
        /// <param name="context"></param>
        /// <param name="resource"></param>
        /// <param name="recurse"></param>
        /// <returns></returns>
        protected ValidationIssue[] ValidateBase(ResourceValidationContext context, IResource resource, bool recurse)
        {
            Check.ArgumentNotNull(context, nameof(context));

            if (context.IsAlreadyValidated(resource.ResourceID))
            {
                return(null);
            }

            if (resource.ResourceType != ResourceTypes.MapDefinition.ToString())
            {
                return(null);
            }

            List <ValidationIssue> issues = new List <ValidationIssue>();

            IMapDefinition mdef = resource as IMapDefinition;

            if (string.IsNullOrEmpty(mdef.CoordinateSystem))
            {
                issues.Add(new ValidationIssue(mdef, ValidationStatus.Warning, ValidationStatusCode.Warning_MapDefinition_MissingCoordinateSystem, Strings.MDF_NoCoordinateSystem));
            }

            foreach (IMapLayerGroup g in mdef.MapLayerGroup)
            {
                if (g.ShowInLegend && (g.LegendLabel == null || g.LegendLabel.Trim().Length == 0))
                {
                    issues.Add(new ValidationIssue(mdef, ValidationStatus.Information, ValidationStatusCode.Info_MapDefinition_GroupMissingLabelInformation, string.Format(Strings.MDF_GroupMissingLabelInformation, g.Name)));
                }
                else if (g.ShowInLegend && g.LegendLabel.Trim().ToLower() == "layer group") //NOXLATE
                {
                    issues.Add(new ValidationIssue(mdef, ValidationStatus.Information, ValidationStatusCode.Info_MapDefinition_GroupHasDefaultLabel, string.Format(Strings.MDF_GroupHasDefaultLabelInformation, g.Name)));
                }

                if (!string.IsNullOrEmpty(g.Group))
                {
                    var grp = mdef.GetGroupByName(g.Group);
                    if (grp == null)
                    {
                        issues.Add(new ValidationIssue(mdef, ValidationStatus.Error, ValidationStatusCode.Error_MapDefinition_GroupWithNonExistentGroup, string.Format(Strings.MDF_GroupWithNonExistentGroup, g.Name, g.Group)));
                    }
                }
            }

            List <IBaseMapLayer> layers = new List <IBaseMapLayer>();

            foreach (IBaseMapLayer l in mdef.MapLayer)
            {
                layers.Add(l);
            }

            if (mdef.BaseMap != null && mdef.BaseMap.HasGroups())
            {
                if (mdef.BaseMap.ScaleCount == 0)
                {
                    issues.Add(new ValidationIssue(mdef, ValidationStatus.Error, ValidationStatusCode.Error_MapDefinition_NoFiniteDisplayScales, Strings.MDF_NoFiniteDisplayScalesSpecified));
                }

                foreach (IBaseMapGroup g in mdef.BaseMap.BaseMapLayerGroups)
                {
                    foreach (IBaseMapLayer l in g.BaseMapLayer)
                    {
                        layers.Add(l);
                    }
                }
            }
            Dictionary <string, IBaseMapLayer> nameCounter = new Dictionary <string, IBaseMapLayer>();

            foreach (IBaseMapLayer l in layers)
            {
                if (nameCounter.ContainsKey(l.Name))
                {
                    issues.Add(new ValidationIssue(mdef, ValidationStatus.Warning, ValidationStatusCode.Error_MapDefinition_DuplicateLayerName, string.Format(Strings.MDF_LayerNameDuplicateWarning, l.Name, l.ResourceId, nameCounter[l.Name].ResourceId)));
                }
                else
                {
                    nameCounter.Add(l.Name, l);
                }

                var ml = l as IMapLayer;
                if (ml != null && !string.IsNullOrEmpty(ml.Group))
                {
                    var grp = mdef.GetGroupByName(ml.Group);
                    if (grp == null)
                    {
                        issues.Add(new ValidationIssue(mdef, ValidationStatus.Error, ValidationStatusCode.Error_MapDefinition_LayerWithNonExistentGroup, string.Format(Strings.MDF_LayerWithNonExistentGroup, ml.Name, ml.Group)));
                    }
                }

                if (l.ShowInLegend && (string.IsNullOrEmpty(l.LegendLabel) || l.LegendLabel.Trim().Length == 0))
                {
                    issues.Add(new ValidationIssue(mdef, ValidationStatus.Information, ValidationStatusCode.Warning_MapDefinition_LayerMissingLegendLabel, string.Format(Strings.MDF_LayerMissingLabelInformation, l.Name)));
                }

                var mapEnv = ObjectFactory.CreateEnvelope(mdef.Extents.MinX, mdef.Extents.MinY, mdef.Extents.MaxX, mdef.Extents.MaxY);

                try
                {
                    ILayerDefinition layer = null;
                    IResource        res   = context.GetResource(l.ResourceId);
                    if (!ResourceValidatorSet.HasValidator(res.ResourceType, res.ResourceVersion))
                    {
                        //Need to trap the no registered validator message
                        issues.AddRange(ResourceValidatorSet.Validate(context, res, true));
                        continue;
                    }

                    layer = (ILayerDefinition)res;
                    if (recurse)
                    {
                        issues.AddRange(ResourceValidatorSet.Validate(context, layer, recurse));
                    }

                    IVectorLayerDefinition vl = null;
                    if (layer.SubLayer.LayerType == LayerType.Vector)
                    {
                        vl = (IVectorLayerDefinition)layer.SubLayer;
                    }

                    if (vl != null)
                    {
                        try
                        {
                            IFeatureSource fs = (IFeatureSource)context.GetResource(vl.ResourceId);
                            if (l.Selectable)
                            {
                                //Test selectability requirement
                                string[] idProps = fs.GetIdentityProperties(this.Connection, vl.FeatureName);
                                if (idProps == null || idProps.Length == 0)
                                {
                                    issues.Add(new ValidationIssue(resource, ValidationStatus.Warning, ValidationStatusCode.Warning_MapDefinition_UnselectableLayer, string.Format(Strings.MDF_UnselectableLayer, l.Name, vl.FeatureName, fs.ResourceID)));
                                }
                            }

                            try
                            {
                                FdoSpatialContextList scList = context.GetSpatialContexts(fs.ResourceID);

                                if (scList.SpatialContext == null || scList.SpatialContext.Count == 0)
                                {
                                    issues.Add(new ValidationIssue(resource, ValidationStatus.Warning, ValidationStatusCode.Warning_MapDefinition_MissingSpatialContext, string.Format(Strings.MDF_MissingSpatialContextWarning, fs.ResourceID)));
                                }
                                else
                                {
                                    if (scList.SpatialContext.Count > 1)
                                    {
                                        issues.Add(new ValidationIssue(resource, ValidationStatus.Information, ValidationStatusCode.Info_MapDefinition_MultipleSpatialContexts, string.Format(Strings.MDF_MultipleSpatialContextsInformation, fs.ResourceID)));
                                    }

                                    bool skipGeomCheck = false;

                                    //TODO: Switch to the correct version (2.1), once released
                                    if (scList.SpatialContext[0].CoordinateSystemWkt != mdef.CoordinateSystem)
                                    {
                                        if (layer.SubLayer.LayerType == LayerType.Raster && this.Connection.SiteVersion <= SiteVersions.GetVersion(OSGeo.MapGuide.MaestroAPI.KnownSiteVersions.MapGuideOS2_0_2))
                                        {
                                            issues.Add(new ValidationIssue(resource, ValidationStatus.Error, ValidationStatusCode.Error_MapDefinition_RasterReprojection, string.Format(Strings.MDF_RasterReprojectionError, fs.ResourceID)));
                                        }
                                        else
                                        {
                                            issues.Add(new ValidationIssue(resource, ValidationStatus.Warning, ValidationStatusCode.Warning_MapDefinition_LayerReprojection, string.Format(Strings.MDF_DataReprojectionWarning, fs.ResourceID)));
                                        }

                                        skipGeomCheck = true;
                                    }

                                    if (vl.Geometry != null && !skipGeomCheck)
                                    {
                                        var env = this.Connection.FeatureService.GetSpatialExtent(fs.ResourceID, vl.FeatureName, vl.Geometry);
                                        if (!env.Intersects(mapEnv))
                                        {
                                            issues.Add(new ValidationIssue(resource, ValidationStatus.Warning, ValidationStatusCode.Warning_MapDefinition_DataOutsideMapBounds, string.Format(Strings.MDF_DataOutsideMapWarning, fs.ResourceID)));
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                var nex = ex as NullExtentException;
                                if (nex != null)
                                {
                                    issues.Add(new ValidationIssue(resource, ValidationStatus.Warning, ValidationStatusCode.Warning_MapDefinition_FeatureSourceWithNullExtent, string.Format(Strings.MDF_LayerWithNullExtent, fs.ResourceID)));
                                }
                                else
                                {
                                    string msg = NestedExceptionMessageProcessor.GetFullMessage(ex);
                                    issues.Add(new ValidationIssue(resource, ValidationStatus.Error, ValidationStatusCode.Error_MapDefinition_ResourceRead, string.Format(Strings.MDF_ResourceReadError, fs.ResourceID, msg)));
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            string msg = NestedExceptionMessageProcessor.GetFullMessage(ex);
                            issues.Add(new ValidationIssue(resource, ValidationStatus.Error, ValidationStatusCode.Error_MapDefinition_FeatureSourceRead, string.Format(Strings.MDF_FeatureSourceReadError, l.ResourceId, msg)));
                        }
                    }
                }
                catch (Exception ex)
                {
                    string msg = NestedExceptionMessageProcessor.GetFullMessage(ex);
                    issues.Add(new ValidationIssue(resource, ValidationStatus.Error, ValidationStatusCode.Error_MapDefinition_LayerRead, string.Format(Strings.MDF_LayerReadError, l.ResourceId, msg)));
                }
            }

            context.MarkValidated(resource.ResourceID);

            return(issues.ToArray());
        }
        public override void Bind(IEditorService service)
        {
            try
            {
                _init  = true;
                _edsvc = service;
                _edsvc.RegisterCustomNotifier(this);

                var res = service.GetEditedResource() as ILayerDefinition;
                Debug.Assert(res != null);

                _vl = res.SubLayer as IVectorLayerDefinition;
                Debug.Assert(_vl != null);

                txtFeatureClass.Text = _vl.FeatureName;
                txtGeometry.Text     = _vl.Geometry;
                ResetErrorState();

                if (string.IsNullOrEmpty(txtFeatureClass.Text) || string.IsNullOrEmpty(txtGeometry.Text))
                {
                    TryFillUIFromNewFeatureSource(_vl.ResourceId);
                    if (!_edsvc.CurrentConnection.ResourceService.ResourceExists(_vl.ResourceId))
                    {
                        errorProvider.SetError(txtFeatureSource, Strings.LayerEditorFeatureSourceNotFound);
                        MessageBox.Show(Strings.LayerEditorHasErrors);
                    }
                }
                else
                {
                    bool bShowErrorMessage = false;
                    txtFeatureSource.Text = _vl.ResourceId;
                    string featureClass = txtFeatureClass.Text;
                    string geometry     = txtGeometry.Text;
                    BusyWaitDialog.Run(null, () =>
                    {
                        var errors = new List <string>();
                        if (!_edsvc.CurrentConnection.ResourceService.ResourceExists(_vl.ResourceId))
                        {
                            errors.Add(Strings.LayerEditorFeatureSourceNotFound);
                        }
                        if (!string.IsNullOrEmpty(featureClass))
                        {
                            ClassDefinition clsDef = null;
                            try
                            {
                                clsDef = _edsvc.CurrentConnection.FeatureService.GetClassDefinition(_vl.ResourceId, featureClass);
                            }
                            catch
                            {
                                errors.Add(Strings.LayerEditorFeatureClassNotFound);
                                //These property mappings will probably be bunk if this is the case, so clear them
                                _vl.ClearPropertyMappings();
                            }

                            if (clsDef != null)
                            {
                                GeometricPropertyDefinition geom = clsDef.FindProperty(geometry) as GeometricPropertyDefinition;
                                if (geom == null)
                                {
                                    errors.Add(Strings.LayerEditorGeometryNotFound);
                                }
                            }
                            else
                            {
                                //This is probably true
                                errors.Add(Strings.LayerEditorGeometryNotFound);
                            }
                        }
                        return(errors);
                    }, (result, ex) =>
                    {
                        if (ex != null)
                        {
                            ErrorDialog.Show(ex);
                        }
                        else
                        {
                            var list = (List <string>)result;
                            foreach (var err in list)
                            {
                                if (err == Strings.LayerEditorGeometryNotFound)
                                {
                                    errorProvider.SetError(txtGeometry, err);
                                    bShowErrorMessage = true;
                                }
                                else if (err == Strings.LayerEditorFeatureSourceNotFound)
                                {
                                    errorProvider.SetError(txtFeatureSource, err);
                                    //Don't show error message here if this is the only error as the user
                                    //will get a repair feature source prompt down the road
                                }
                                else if (err == Strings.LayerEditorFeatureClassNotFound)
                                {
                                    errorProvider.SetError(txtFeatureClass, err);
                                    bShowErrorMessage = true;
                                }
                            }
                            if (bShowErrorMessage)
                            {
                                MessageBox.Show(Strings.LayerEditorHasErrors);
                            }
                        }
                    });
                }

                txtFilter.Text = _vl.Filter;

                //Loose bind this one because 2.4 changes this behaviour making it
                //unsuitable for databinding via TextBoxBinder
                txtHyperlink.Text = _vl.Url;

                txtTooltip.Text = _vl.ToolTip;

                //This is not the root object so no change listeners have been subscribed
                _vl.PropertyChanged += WeakEventHandler.Wrap <PropertyChangedEventHandler>(OnVectorLayerPropertyChanged, (eh) => _vl.PropertyChanged -= eh);
            }
            finally
            {
                _init = false;
            }
        }
Exemple #19
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string agent   = ConfigurationManager.AppSettings["MapAgentUrl"];
                string mapName = Request.Params["MAPNAME"];
                string session = Request.Params["SESSION"];

                IServerConnection conn = ConnectionProviderRegistry.CreateConnection(
                    "Maestro.Http",
                    "Url", agent,
                    "SessionId", session);

                IMappingService mpSvc   = (IMappingService)conn.GetService((int)ServiceType.Mapping);
                string          rtMapId = "Session:" + conn.SessionID + "//" + mapName + ".Map";

                RuntimeMap      rtMap      = mpSvc.OpenMap(rtMapId);
                int             layerIndex = rtMap.Layers.IndexOf("Parcels");
                RuntimeMapLayer layer      = rtMap.Layers[layerIndex];

                //Here is now the layer replacement technique works:
                //
                //We take the Layer Definition content referenced by the old layer
                //Modify the filter in this content and save it to a new resource id
                //We then create a replacement layer that points to this new resource id
                //and set the public properties to be identical of the old layer.
                //
                //Finally we then remove the old layer and put the replacement layer in its
                //place, before saving the runtime map.

                ILayerDefinition       ldf = (ILayerDefinition)conn.ResourceService.GetResource(layer.LayerDefinitionID);
                IVectorLayerDefinition vl  = (IVectorLayerDefinition)ldf.SubLayer;

                //Sets the layer filter
                vl.Filter = "RNAME LIKE 'SCHMITT%'";
                if (Request.Params["RESET"] == "1")
                {
                    vl.Filter = "";
                }

                //Save this modified layer under a different resource id
                string ldfId = "Session:" + conn.SessionID + "//ParcelsFiltered.LayerDefinition";
                conn.ResourceService.SaveResourceAs(ldf, ldfId);
                //Note that SaveResourceAs does not modify the ResourceID of the resource we want to save
                //so we need to update it here
                ldf.ResourceID = ldfId;

                //Create our replacement layer and apply the same properties from the old one
                RuntimeMapLayer replace = mpSvc.CreateMapLayer(rtMap, ldf);
                replace.ExpandInLegend = layer.ExpandInLegend;
                replace.Group          = layer.Group;
                replace.LegendLabel    = layer.LegendLabel;
                replace.Name           = layer.Name;
                replace.Selectable     = layer.Selectable;
                replace.ShowInLegend   = layer.ShowInLegend;
                replace.Visible        = layer.Visible;

                //Remove the old layer and put the new layer at the same position (thus having the
                //same draw order)
                rtMap.Layers.RemoveAt(layerIndex);
                rtMap.Layers.Insert(layerIndex, replace);
                replace.ForceRefresh();

                rtMap.Save();

                if (Request.Params["RESET"] == "1")
                {
                    lblMessage.Text   = "Layer filter has been reset";
                    resetLink.Visible = false;
                }
                else
                {
                    lblMessage.Text = "Layer filter has been set (to RNAME LIKE 'SCHMITT%')";
                    resetLink.Attributes["href"] = "ModifyParcelsFilter.aspx?MAPNAME=" + mapName + "&SESSION=" + session + "&RESET=1";
                }

                Page.ClientScript.RegisterStartupScript(
                    this.GetType(),
                    "load",
                    "<script type=\"text/javascript\"> window.onload = function() { parent.parent.Refresh(); } </script>");
            }
        }
        private void CreateThemeButton_Click(object sender, EventArgs e)
        {
            try
            {
                IVectorStyle owner = null;

                if (m_point != null)
                {
                    owner = m_point;
                }
                else if (m_line != null)
                {
                    owner = m_line;
                }
                else if (m_area != null)
                {
                    owner = m_area;
                }
                else if (m_comp != null)
                {
                    owner = m_comp;
                }

                if (owner is ICompositeTypeStyle)
                {
                    MessageBox.Show(Strings.CannotCreateThemeForCompositeStyleClassicEditor);
                    return;
                }

                ILayerDefinition       layer = (ILayerDefinition)m_owner.Editor.GetEditedResource();
                IVectorLayerDefinition vl    = (IVectorLayerDefinition)layer.SubLayer;
                if (string.IsNullOrEmpty(vl.FeatureName))
                {
                    MessageBox.Show(Strings.NoFeatureClassAssigned);
                    return;
                }
                var cls = m_owner.Editor.CurrentConnection.FeatureService.GetClassDefinition(vl.ResourceId, vl.FeatureName);
                if (cls == null)
                {
                    MessageBox.Show(string.Format(Strings.FeatureClassNotFound, vl.FeatureName));
                    return;
                }
                ThemeCreator dlg = new ThemeCreator(
                    m_owner.Editor,
                    layer,
                    m_owner.SelectedClass,
                    owner);
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    var area  = owner as IAreaVectorStyle;
                    var point = owner as IPointVectorStyle;
                    var line  = owner as ILineVectorStyle;
                    if (area != null)
                    {
                        SetItem(m_parent, area);
                    }
                    else if (point != null)
                    {
                        SetItem(m_parent, point);
                    }
                    else if (line != null)
                    {
                        SetItem(m_parent, line);
                    }

                    m_owner.HasChanged();
                    m_owner.UpdateDisplay();
                }
            }
            catch (Exception ex)
            {
                string msg = NestedExceptionMessageProcessor.GetFullMessage(ex);
                m_owner.SetLastException(ex);
                MessageBox.Show(this, string.Format(Strings.GenericError, msg), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
 /// <summary>
 /// Determines whether the vector layer has scale ranges
 /// </summary>
 /// <param name="vl">The vl.</param>
 /// <returns>
 ///     <c>true</c> if vector layer has scale ranges; otherwise, <c>false</c>.
 /// </returns>
 public static bool HasVectorScaleRanges(this IVectorLayerDefinition vl)
 {
     Check.NotNull(vl, "vl"); //NOXLATE
     return(vl.GetScaleRangeCount() > 0);
 }
Exemple #22
0
        public async Task WritePointStyleFunctionAsync(StreamWriter sw, IVectorLayerDefinition vl, IPointVectorStyle pointStyle)
        {
            await sw.WriteLineAsync(INDENT + "var fillColor;");

            await sw.WriteLineAsync(INDENT + "var edgeColor;");

            await sw.WriteLineAsync(INDENT + "var edgeThickness;");

            await sw.WriteLineAsync(INDENT + "var pointRadius = 10;");

            var sb = new StringBuilder(512);
            var defaultRuleBlock = "";
            var themes           = new List <(string conditon, string filter, string block)>();

            await sw.WriteLineAsync(INDENT + "var pointStyle = OLPointCircle;");

            foreach (var rule in pointStyle.Rules)
            {
                if (rule.PointSymbolization2D != null)
                {
                    if (string.IsNullOrEmpty(rule.Filter)) //No filter = default rule effectively
                    {
                        if (string.IsNullOrEmpty(defaultRuleBlock))
                        {
                            BuildPointRuleAssignment(sb, rule.PointSymbolization2D.Symbol as IMarkSymbol);
                            defaultRuleBlock = sb.ToString();
                        }
                    }
                    else
                    {
                        //Parse this filter and see if it's translateable
                        var filter = FdoFilter.Parse(rule.Filter);
                        var check  = TryTranslateFdoFilter(filter, _featureVarName);
                        BuildPointRuleAssignment(sb, rule.PointSymbolization2D.Symbol as IMarkSymbol);
                        themes.Add((check, rule.Filter, sb.ToString()));
                    }
                }
            }

            //Now write out the theme
            if (themes.Count > 0)
            {
                bool bFirst = true;
                foreach (var th in themes)
                {
                    if (bFirst)
                    {
                        await sw.WriteLineAsync(INDENT + $"if ({th.conditon}) {{ // Translated from rule filter: {th.filter}");

                        await sw.WriteLineAsync(th.block);

                        await sw.WriteLineAsync(INDENT + "}");
                    }
                    else
                    {
                        await sw.WriteLineAsync(INDENT + $"else if ({th.conditon}) {{  // Translated from rule filter: {th.filter}");

                        await sw.WriteLineAsync(th.block);

                        await sw.WriteLineAsync(INDENT + "}");
                    }

                    bFirst = false;
                }

                if (!string.IsNullOrEmpty(defaultRuleBlock))
                {
                    await sw.WriteLineAsync(INDENT + $"else {{  // Default rule");

                    await sw.WriteLineAsync(defaultRuleBlock);

                    await sw.WriteLineAsync(INDENT + "}");
                }
            }
            else
            {
                await sw.WriteLineAsync("//Default rule");

                await sw.WriteLineAsync(defaultRuleBlock);
            }

            await sw.WriteLineAsync(INDENT + "var style = {");

            await sw.WriteLineAsync(INDENT + INDENT + "radius: pointRadius,");

            await sw.WriteLineAsync(INDENT + INDENT + $"fill: new ol.style.Fill({{ color: fillColor }}),");

            await sw.WriteLineAsync(INDENT + INDENT + $"stroke: new ol.style.Stroke({{ color: edgeColor, width: edgeThickness }})");

            await sw.WriteLineAsync(INDENT + "}");

            await sw.WriteLineAsync(INDENT + "return new ol.style.Style({ image: pointStyle(style) });");
        }
Exemple #23
0
        private async Task WritePopupConfigurationAsync(IVectorLayerDefinition vl, int layerNumber, string name, StreamWriter sw)
        {
            await sw.WriteLineAsync($"//{_options.Viewer} popup template configuration for: {name}");

            if (vl.PropertyMapping.Any())
            {
                switch (_options.Viewer)
                {
                case ViewerType.Leaflet:
                {
                    await sw.WriteLineAsync($"var {GetVariableName(layerNumber)}_popup_template = function(feature, layer) {{");

                    await sw.WriteLineAsync("    var html = '<h3>" + name + "</h3><table>';");

                    await sw.WriteLineAsync("    html += '<tbody>';");

                    foreach (var pm in vl.PropertyMapping)
                    {
                        await sw.WriteLineAsync("    html += '<tr>';");

                        await sw.WriteLineAsync("    html += '<td>';");

                        await sw.WriteLineAsync("    html += '" + pm.Value + "';");

                        await sw.WriteLineAsync("    html += '</td>';");

                        await sw.WriteLineAsync("    html += '<td>';");

                        await sw.WriteLineAsync("    html += feature.properties." + pm.Name + " || '';");

                        await sw.WriteLineAsync("    html += '</td>';");

                        await sw.WriteLineAsync("    html += '</tr>';");
                    }
                    await sw.WriteLineAsync("    html += '</tbody>';");

                    await sw.WriteLineAsync("    html += '</table>';");

                    if (!string.IsNullOrEmpty(vl.Url))
                    {
                        try
                        {
                            //Only supports property references in the URL
                            var expr = FdoExpression.Parse(vl.Url);
                            if (expr is FdoIdentifier ident)
                            {
                                await sw.WriteLineAsync($"    if (feature.properties.{ident.Name}) {{");

                                await sw.WriteLineAsync($"        html += \"<hr /><a href='\" + feature.properties.{ident.Name} + \"' target='_blank'>Open Link</a>\"");

                                await sw.WriteLineAsync("    }");
                            }
                        }
                        catch { }
                    }
                    await sw.WriteLineAsync("    layer.bindPopup(html);");

                    await sw.WriteLineAsync("}");
                }
                break;

                case ViewerType.OpenLayers:
                {
                    await sw.WriteLineAsync($"var {GetVariableName(layerNumber)}_popup_template = function (feature) {{");

                    await sw.WriteLineAsync("    var html = '<h3>" + name + "</h3><table>';");

                    await sw.WriteLineAsync("    html += '<tbody>';");

                    foreach (var pm in vl.PropertyMapping)
                    {
                        await sw.WriteLineAsync("    html += '<tr>';");

                        await sw.WriteLineAsync("    html += '<td>';");

                        await sw.WriteLineAsync("    html += '" + pm.Value + "';");

                        await sw.WriteLineAsync("    html += '</td>';");

                        await sw.WriteLineAsync("    html += '<td>';");

                        await sw.WriteLineAsync("    html += feature.get('" + pm.Name + "') || '';");

                        await sw.WriteLineAsync("    html += '</td>';");

                        await sw.WriteLineAsync("    html += '</tr>';");
                    }
                    await sw.WriteLineAsync("    html += '</tbody>';");

                    await sw.WriteLineAsync("    html += '</table>';");

                    if (!string.IsNullOrEmpty(vl.Url))
                    {
                        try
                        {
                            //Only supports property references in the URL
                            var expr = FdoExpression.Parse(vl.Url);
                            if (expr is FdoIdentifier ident)
                            {
                                await sw.WriteLineAsync($"    if (feature.get('{ident.Name}')) {{");

                                await sw.WriteLineAsync($"        html += \"<hr /><a href='\" + feature.get('{ident.Name}') + \"' target='_blank'>Open Link</a>\"");

                                await sw.WriteLineAsync("    }");
                            }
                        }
                        catch { }
                    }
                    await sw.WriteLineAsync("    return html;");

                    await sw.WriteLineAsync("}");
                }
                break;
                }
            }
            else
            {
                switch (_options.Viewer)
                {
                case ViewerType.Leaflet:
                {
                    await sw.WriteLineAsync($"var {GetVariableName(layerNumber)}_popup_template = function(feature, layer) {{ }}");
                }
                break;

                case ViewerType.OpenLayers:
                {
                    await sw.WriteLineAsync($"var {GetVariableName(layerNumber)}_popup_template = null;");
                }
                break;
                }
            }
        }
        public override void Run()
        {
            var wb = Workbench.Instance;

            if (wb != null)
            {
                if (wb.ActiveSiteExplorer != null)
                {
                    var items = wb.ActiveSiteExplorer.SelectedItems;
                    if (items.Length == 1)
                    {
                        var it = items[0];
                        if (it.ResourceType == ResourceTypes.LayerDefinition.ToString())
                        {
                            var connMgr = ServiceRegistry.GetService <ServerConnectionManager>();
                            var conn    = connMgr.GetConnection(wb.ActiveSiteExplorer.ConnectionName);
                            BusyWaitDialog.Run(Strings.RetrievingSpatialContextForLayer,
                                               () =>
                            {
                                var resId = it.ResourceId;
                                var ldf   = (ILayerDefinition)conn.ResourceService.GetResource(resId);

                                //If selected item is a Layer, it must be pointing to a Feature Source and not a Drawing Source
                                if (ldf.SubLayer.ResourceId.EndsWith(ResourceTypes.FeatureSource.ToString()))
                                {
                                    var ltype = ldf.SubLayer.LayerType;
                                    if (ltype == LayerType.Vector ||
                                        ltype == LayerType.Raster)
                                    {
                                        var sc = ldf.GetSpatialContext(conn);
                                        if (sc == null)
                                        {
                                            if (ltype == LayerType.Vector)
                                            {
                                                IVectorLayerDefinition vl = (IVectorLayerDefinition)ldf.SubLayer;
                                                throw new SpatialContextNotFoundException(string.Format(Strings.GeometryPropertyNotFound, vl.Geometry));
                                            }
                                            else //Raster
                                            {
                                                IRasterLayerDefinition rl = (IRasterLayerDefinition)ldf.SubLayer;
                                                throw new SpatialContextNotFoundException(string.Format(Strings.RasterPropertyNotFound, rl.Geometry));
                                            }
                                        }
                                        return(sc);
                                    }
                                    else
                                    {
                                        throw new SpatialContextNotFoundException(string.Format(Strings.NonApplicableLayerType, ldf.SubLayer.LayerType));
                                    }
                                }
                                else
                                {
                                    throw new SpatialContextNotFoundException(string.Format(Strings.NonApplicableLayerType, ldf.SubLayer.LayerType));
                                }
                            }, (res, ex) =>
                            {
                                if (ex != null)
                                {
                                    var nf = ex as SpatialContextNotFoundException;
                                    if (nf != null)
                                    {
                                        MessageService.ShowMessage(nf.Message);
                                    }
                                    else
                                    {
                                        ErrorDialog.Show(ex);
                                    }
                                }
                                else
                                {
                                    var sc = res as IFdoSpatialContext;
                                    if (sc != null)
                                    {
                                        new SpatialContextInfoDialog(sc).ShowDialog();
                                    }
                                }
                            });
                        }
                    }
                }
            }
        }
Exemple #25
0
        private async Task WriteStyleConfigurationAsync(IVectorLayerDefinition vl, int layerNumber, string name, StreamWriter sw)
        {
            await sw.WriteLineAsync($"//Style configuration for: {name}");

            var vsr = vl.VectorScaleRange.FirstOrDefault();

            //No vector scale range = nothing to translate.
            if (vsr == null)
            {
                await sw.WriteLineAsync($"var {GetVariableName(layerNumber)}_style = null; //Could not determine or translate from source style. Use OL default");

                return;
            }

            //Can't translate from advanced stylization
            if (vsr is IVectorScaleRange2 vsr2 && vsr2.CompositeStyle.Any())
            {
                await sw.WriteLineAsync($"var {GetVariableName(layerNumber)}_style = null; //Could not determine or translate from source style. Use OL default");

                return;
            }

            if (_options.Viewer == ViewerType.OpenLayers)
            {
                var olx = new OLStyleTranslator("feature");
                await sw.WriteLineAsync($"var {GetVariableName(layerNumber)}_style = function ({olx.FeatureVariableName}, resolution) {{");

                if (vsr.AreaStyle != null)
                {
                    await olx.WritePolygonStyleFunctionAsync(sw, vl, vsr.AreaStyle);
                }
                else if (vsr.LineStyle != null)
                {
                    await olx.WriteLineStyleFunctionAsync(sw, vl, vsr.LineStyle);
                }
                else if (vsr.PointStyle != null)
                {
                    await olx.WritePointStyleFunctionAsync(sw, vl, vsr.PointStyle);
                }
                await sw.WriteLineAsync("}");
            }
            else if (_options.Viewer == ViewerType.Leaflet)
            {
                var lst = new LeafletStyleTranslator("feature");
                await sw.WriteLineAsync($"var {GetVariableName(layerNumber)}_style = function ({lst.FeatureVariableName}) {{");

                if (vsr.AreaStyle != null)
                {
                    await lst.WritePolygonStyleFunctionAsync(sw, vl, vsr.AreaStyle);
                }
                else if (vsr.LineStyle != null)
                {
                    await lst.WriteLineStyleFunctionAsync(sw, vl, vsr.LineStyle);
                }
                else if (vsr.PointStyle != null)
                {
                    await lst.WritePointStyleFunctionAsync(sw, vl, vsr.PointStyle);
                }
                await sw.WriteLineAsync("}");

                await lst.WritePointMarker(GetVariableName(layerNumber), vsr, sw);
            }
        }
Exemple #26
0
        private void ProfileLayerDefinition(ILayerDefinition ldef)
        {
            //TODO: This was a line-by-line port from 2.x to match the 3.x APIs
            //we should find time to clean this up and ensure the profiling numbers are
            //truly reflective of actual performance metrics
            if (backgroundWorker.CancellationPending)
            {
                return;
            }

            string resourceId = ldef == m_item ? m_resourceId : ldef.ResourceID;

            MakeTempMap();

            backgroundWorker.ReportProgress(0, (string.Format(Strings.Prof_LogMessageLayerDefinition, resourceId)));
            using (new Timer(Strings.Prof_LogMessageRuntimeLayer, backgroundWorker))
            {
                try
                {
                    IMapDefinition mdef = Utility.CreateMapDefinition(m_connection, string.Empty);
                    //We cannot flub this anymore. AIMS 2012 demands the Map Definition id specified checks out
                    mdef.ResourceID = "Session:" + m_connection.SessionID + "//ProfileTest.MapDefinition"; //NOXLATE
                    m_connection.ResourceService.SaveResource(mdef);
                    IMapLayer layer = mdef.AddLayer(null, "Test Layer", ldef.ResourceID);                  //NOXLATE
                    layer.Visible    = false;
                    layer.Selectable = false;

                    if (backgroundWorker.CancellationPending)
                    {
                        return;
                    }

                    var mpsvc = (IMappingService)m_connection.GetService((int)ServiceType.Mapping);

                    var map = mpsvc.CreateMap(mdef);
                    using (new Timer(Strings.Prof_LogMessageIdentifyFetching, backgroundWorker))
                    {
                        var rtl = map.Layers["Test Layer"]; //NOXLATE
                        rtl.Visible    = true;
                        rtl.Selectable = true;
                    }

                    map.Save();
                }
                catch (Exception ex)
                {
                    //string msg = NestedExceptionMessageProcessor.GetFullMessage(ex);
                    backgroundWorker.ReportProgress(0, (string.Format(Strings.Prof_LayerDefinitionProfilingError, resourceId, ex.ToString(), Environment.NewLine)));
                }
            }

            if (backgroundWorker.CancellationPending)
            {
                return;
            }

            ILayerDefinition lx = (ILayerDefinition)ldef.Clone();

            if (lx.SubLayer.LayerType == LayerType.Vector || lx.SubLayer.LayerType == LayerType.Raster)
            {
                using (new Timer(Strings.Prof_LogMessageRenderingScales, backgroundWorker))
                {
                    if (lx.SubLayer.LayerType == LayerType.Vector)
                    {
                        IVectorLayerDefinition vlx = lx.SubLayer as IVectorLayerDefinition;
                        //VectorScaleRangeTypeCollection ranges = vlx.VectorScaleRange;
                        List <IVectorScaleRange> ranges = new List <IVectorScaleRange>(vlx.VectorScaleRange);
                        foreach (var vsr in ranges)
                        {
                            if (backgroundWorker.CancellationPending)
                            {
                                return;
                            }

                            string tmp1 = new ResourceIdentifier(Guid.NewGuid().ToString(), ResourceTypes.LayerDefinition, m_connection.SessionID);

                            try
                            {
                                double minscale = vsr.MinScale.HasValue ? vsr.MinScale.Value : 0;
                                double maxscale = vsr.MaxScale.HasValue ? vsr.MaxScale.Value : 10000000;

                                vlx.RemoveAllScaleRanges();
                                vsr.MinScale = null;
                                vsr.MaxScale = null;
                                vlx.AddVectorScaleRange(vsr);

                                m_connection.ResourceService.SaveResourceAs(lx, tmp1);

                                if (backgroundWorker.CancellationPending)
                                {
                                    return;
                                }

                                var lst = m_connection.FeatureService.GetSpatialContextInfo(vlx.ResourceId, false);

                                //Create a runtime map just containing this particular layer at this particular scale range
                                //We are profiling the stylization settings for this layer
                                var mdf = Utility.CreateMapDefinition(m_connection, "");
                                if (lst.SpatialContext != null && lst.SpatialContext.Count >= 1)
                                {
                                    mdf.CoordinateSystem = lst.SpatialContext[0].CoordinateSystemWkt;
                                    if (string.IsNullOrEmpty(m_tempmap.CoordinateSystem))
                                    {
                                        mdf.CoordinateSystem = @"LOCAL_CS[""*XY-M*"", LOCAL_DATUM[""*X-Y*"", 10000], UNIT[""Meter"", 1], AXIS[""X"", EAST], AXIS[""Y"", NORTH]]"; //NOXLATE
                                    }
                                    double llx = double.Parse(lst.SpatialContext[0].Extent.LowerLeftCoordinate.X, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture);
                                    double lly = double.Parse(lst.SpatialContext[0].Extent.LowerLeftCoordinate.Y, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture);
                                    double urx = double.Parse(lst.SpatialContext[0].Extent.UpperRightCoordinate.X, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture);
                                    double ury = double.Parse(lst.SpatialContext[0].Extent.UpperRightCoordinate.Y, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture);

                                    m_tempmap.DataExtent = ObjectFactory.CreateEnvelope(llx, lly, urx, ury);
                                }

                                SetTempLayer(mdf, tmp1);

                                var mpsvc = (IMappingService)m_connection.GetService((int)ServiceType.Mapping);
                                //We cannot flub this anymore. AIMS 2012 demands the Map Definition id specified checks out
                                mdf.ResourceID = "Session:" + m_connection.SessionID + "//ProfileTest.MapDefinition"; //NOXLATE
                                m_connection.ResourceService.SaveResource(mdf);
                                var rtmap = mpsvc.CreateMap(mdf);

                                if (m_connection.ResourceService.ResourceExists(rtmap.ResourceID))
                                {
                                    m_connection.ResourceService.DeleteResource(rtmap.ResourceID);
                                }

                                rtmap.Save();

                                if (backgroundWorker.CancellationPending)
                                {
                                    return;
                                }

                                using (new Timer(string.Format(Strings.Prof_LogMessageScaleRange, minscale, maxscale), backgroundWorker))
                                {
                                    //TODO: Use extents rather than scale
                                    //using (System.IO.Stream s = m_connection.RenderRuntimeMap(tmp2, m.Extents, 1024, 800, 96))
                                    using (System.IO.Stream s = mpsvc.RenderRuntimeMap(rtmap, ((rtmap.DataExtent.MaxX - rtmap.DataExtent.MinX) / 2) + rtmap.DataExtent.MinX, ((rtmap.DataExtent.MaxY - rtmap.DataExtent.MinY) / 2) + rtmap.DataExtent.MinY, 50000, 1024, 800, 96))
                                    {
                                        backgroundWorker.ReportProgress(0, (string.Format(Strings.Prof_MapRenderingImageSize, s.Length)));
                                    }
                                }
                            }
                            finally
                            {
                                try { m_connection.ResourceService.DeleteResource(tmp1); }
                                catch { }
                            }
                        }
                    }
                }
            }

            if (backgroundWorker.CancellationPending)
            {
                return;
            }

            backgroundWorker.ReportProgress(0, ("\r\n")); //NOXLATE
        }
Exemple #27
0
        public async Task WritePolygonStyleFunctionAsync(StreamWriter sw, IVectorLayerDefinition vl, IAreaVectorStyle areaStyle)
        {
            await sw.WriteLineAsync(INDENT + "var fillColor;");

            await sw.WriteLineAsync(INDENT + "var edgeColor;");

            await sw.WriteLineAsync(INDENT + "var edgeThickness;");

            var sb = new StringBuilder(512);
            var defaultRuleBlock = "";
            var themes           = new List <(string conditon, string filter, string block)>();

            foreach (var rule in areaStyle.Rules)
            {
                if (rule.AreaSymbolization2D != null)
                {
                    if (string.IsNullOrEmpty(rule.Filter)) //No filter = default rule effectively
                    {
                        if (string.IsNullOrEmpty(defaultRuleBlock))
                        {
                            BuildPolygonRuleAssignment(sb, rule);
                            defaultRuleBlock = sb.ToString();
                        }
                    }
                    else
                    {
                        //Parse this filter and see if it's translateable
                        var filter = FdoFilter.Parse(rule.Filter);
                        var check  = TryTranslateFdoFilter(filter, _featureVarName);
                        BuildPolygonRuleAssignment(sb, rule);
                        themes.Add((check, rule.Filter, sb.ToString()));
                    }
                }
            }

            //Now write out the theme
            if (themes.Count > 0)
            {
                bool bFirst = true;
                foreach (var th in themes)
                {
                    if (bFirst)
                    {
                        await sw.WriteLineAsync(INDENT + $"if ({th.conditon}) {{ // Translated from rule filter: {th.filter}");

                        await sw.WriteLineAsync(th.block);

                        await sw.WriteLineAsync(INDENT + "}");
                    }
                    else
                    {
                        await sw.WriteLineAsync(INDENT + $"else if ({th.conditon}) {{  // Translated from rule filter: {th.filter}");

                        await sw.WriteLineAsync(th.block);

                        await sw.WriteLineAsync(INDENT + "}");
                    }

                    bFirst = false;
                }

                if (!string.IsNullOrEmpty(defaultRuleBlock))
                {
                    await sw.WriteLineAsync(INDENT + $"else {{  // Default rule");

                    await sw.WriteLineAsync(defaultRuleBlock);

                    await sw.WriteLineAsync(INDENT + "}");
                }
            }
            else
            {
                await sw.WriteLineAsync("//Default rule");

                await sw.WriteLineAsync(defaultRuleBlock);
            }

            await sw.WriteLineAsync(INDENT + "var style = {");

            await sw.WriteLineAsync(INDENT + INDENT + $"opacity: 1, fillOpacity: 1,");

            await sw.WriteLineAsync(INDENT + INDENT + $"fillColor: fillColor,");

            await sw.WriteLineAsync(INDENT + INDENT + $"color: edgeColor, weight: Math.max(edgeThickness, 1)");

            await sw.WriteLineAsync(INDENT + "}");

            await sw.WriteLineAsync(INDENT + "return style;");
        }
        public override void Bind(IEditorService service)
        {
            try
            {
                _init = true;
                _edsvc = service;
                _edsvc.RegisterCustomNotifier(this);

                var res = service.GetEditedResource() as ILayerDefinition;
                Debug.Assert(res != null);

                _vl = res.SubLayer as IVectorLayerDefinition;
                Debug.Assert(_vl != null);

                TextBoxBinder.BindText(txtFeatureSource, _vl, "ResourceId");

                TextBoxBinder.BindText(txtFeatureClass, _vl, "FeatureName");
                TextBoxBinder.BindText(txtGeometry, _vl, "Geometry");
                //TextBoxBinder.BindText(txtFilter, _vl, "Filter");
                txtFilter.Text = _vl.Filter;

                //Loose bind this one because 2.4 changes this behaviour making it
                //unsuitable for databinding via TextBoxBinder
                txtHyperlink.Text = _vl.Url;

                //TextBoxBinder.BindText(txtTooltip, _vl, "ToolTip");
                txtTooltip.Text = _vl.ToolTip;

                //This is not the root object so no change listeners have been subscribed
                _vl.PropertyChanged += OnVectorLayerPropertyChanged;
            }
            finally
            {
                _init = false;
            }
        }
        private string GetFeatureSource()
        {
            IVectorLayerDefinition vl = (IVectorLayerDefinition)_editedLayer.SubLayer;

            return(vl.ResourceId);
        }
Exemple #30
0
        private void InitScaleRanges(IVectorLayerDefinition vl)
        {
            List<double> scales = new List<double>();
            foreach (var vsr in vl.VectorScaleRange)
            {
                if (vsr.MinScale.HasValue)
                    scales.Add(vsr.MinScale.Value);
                else
                    scales.Add(0.0);

                if (vsr.MaxScale.HasValue)
                    scales.Add(vsr.MaxScale.Value);
                else
                    scales.Add(InfinityScale);
            }
            _scaleRanges = scales.ToArray();
            EnsureOrderedMinMaxScales();
        }
Exemple #31
0
        private void CreateDistrictsLayer(IServerConnection conn, string resId, string layerId)
        {
            //We use the Utility class to create our layer. You can also use ObjectFactory, but
            //that requires explicitly specifying the resource version. Using Utility will pick
            //the latest supported version
            ILayerDefinition       ldf  = Utility.CreateDefaultLayer(conn, LayerType.Vector);
            IVectorLayerDefinition vldf = (IVectorLayerDefinition)ldf.SubLayer;

            //Set feature source
            vldf.ResourceId = resId;

            //Set the feature class
            //
            //Note: In versions of the Sheboygan Dataset before 2.6, this used to be
            //
            // - Feature Class: SDF_2_Schema:VotingDistricts
            // - Identity Property: Autogenerated_SDF_ID
            // - Geometry Property: Data
            string featureClass = "Default:VotingDistricts";
            string idProp       = "FeatId";
            string geometryProp = "Geometry";

            vldf.FeatureName = featureClass;

            //Set the designated geometry
            vldf.Geometry = geometryProp;

            //Get the first vector scale range. This will have been created for us and is 0 to infinity
            IVectorScaleRange vsr = vldf.GetScaleRangeAt(0);

            //What are we doing here? We're checking if this vector scale range is a
            //IVectorScaleRange2 instance. If it is, it means this layer definition
            //has a composite style attached, which takes precedence over point/area/line
            //styles. We don't want this, so this removes the composite styles if they
            //exist.
            IVectorScaleRange2 vsr2 = vsr as IVectorScaleRange2;

            if (vsr2 != null)
            {
                vsr2.CompositeStyle = null;
            }

            //Get the area style
            IAreaVectorStyle astyle = vsr.AreaStyle;

            //Remove the default rule
            astyle.RemoveAllRules();

            IFeatureService featSvc = conn.FeatureService;
            //Generate a random color for each distinct feature id
            //Perform a distinct value query
            IReader valueReader = featSvc.AggregateQueryFeatureSource(resId, featureClass, null, new NameValueCollection()
            {
                { "Value", "UNIQUE(" + idProp + ")" } //UNIQUE() is the aggregate function that collects all distinct values of FeatId
            });

            while (valueReader.ReadNext())
            {
                //The parent Layer Definition provides all the methods needed to create the necessary child elements
                IAreaRule rule = ldf.CreateDefaultAreaRule();
                //Set the filter for this rule
                rule.Filter = idProp + " = " + valueReader["Value"].ToString();
                //IReader allows object access by name in case you don't care to determine the data type
                rule.LegendLabel = valueReader["Value"].ToString();
                //Assign a random color fill
                rule.AreaSymbolization2D.Fill.ForegroundColor = Utility.SerializeHTMLColor(RandomColor(), true);
                //Add this rule
                astyle.AddRule(rule);
            }
            valueReader.Close();

            //Now save it
            conn.ResourceService.SaveResourceAs(ldf, layerId);
        }
Exemple #32
0
        private void InitIdentityProperties(IVectorLayerDefinition vl, bool suppressErrors)
        {
            try
            {
                var fs = (IFeatureSource)this.Parent.ResourceService.GetResource(vl.ResourceId);
                var cls = fs.GetClass(vl.FeatureName);
                if (cls == null)
                    throw new Exception(string.Format(Strings.ERR_CLASS_NOT_FOUND, vl.FeatureName));

                var idProps = cls.IdentityProperties;
                var propInfo = new PropertyInfo[idProps.Count];

                int i = 0;
                foreach (var prop in idProps)
                {
                    propInfo[i] = new PropertyInfo(prop.Name, ClrFdoTypeMap.GetClrType(prop.DataType));
                    i++;
                }

                this.IdentityProperties = propInfo;
            }
            catch (Exception ex) //Has to be a bug in MapGuide or in the FDO provider
            {
                //If not suppressing, rethrow with original stack trace
                if (!suppressErrors)
                    throw;

                this.IdentityProperties = new PropertyInfo[0];
                Trace.TraceWarning(string.Format(Strings.ERR_INIT_IDENTITY_PROPS, Environment.NewLine, this.Name, ex.ToString()));
            }
        }