Example #1
0
 /// <summary>
 /// Initializes a new instance
 /// </summary>
 /// <param name="parent"></param>
 /// <param name="source"></param>
 /// <param name="ldf"></param>
 /// <param name="suppressErrors"></param>
 protected internal RuntimeMapLayer(RuntimeMap parent, IBaseMapLayer source, ILayerDefinition ldf, bool suppressErrors)
     : this(parent, ldf, suppressErrors)
 {
     Check.ArgumentNotNull(source, nameof(source));
     Check.ArgumentNotNull(ldf, nameof(ldf));
     Check.ThatPreconditionIsMet(source.ResourceId == ldf.ResourceID, $"{nameof(source)}.{nameof(source.ResourceId)} == {nameof(ldf)}.{nameof(ldf.ResourceID)}");
 }
Example #2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RuntimeMapLayer"/> class.
 /// </summary>
 /// <param name="parent">The parent.</param>
 /// <param name="ldf">The Layer Definition.</param>
 /// <param name="suppressErrors">If true, any errors while creating the layer are suppressed. The nature of the error may result in un-selectable layers</param>
 protected internal RuntimeMapLayer(RuntimeMap parent, ILayerDefinition ldf, bool suppressErrors)
     : this(parent)
 {
     _disableChangeTracking = true;
     Initialize(ldf, suppressErrors);
     _disableChangeTracking = false;
 }
        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);
        }
        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;
        }
        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);
        }
Example #6
0
            /// <summary>
            /// Gets the name of the active spatial context used by the given layer definition
            /// </summary>
            /// <param name="ldf">The layer definition</param>
            /// <param name="conn">The server connection</param>
            /// <returns>The name of the active spatial context</returns>
            public static string GetLayerSpatialContextName(this ILayerDefinition ldf, IServerConnection conn)
            {
                var rl = ldf.SubLayer as IRasterLayerDefinition;
                var vl = ldf.SubLayer as IVectorLayerDefinition;

                if (vl != null)
                {
                    var cls = conn.FeatureService.GetClassDefinition(vl.ResourceId, vl.FeatureName);
                    var gp  = cls.FindProperty(vl.Geometry) as GeometricPropertyDefinition;
                    if (gp != null)
                    {
                        return(gp.SpatialContextAssociation);
                    }
                }
                else if (rl != null)
                {
                    var cls = conn.FeatureService.GetClassDefinition(rl.ResourceId, rl.FeatureName);
                    var rp  = cls.FindProperty(rl.Geometry) as RasterPropertyDefinition;
                    if (rp != null)
                    {
                        return(rp.SpatialContextAssociation);
                    }
                }
                return(null);
            }
Example #7
0
        public ExplodeThemeDialog(IEditorService editor, IVectorScaleRange parentRange, IVectorStyle style, ILayerDefinition parentLayer)
            : this()
        {
            if (style.StyleType == StyleType.Composite)
            {
                throw new NotSupportedException(Strings.ErrorExplodingCompositeStyleNotSupported);
            }

            _editor      = editor;
            _style       = style;
            _parentRange = parentRange;
            _parentLayer = parentLayer;

            txtLayersCreate.Text    = style.RuleCount.ToString(CultureInfo.InvariantCulture);
            txtLayerNameFormat.Text = "{0} - {1} - {2}"; //NOXLATE
            EvaluateStates();

            if (!_editor.IsNew)
            {
                txtLayerPrefix.Text = ResourceIdentifier.GetName(_editor.ResourceID);
            }
            else
            {
                txtLayerPrefix.Text = "Theme"; //NOXLATE
            }
        }
        private IMapDefinition CreateLayerPreviewMapDefinition(ILayerDefinition ldf, string sessionId, string layerName, IServerConnection conn)
        {
            //Create temp map definition to house our current layer
            var    mdfId = $"Session:{sessionId}//{Guid.NewGuid()}.MapDefinition"; //NOXLATE
            string csWkt;
            var    extent = ldf.GetSpatialExtent(_conn, true, out csWkt);

            if (extent == null)
            {
                throw new ApplicationException(Strings.FailedToCalculateFeatureSourceExtents);
            }

            string layerSc = ldf.GetLayerSpatialContextName(_conn);

            //TODO: Based on the visible scales in this layer, size this extents accordingly
            var             mdf  = Utility.CreateMapDefinition(conn, Strings.PreviewMap, csWkt, extent);
            IMapDefinition2 mdf2 = mdf as IMapDefinition2;

            if (mdf2 != null && this.AddDebugWatermark)
            {
                CreateDebugWatermark(mdf2, conn, layerSc);
            }

            var layer = mdf.AddLayer(null, layerName, ldf.ResourceID);

            conn.ResourceService.SaveResourceAs(mdf, mdfId);
            mdf.ResourceID = mdfId;
            return(mdf);
        }
Example #9
0
        /// <summary>
        /// Initializes a new instance
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="source"></param>
        /// <param name="ldf"></param>
        /// <param name="suppressErrors"></param>
        protected internal RuntimeMapLayer(RuntimeMap parent, IMapLayer source, ILayerDefinition ldf, bool suppressErrors)
            : this(parent, (IBaseMapLayer)source, ldf, suppressErrors)
        {
            _disableChangeTracking = true;

            this.Group = source.Group;
            _visible   = source.Visible;

            _disableChangeTracking = false;
        }
Example #10
0
        public VectorScaleRangeGrid(IVectorScaleRange vsr, VectorLayerStyleSectionCtrl parent)
            : this()
        {
            try
            {
                _init        = true;
                _parent      = parent;
                _editedLayer = (ILayerDefinition)_parent.EditorService.GetEditedResource();
                _vsr         = vsr;
                _pts         = _vsr.PointStyle;
                _lts         = _vsr.LineStyle;
                _ats         = _vsr.AreaStyle;

                chkPoints.Checked = (_pts != null);
                chkLine.Checked   = (_lts != null);
                chkArea.Checked   = (_ats != null);

                var vsr2 = _vsr as IVectorScaleRange2;
                if (vsr2 != null)
                {
                    _cts = new BindingList <ICompositeTypeStyle>();
                    if (chkArea.Checked || chkLine.Checked || chkArea.Checked)
                    {
                        chkComposite.Checked = false;
                    }
                    else
                    {
                        foreach (var r in vsr2.CompositeStyle)
                        {
                            _cts.Add(r);
                        }
                        chkComposite.Checked = (vsr2.CompositeStyleCount > 0);
                    }
                }
                else
                {
                    chkComposite.Visible = false;
                    SetCompositeTabVisibility(false);
                }

                SetPointUI();
                SetLineUI();
                SetAreaUI();
                SetCompositeUI();

                pointRuleGrid.Init(_parent.EditorService, _vsr, _vsr.PointStyle);
                lineRuleGrid.Init(_parent.EditorService, _vsr, _vsr.LineStyle);
                areaRuleGrid.Init(_parent.EditorService, _vsr, _vsr.AreaStyle);
            }
            finally
            {
                _init = false;
            }
        }
Example #11
0
        public void Init(IEditorService edSvc, IVectorScaleRange parentRange, IVectorStyle style)
        {
            try
            {
                _init  = true;
                _edSvc = edSvc;
                _style = style;
                var p2 = style as IPointVectorStyle2;
                var l2 = style as ILineVectorStyle2;
                var a2 = style as IAreaVectorStyle2;
                var c2 = style as ICompositeTypeStyle2;
                btnShowInLegend.Visible = !(p2 == null && l2 == null && a2 == null && c2 == null);
                if (btnShowInLegend.Visible)
                {
                    if (p2 != null)
                    {
                        btnShowInLegend.Checked = p2.ShowInLegend;
                    }
                    else if (l2 != null)
                    {
                        btnShowInLegend.Checked = l2.ShowInLegend;
                    }
                    else if (a2 != null)
                    {
                        btnShowInLegend.Checked = a2.ShowInLegend;
                    }
                    else if (c2 != null)
                    {
                        btnShowInLegend.Checked = c2.ShowInLegend;
                    }
                }

                var pts = style as IPointVectorStyle;
                if (pts != null)
                {
                    btnAllowOverpost.Checked = pts.AllowOverpost;
                    btnDisplayAsText.Checked = pts.DisplayAsText;
                }
                else
                {
                    btnAllowOverpost.Visible     =
                        btnDisplayAsText.Visible = false;
                }

                InitGrid(style is ICompositeTypeStyle);
                _editedLayer      = (ILayerDefinition)_edSvc.GetEditedResource();
                _parentScaleRange = parentRange;
                ReSyncRulesToBindingList(style);
            }
            finally
            {
                _init = false;
            }
        }
Example #12
0
        public VectorScaleRangeGrid(IVectorScaleRange vsr, VectorLayerStyleSectionCtrl parent)
            : this()
        {
            try
            {
                _init = true;
                _parent = parent;
                _editedLayer = (ILayerDefinition)_parent.EditorService.GetEditedResource();
                _vsr = vsr;
                _pts = _vsr.PointStyle;
                _lts = _vsr.LineStyle;
                _ats = _vsr.AreaStyle;

                chkPoints.Checked = (_pts != null);
                chkLine.Checked = (_lts != null);
                chkArea.Checked = (_ats != null);

                var vsr2 = _vsr as IVectorScaleRange2;
                if (vsr2 != null)
                {
                    _cts = new BindingList<ICompositeTypeStyle>();
                    if (chkArea.Checked || chkLine.Checked || chkArea.Checked)
                    {
                        chkComposite.Checked = false;
                    }
                    else
                    {
                        foreach (var r in vsr2.CompositeStyle)
                        {
                            _cts.Add(r);
                        }
                        chkComposite.Checked = (vsr2.CompositeStyleCount > 0);
                    }
                }
                else
                {
                    chkComposite.Visible = false;
                    SetCompositeTabVisibility(false);
                }

                SetPointUI();
                SetLineUI();
                SetAreaUI();
                SetCompositeUI();

                pointRuleGrid.Init(_parent.EditorService, _vsr, _vsr.PointStyle);
                lineRuleGrid.Init(_parent.EditorService, _vsr, _vsr.LineStyle);
                areaRuleGrid.Init(_parent.EditorService, _vsr, _vsr.AreaStyle);
            }
            finally
            {
                _init = false;
            }
        }
Example #13
0
        public ThemeCreator(IEditorService editor, ILayerDefinition layer, ClassDefinition schema, object ruleCollection)
            : this()
        {
            m_editor = editor;
            m_layer = layer;
            m_featureClass = schema;
            m_ruleCollection = ruleCollection;

            _factory = (ILayerElementFactory2)editor.GetEditedResource();

            ColorBrewerColorSet.SetCustomRender(new CustomCombo.RenderCustomItem(DrawColorSetPreview));
        }
        /// <summary>
        /// Gets the coordinate system WKT.
        /// </summary>
        /// <param name="layer">The layer.</param>
        /// <returns></returns>
        public static string GetCoordinateSystemWkt(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;

            switch (layer.SubLayer.LayerType)
            {
            case LayerType.Raster:
            {
                var rl     = (IRasterLayerDefinition)layer.SubLayer;
                var fs     = (IFeatureSource)conn.ResourceService.GetResource(rl.ResourceId);
                var scList = fs.GetSpatialInfo(true);
                if (scList.SpatialContext.Count > 0)
                {
                    return(scList.SpatialContext[0].CoordinateSystemWkt);
                }
            }
            break;

            case LayerType.Vector:
            {
                var vl     = (IVectorLayerDefinition)layer.SubLayer;
                var fs     = (IFeatureSource)conn.ResourceService.GetResource(vl.ResourceId);
                var scList = fs.GetSpatialInfo(true);
                if (scList.SpatialContext.Count > 0)
                {
                    return(scList.SpatialContext[0].CoordinateSystemWkt);
                }
            }
            break;

            case LayerType.Drawing:
            {
                int[] services = conn.Capabilities.SupportedServices;
                if (Array.IndexOf(services, (int)ServiceType.Drawing) >= 0)
                {
                    var sheet = ((IDrawingLayerDefinition)layer.SubLayer).Sheet;
                    var dws   = (IDrawingSource)conn.ResourceService.GetResource(((IDrawingLayerDefinition)layer.SubLayer).ResourceId);

                    //This should already be WKT form
                    return(dws.CoordinateSpace);
                }
            }
            break;
            }
            return(string.Empty);
        }
Example #15
0
        /// <summary>
        /// Initializes this instances from the specified Layer Definition
        /// </summary>
        /// <param name="ldf"></param>
        /// <param name="suppressErrors"></param>
        protected void Initialize(ILayerDefinition ldf, bool suppressErrors)
        {
            Check.ArgumentNotNull(ldf, nameof(ldf));
            this.LayerDefinitionID = ldf.ResourceID;
            switch (ldf.SubLayer.LayerType)
            {
            case LayerType.Vector:
            {
                var vl = ((IVectorLayerDefinition)ldf.SubLayer);
                _qualifiedClassName   = vl.FeatureName;
                _geometryPropertyName = vl.Geometry;
                _featureSourceId      = vl.ResourceId;
                _filter = vl.Filter;
                InitIdentityProperties(vl, suppressErrors);
                InitScaleRanges(vl);
                _hasTooltips = !string.IsNullOrEmpty(vl.ToolTip);
            }
            break;

            case LayerType.Raster:
            {
                var rl = ((IRasterLayerDefinition)ldf.SubLayer);
                _qualifiedClassName   = rl.FeatureName;
                _geometryPropertyName = rl.Geometry;
                _featureSourceId      = rl.ResourceId;
                InitScaleRanges(rl);
            }
            break;

            case LayerType.Drawing:
            {
                _featureSourceId = ldf.SubLayer.ResourceId;
                var dl = ((IDrawingLayerDefinition)ldf.SubLayer);
                _scaleRanges = new double[]
                {
                    dl.MinScale,
                    dl.MaxScale
                };
                EnsureOrderedMinMaxScales();
            }
            break;
            }

            _expandInLegend = false;
            this.Name       = ResourceIdentifier.GetName(ldf.ResourceID);
            _legendLabel    = this.Name;
            _selectable     = true;
            _showInLegend   = true;
            _visible        = true;
        }
        /// <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);
            }
        }
Example #17
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);
        }
 private void OnMapLayerAdded(object sender, RuntimeMapLayer layer)
 {
     if (_bComputeLayerCsAndExtentOnFirstLayerAdded && _mapEditor.Map.Layers.Count == 1)
     {
         Debug.WriteLine("Computing map extents and CS based on first layer added");
         try
         {
             ILayerDefinition layerDef = (ILayerDefinition)_conn.ResourceService.GetResource(layer.LayerDefinitionID);
             string           wkt;
             IEnvelope        env = layerDef.GetSpatialExtent(_conn, true, out wkt);
             if (SupportsMutableMapProperties(_mapEditor.Map))
             {
                 _mapEditor.Map.MapExtent        = env;
                 _mapEditor.Map.CoordinateSystem = wkt;
                 if (CsHelper.DefaultCalculator != null)
                 {
                     _mapEditor.Map.MetersPerUnit = CsHelper.DefaultCalculator.Calculate(wkt, 1.0);
                 }
                 else
                 {
                     var calc = _mapEditor.Map.CurrentConnection.GetCalculator();
                     _mapEditor.Map.MetersPerUnit = calc.Calculate(wkt, 1.0);
                 }
                 _mapEditor.ReloadViewer();
             }
             else
             {
                 //We have to tear down the current runtime map, update the shadow copy
                 //map definition and then rebuild a new runtime map
                 _mapEditor.SyncMap();
                 IMapDefinition mdf = _mapEditor.GetMapDefinition();
                 mdf.Extents          = env;
                 mdf.CoordinateSystem = wkt;
                 CleanupExistingMap();
                 //If local, we'd be rebuilding off of the resource ID and not its in-memory
                 //object representation so flush
                 _mapEditor.EditorService.SyncSessionCopy();
                 _mapEditor.RebuildRuntimeMap();
                 _mapEditor.ReloadViewer();
             }
             Debug.WriteLine("Computed map extents and CS");
         }
         catch (Exception ex)
         {
             Debug.WriteLine("Uh-Oh: " + ex.ToString());
         }
     }
 }
Example #19
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);
                }
            }
        internal static ImagePreviewResult GenerateSymbolDefinitionPreview(IServerConnection conn, IResource previewCopy, int width, int height)
        {
            //For Symbol Definition previews, we make a placeholder Layer Definition with the
            ILayerDefinition        layerDef = Utility.CreateDefaultLayer(conn, LayerType.Vector);
            IVectorLayerDefinition2 vl       = layerDef.SubLayer as IVectorLayerDefinition2;

            if (vl != null)
            {
                //HACK-ish: We are flubbing a completely invalid Layer Definition under normal circumstances,
                //but one that has the minimum required content model to generate an appropriate GETLEGENDIMAGE preview for
                vl.FeatureName = string.Empty;
                vl.ResourceId  = string.Empty;
                vl.Geometry    = string.Empty;
                vl.ToolTip     = string.Empty;
                var vsr = vl.GetScaleRangeAt(0) as IVectorScaleRange2;
                if (vsr != null)
                {
                    vsr.AreaStyle  = null;
                    vsr.LineStyle  = null;
                    vsr.PointStyle = null;
                    var cs   = layerDef.CreateDefaultCompositeStyle();
                    var cr   = cs.GetRuleAt(0);
                    var csym = cr.CompositeSymbolization;
                    var si   = csym.CreateSymbolReference(previewCopy.ResourceID);
                    csym.AddSymbolInstance(si);
                    vsr.CompositeStyle = new List <ICompositeTypeStyle>()
                    {
                        cs
                    };

                    var ldfId = "Session:" + conn.SessionID + "//SymbolDefinitionPreview" + Guid.NewGuid() + ".LayerDefinition"; //NOXLATE
                    conn.ResourceService.SaveResourceAs(layerDef, ldfId);

                    var mappingSvc = (IMappingService)conn.GetService((int)ServiceType.Mapping);
                    var img        = mappingSvc.GetLegendImage(42, ldfId, 0, 4, width, height, "PNG"); //NOXLATE
                    return(new ImagePreviewResult()
                    {
                        ImagePreview = img
                    });
                }
            }
            return(null);
        }
Example #21
0
        /// <summary>
        /// Binds the specified resource to this control. This effectively initializes
        /// all the fields in this control and sets up databinding on all fields. All
        /// subclasses *must* override this method.
        ///
        /// Also note that this method may be called more than once (e.g. Returning from
        /// and XML edit of this resource). Thus subclasses must take this scenario into
        /// account when implementing
        /// </summary>
        /// <param name="service">The editor service</param>
        protected override void Bind(Maestro.Editors.IEditorService service)
        {
            if (!_init)
            {
                _edsvc = service;
                _res   = service.GetEditedResource() as ILayerDefinition;
                Debug.Assert(_res != null);
                _init = true;
            }

            panelBody.Controls.Clear();

            var vl = _res.SubLayer as IVectorLayerDefinition;
            var gl = _res.SubLayer as IRasterLayerDefinition;
            var dl = _res.SubLayer as IDrawingLayerDefinition;

            if (vl != null)
            {
                var ed = new VectorLayerEditorCtrl();
                ed.Bind(service);
                ed.Dock = DockStyle.Fill;
                panelBody.Controls.Add(ed);
            }
            else if (gl != null)
            {
                var ed = new RasterLayerEditorCtrl();
                ed.Bind(service);
                ed.Dock = DockStyle.Fill;
                panelBody.Controls.Add(ed);
            }
            else if (dl != null)
            {
                var ed = new DrawingLayerEditorCtrl();
                ed.Bind(service);
                ed.Dock = DockStyle.Fill;
                panelBody.Controls.Add(ed);
            }
            else
            {
                throw new NotSupportedException(Strings.LayerSubTypeNotSupported);
            }
        }
Example #22
0
        protected override void Bind(Maestro.Editors.IEditorService service)
        {
            if (!_init)
            {
                _edsvc = service;
                _res = service.GetEditedResource() as ILayerDefinition;
                Debug.Assert(_res != null);
                _init = true;
            }

            panelBody.Controls.Clear();

            var vl = _res.SubLayer as IVectorLayerDefinition;
            var gl = _res.SubLayer as IRasterLayerDefinition;
            var dl = _res.SubLayer as IDrawingLayerDefinition;
            if (vl != null)
            {
                var ed = new VectorLayerEditorCtrl();
                ed.Bind(service);
                ed.Dock = DockStyle.Fill;
                panelBody.Controls.Add(ed);
            }
            else if (gl != null)
            {
                var ed = new RasterLayerEditorCtrl();
                ed.Bind(service);
                ed.Dock = DockStyle.Fill;
                panelBody.Controls.Add(ed);
            }
            else if (dl != null)
            {
                var ed = new DrawingLayerEditorCtrl();
                ed.Bind(service);
                ed.Dock = DockStyle.Fill;
                panelBody.Controls.Add(ed);
            }
            else
            {
                throw new NotSupportedException(Strings.LayerSubTypeNotSupported);
            }
        }
Example #23
0
        public ExplodeThemeDialog(IEditorService editor, IVectorScaleRange parentRange, IVectorStyle style, ILayerDefinition parentLayer)
            : this()
        {
            if (style.StyleType == StyleType.Composite)
                throw new NotSupportedException(Strings.ErrorExplodingCompositeStyleNotSupported);

            _editor = editor;
            _style = style;
            _parentRange = parentRange;
            _parentLayer = parentLayer;

            txtLayersCreate.Text = style.RuleCount.ToString(CultureInfo.InvariantCulture);
            txtLayerNameFormat.Text = "{0} - {1} - {2}"; //NOXLATE
            EvaluateStates();

            if (!_editor.IsNew)
            {
                txtLayerPrefix.Text = ResourceIdentifier.GetName(_editor.ResourceID);
            }
            else
            {
                txtLayerPrefix.Text = "Theme"; //NOXLATE
            }
        }
Example #24
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);
        }
Example #25
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 = ObjectFactory.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 = ObjectFactory.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
        }
Example #26
0
 private static string GetLayerSpatialContext(ILayerDefinition ldf)
 {
     var conn = ldf.CurrentConnection;
     var rl = ldf.SubLayer as IRasterLayerDefinition;
     var vl = ldf.SubLayer as IVectorLayerDefinition;
     if (vl != null)
     {
         var cls = conn.FeatureService.GetClassDefinition(vl.ResourceId, vl.FeatureName);
         var gp = cls.FindProperty(vl.Geometry) as GeometricPropertyDefinition;
         if (gp != null)
             return gp.SpatialContextAssociation;
     }
     else if (rl != null)
     {
         var cls = conn.FeatureService.GetClassDefinition(rl.ResourceId, rl.FeatureName);
         var rp = cls.FindProperty(rl.Geometry) as RasterPropertyDefinition;
         if (rp != null)
             return rp.SpatialContextAssociation;
     }
     return null;
 }
Example #27
0
        internal static IMapDefinition CreateLayerPreviewMapDefinition(ILayerDefinition ldf, string sessionId, string layerName, IServerConnection conn)
        {
            //Create temp map definition to house our current layer
            var mdfId = "Session:" + sessionId + "//" + Guid.NewGuid() + ".MapDefinition"; //NOXLATE
            string csWkt;
            var extent = ldf.GetSpatialExtent(true, out csWkt);
            if (extent == null)
                throw new ApplicationException(Strings.FailedToCalculateFeatureSourceExtents);

            string layerSc = GetLayerSpatialContext(ldf);

            //TODO: Based on the visible scales in this layer, size this extents accordingly
            var mdf = ObjectFactory.CreateMapDefinition(conn, Strings.PreviewMap, csWkt, extent);
            IMapDefinition2 mdf2 = mdf as IMapDefinition2;
            if (mdf2 != null && PreviewSettings.AddDebugWatermark)
                CreateDebugWatermark(mdf2, conn, layerSc);

            var layer = mdf.AddLayer(null, layerName, ldf.ResourceID);
            conn.ResourceService.SaveResourceAs(mdf, mdfId);
            mdf.ResourceID = mdfId;
            return mdf;
        }
Example #28
0
        /// <summary>
        /// Previews the given resource
        /// </summary>
        /// <param name="res"></param>
        /// <param name="edSvc"></param>
        /// <param name="locale"></param>
        public void Preview(IResource res, IEditorService edSvc, string locale)
        {
            IServerConnection conn = edSvc.CurrentConnection;

            if (this.UseLocal && IsLocalPreviewableType(res) && SupportsMappingService(conn))
            {
                BusyWaitDelegate worker = () =>
                {
                    IMappingService mapSvc     = (IMappingService)conn.GetService((int)ServiceType.Mapping);
                    IMapDefinition  previewMdf = null;
                    switch (res.ResourceType)
                    {
                    case "LayerDefinition":
                    {
                        ILayerDefinition ldf       = (ILayerDefinition)res;
                        string           layerName = string.Empty;
                        if (edSvc.IsNew)
                        {
                            layerName = ResourceIdentifier.GetName(ldf.SubLayer.ResourceId);
                        }
                        else
                        {
                            layerName = ResourceIdentifier.GetName(edSvc.ResourceID);
                        }
                        previewMdf = ResourcePreviewEngine.CreateLayerPreviewMapDefinition(ldf, edSvc.SessionID, layerName, conn);
                    }
                    break;

                    case "WatermarkDefinition":
                    {
                        previewMdf = Utility.CreateWatermarkPreviewMapDefinition((IWatermarkDefinition)res);
                    }
                    break;

                    case "MapDefinition":
                    {
                        previewMdf = (IMapDefinition)res;
                    }
                    break;
                    }

                    if (string.IsNullOrEmpty(previewMdf.ResourceID))
                    {
                        var sessionId = edSvc.SessionID;
                        var mdfId     = "Session:" + sessionId + "//" + Guid.NewGuid() + ".MapDefinition"; //NOXLATE

                        conn.ResourceService.SaveResourceAs(previewMdf, mdfId);
                        previewMdf.ResourceID = mdfId;
                    }

                    if (previewMdf != null)
                    {
                        return(mapSvc.CreateMap(previewMdf, false));
                    }
                    else
                    {
                        return(null);
                    }
                };
                Action <object, Exception> onComplete = (obj, ex) =>
                {
                    if (ex != null)
                    {
                        throw ex;
                    }

                    if (obj != null)
                    {
                        var rtMap = (RuntimeMap)obj;
                        if (_viewManager != null)
                        {
                            _viewManager.OpenContent(ViewRegion.Document, () => new MapPreviewViewContent(rtMap, _launcher, (edSvc.IsNew) ? null : edSvc.ResourceID));
                        }
                        else
                        {
                            var diag = new MapPreviewDialog(rtMap, _launcher, (edSvc.IsNew) ? null : edSvc.ResourceID);
                            diag.Show(null);
                        }
                    }
                    else //Fallback, shouldn't happen
                    {
                        _inner.Preview(res, edSvc, locale);
                    }
                };
                BusyWaitDialog.Run(Strings.PrgPreparingResourcePreview, worker, onComplete);
            }
            else
            {
                _inner.Preview(res, edSvc, locale);
            }
        }
Example #29
0
 /// <summary>
 /// Initializes a new instance
 /// </summary>
 /// <param name="parent"></param>
 /// <param name="source"></param>
 /// <param name="ldf"></param>
 /// <param name="suppressErrors"></param>
 protected internal RuntimeMapLayer(RuntimeMap parent, IBaseMapLayer source, ILayerDefinition ldf, bool suppressErrors)
     : this(parent, ldf, suppressErrors)
 {
     Check.NotNull(source, "source"); //NOXLATE
     Check.NotNull(ldf, "ldf"); //NOXLATE
     Check.Precondition(source.ResourceId == ldf.ResourceID, "source.ResourceId == ldf.ResourceID"); //NOXLATE
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            string agent = ConfigurationManager.AppSettings["MapAgentUrl"];

            IServerConnection conn = ConnectionProviderRegistry.CreateConnection(
                "Maestro.Http",
                "Url", agent,
                "SessionId", Request.Params["SESSION"]);

            IMappingService mpSvc   = (IMappingService)conn.GetService((int)ServiceType.Mapping);
            string          rtMapId = "Session:" + conn.SessionID + "//" + Request.Params["MAPNAME"] + ".Map";

            RuntimeMap rtMap = mpSvc.OpenMap(rtMapId);

            RuntimeMapLayer parcels = rtMap.Layers["Parcels"];

            if (parcels != null)
            {
                rtMap.Layers.Remove(parcels);

                rtMap.Save();

                Page.ClientScript.RegisterStartupScript(
                    this.GetType(),
                    "load",
                    "<script type=\"text/javascript\"> window.onload = function() { parent.parent.Refresh(); } </script>");

                lblMessage.Text = "Parcels layer removed";
            }
            else
            {
                string          groupName = "Municipal";
                RuntimeMapGroup group     = rtMap.Groups[groupName];
                if (group == null)
                {
                    group = mpSvc.CreateMapGroup(rtMap, groupName);
                    rtMap.Groups.Add(group);
                    throw new Exception("Layer group not found");
                }

                ILayerDefinition layerDef = (ILayerDefinition)conn.ResourceService.GetResource("Library://Samples/Sheboygan/Layers/Parcels.LayerDefinition");
                RuntimeMapLayer  layer    = mpSvc.CreateMapLayer(rtMap, layerDef);

                layer.Group          = group.Name;
                layer.LegendLabel    = "Parcels";
                layer.ShowInLegend   = true;
                layer.ExpandInLegend = true;
                layer.Selectable     = true;
                layer.Visible        = true;

                //Set it to be drawn above islands.
                //In terms of draw order, it goes [0...n] -> [TopMost ... Bottom]
                //So for a layer to be drawn above something else, its draw order must be
                //less than that particular layer.

                int index = rtMap.Layers.IndexOf("Islands");
                rtMap.Layers.Insert(index, layer);

                rtMap.Save();

                Page.ClientScript.RegisterStartupScript(
                    this.GetType(),
                    "load",
                    "<script type=\"text/javascript\"> window.onload = function() { parent.parent.Refresh(); } </script>");

                lblMessage.Text = "Parcels layer added again";
            }

            rtMap = mpSvc.OpenMap(rtMapId);
            DumpMap(rtMap);
        }
Example #31
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());
        }
Example #32
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>
        /// Returns the spatial extent of the data.
        /// This is calculated by asking the underlying featuresource for the minimum rectangle that
        /// contains all the features in the specified table. If the <paramref name="allowFallbackToContextInformation"/>
        /// is set to true, and the query fails, the code will attempt to read this information
        /// from the spatial context information instead.
        /// </summary>
        /// <param name="layer">The layer definition</param>
        /// <param name="allowFallbackToContextInformation">If true, will default to the extents of the active spatial context.</param>
        /// <param name="csWkt">The coordinate system WKT that this extent corresponds to</param>
        /// <returns></returns>
        public static IEnvelope GetSpatialExtent(this ILayerDefinition layer, bool allowFallbackToContextInformation, out string csWkt)
        {
            csWkt = null;
            Check.NotNull(layer, "layer"); //NOXLATE
            if (layer.CurrentConnection == null)
            {
                throw new System.Exception(OSGeo.MapGuide.MaestroAPI.Strings.ErrorNoServerConnectionAttached);
            }

            var conn = layer.CurrentConnection;

            switch (layer.SubLayer.LayerType)
            {
            case LayerType.Vector:
            {
                IEnvelope          env      = null;
                IFdoSpatialContext activeSc = null;
                try
                {
                    activeSc = layer.GetSpatialContext();
                    if (activeSc != null)
                    {
                        //TODO: Check if ones like SQL Server will return the WKT, otherwise we'll need to bring in the
                        //CS catalog to do CS code to WKT conversion.
                        csWkt = activeSc.CoordinateSystemWkt;
                    }

                    //This can fail if SpatialExtents() aggregate function is not supported
                    env = conn.FeatureService.GetSpatialExtent(layer.SubLayer.ResourceId, ((IVectorLayerDefinition)layer.SubLayer).FeatureName, ((IVectorLayerDefinition)layer.SubLayer).Geometry);
                    return(env);
                }
                catch
                {
                    //Which in that case, default to extents of active spatial context
                    if (activeSc != null && activeSc.Extent != null)
                    {
                        return(activeSc.Extent.Clone());
                    }
                    else
                    {
                        return(null);
                    }
                }
            }

            case LayerType.Raster:
            {
                IEnvelope          env      = null;
                IFdoSpatialContext activeSc = null;
                try
                {
                    var scList = conn.FeatureService.GetSpatialContextInfo(layer.SubLayer.ResourceId, true);
                    if (scList.SpatialContext.Count > 0)
                    {
                        activeSc = scList.SpatialContext[0];
                    }

                    //TODO: Would any raster provider *not* return a WKT?
                    csWkt = activeSc.CoordinateSystemWkt;

                    //Can fail if SpatialExtents() aggregate function is not supported
                    env = conn.FeatureService.GetSpatialExtent(layer.SubLayer.ResourceId, ((IRasterLayerDefinition)layer.SubLayer).FeatureName, ((IRasterLayerDefinition)layer.SubLayer).Geometry);
                    return(env);
                }
                catch         //Default to extents of active spatial context
                {
                    if (activeSc != null && activeSc.Extent != null)
                    {
                        return(activeSc.Extent.Clone());
                    }
                    else
                    {
                        return(null);
                    }
                }
            }

            default:
            {
                int[] services = conn.Capabilities.SupportedServices;
                if (Array.IndexOf(services, (int)ServiceType.Drawing) >= 0)
                {
                    var sheet = ((IDrawingLayerDefinition)layer.SubLayer).Sheet;
                    var dws   = (IDrawingSource)conn.ResourceService.GetResource(((IDrawingLayerDefinition)layer.SubLayer).ResourceId);

                    if (dws.Sheet != null)
                    {
                        //find matching sheet
                        foreach (var sht in dws.Sheet)
                        {
                            if (sheet.Equals(sht.Name))
                            {
                                csWkt = dws.CoordinateSpace;
                                return(ObjectFactory.CreateEnvelope(sht.Extent.MinX, sht.Extent.MinY, sht.Extent.MaxX, sht.Extent.MaxY));
                            }
                        }
                    }
                }
                return(null);
            }
            }
        }
Example #35
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RuntimeMapLayer"/> class.
 /// </summary>
 /// <param name="parent">The parent.</param>
 /// <param name="ldf">The Layer Definition.</param>
 /// <param name="suppressErrors">If true, any errors while creating the layer are suppressed. The nature of the error may result in un-selectable layers</param>
 protected internal RuntimeMapLayer(RuntimeMap parent, ILayerDefinition ldf, bool suppressErrors)
     : this(parent)
 {
     _disableChangeTracking = true;
     Initialize(ldf, suppressErrors);
     _disableChangeTracking = false;
 }
Example #36
0
        /// <summary>
        /// Initializes a new instance
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="source"></param>
        /// <param name="ldf"></param>
        /// <param name="suppressErrors"></param>
        protected internal RuntimeMapLayer(RuntimeMap parent, IMapLayer source, ILayerDefinition ldf, bool suppressErrors)
            : this(parent, (IBaseMapLayer)source, ldf, suppressErrors)
        {
            _disableChangeTracking = true;

            this.Group = source.Group;
            _visible = source.Visible;

            _disableChangeTracking = false;
        }
Example #37
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string agent = ConfigurationManager.AppSettings["MapAgentUrl"];

            IServerConnection conn = ConnectionProviderRegistry.CreateConnection(
                "Maestro.Http",
                "Url", agent,
                "SessionId", Request.Params["SESSION"]);

            IMappingService mpSvc   = (IMappingService)conn.GetService((int)ServiceType.Mapping);
            string          rtMapId = "Session:" + conn.SessionID + "//" + Request.Params["MAPNAME"] + ".Map";

            RuntimeMap rtMap = mpSvc.OpenMap(rtMapId);

            RuntimeMapLayer tracks = rtMap.Layers["ThemedDistricts"];

            if (tracks != null)
            {
                lblMessage.Text = "Themed districts layer already added";
            }
            else
            {
                //Add our themed districts layer

                //Our Feature Source
                string fsId = "Library://Samples/Sheboygan/Data/VotingDistricts.FeatureSource";

                //The place we'll store the layer definition
                string layerId = "Session:" + conn.SessionID + "//ThemedVotingDistricts.LayerDefinition";

                CreateDistrictsLayer(conn, fsId, layerId);

                ILayerDefinition layerDef = (ILayerDefinition)conn.ResourceService.GetResource(layerId);
                RuntimeMapLayer  layer    = mpSvc.CreateMapLayer(rtMap, layerDef);

                layer.Name           = "ThemedDistricts";
                layer.Group          = "";
                layer.LegendLabel    = "Themed Districts";
                layer.ShowInLegend   = true;
                layer.ExpandInLegend = true;
                layer.Selectable     = true;
                layer.Visible        = true;

                //Set it to be drawn above districts.
                //In terms of draw order, it goes [0...n] -> [TopMost ... Bottom]
                //So for a layer to be drawn above something else, its draw order must be
                //less than that particular layer.

                int index = rtMap.Layers.IndexOf("Districts");
                rtMap.Layers.Insert(index, layer);

                rtMap.Save();

                Page.ClientScript.RegisterStartupScript(
                    this.GetType(),
                    "load",
                    "<script type=\"text/javascript\"> window.onload = function() { parent.parent.Refresh(); } </script>");

                lblMessage.Text = "Themed districts layer added";
            }

            rtMap = mpSvc.OpenMap(rtMapId);
            DumpMap(rtMap);
        }
Example #38
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
        }
Example #39
0
        private void ProfileMapDefinition(IMapDefinition mapDef)
        {
            //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
            var mdef = (IMapDefinition)mapDef.Clone();

            if (backgroundWorker.CancellationPending)
            {
                return;
            }

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

            backgroundWorker.ReportProgress(0, (string.Format(Strings.Prof_LogMessageMapDefinition, resourceId)));

            using (new Timer(Strings.Prof_LogMessageRuntimeMap, backgroundWorker))
            {
                foreach (var ml in mdef.MapLayer)
                {
                    try
                    {
                        if (backgroundWorker.CancellationPending)
                        {
                            return;
                        }

                        ILayerDefinition ldef = (ILayerDefinition)m_connection.ResourceService.GetResource(ml.ResourceId);
                        ProfileLayerDefinition(ldef);
                    }
                    catch (Exception ex)
                    {
                        //string msg = NestedExceptionMessageProcessor.GetFullMessage(ex);
                        backgroundWorker.ReportProgress(0, (string.Format(Strings.Prof_LayerDefinitionProfilingError, ml.ResourceId, ex.ToString(), Environment.NewLine)));
                    }
                }

                if (mdef.BaseMap != null)
                {
                    foreach (var g in mdef.BaseMap.BaseMapLayerGroups)
                    {
                        if (g.BaseMapLayer != null)
                        {
                            foreach (var ml in g.BaseMapLayer)
                            {
                                try
                                {
                                    if (backgroundWorker.CancellationPending)
                                    {
                                        return;
                                    }

                                    ILayerDefinition ldef = (ILayerDefinition)m_connection.ResourceService.GetResource(ml.ResourceId);
                                    ProfileLayerDefinition(ldef);
                                }
                                catch (Exception ex)
                                {
                                    //string msg = NestedExceptionMessageProcessor.GetFullMessage(ex);
                                    backgroundWorker.ReportProgress(0, (string.Format(Strings.Prof_LayerDefinitionProfilingError, ml.ResourceId, ex.ToString(), Environment.NewLine)));
                                }
                            }
                        }
                    }
                }
            }

            if (backgroundWorker.CancellationPending)
            {
                return;
            }

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

            try
            {
                if (backgroundWorker.CancellationPending)
                {
                    return;
                }

                //m_connection.ResetFeatureSourceSchemaCache();
                using (new Timer(Strings.Prof_LogMessageRuntimeMapTotal, backgroundWorker))
                    mpsvc.CreateMap(mdef);
            }
            catch (Exception ex)
            {
                //string msg = NestedExceptionMessageProcessor.GetFullMessage(ex);
                backgroundWorker.ReportProgress(0, (string.Format(Strings.Prof_RuntimeMapProfilingError, resourceId, ex.ToString(), Environment.NewLine)));
            }

            try
            {
                if (backgroundWorker.CancellationPending)
                {
                    return;
                }

                //We cannot flub this anymore. AIMS 2012 demands the Map Definition id specified checks out
                mdef.ResourceID = "Session:" + m_connection.SessionID + "//ProfilingTest.MapDefinition"; //NOXLATE
                m_connection.ResourceService.SaveResource(mdef);

                var rtmap = mpsvc.CreateMap(mdef);

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

                rtmap.Save();

                using (new Timer(Strings.Prof_LogMessageRenderingMap, backgroundWorker))
                {
                    //TODO: Use extents rather than scale
                    //using (System.IO.Stream s = m_connection.RenderRuntimeMap(tmp2, mdef.Extents, 1024, 800, 96))
                    using (System.IO.Stream s = mpsvc.RenderRuntimeMap(rtmap, ((mdef.Extents.MaxX - mdef.Extents.MinX) / 2) + mdef.Extents.MinX, ((mdef.Extents.MaxY - mdef.Extents.MinY) / 2) + mdef.Extents.MinY, 50000, 1024, 800, 96))
                    {
                        //Just dispose it after being read
                        backgroundWorker.ReportProgress(0, (string.Format(Strings.Prof_MapRenderingImageSize, s.Length)));
                    }
                }
            }
            catch (Exception ex)
            {
                //string msg = NestedExceptionMessageProcessor.GetFullMessage(ex);
                backgroundWorker.ReportProgress(0, (string.Format(Strings.Prof_MapRenderingError, resourceId, ex.ToString(), Environment.NewLine)));
            }
        }
        private void AutoGenerateWMSBounds_Click(object sender, EventArgs e)
        {
            try
            {
                m_isUpdating = true;
                string srs        = "EPSG:????"; //NOXLATE
                string bounds     = WMSBounds.Text;
                bool   warnedEPSG = false;

                try
                {
                    if (!string.IsNullOrEmpty(bounds))
                    {
                        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                        if (bounds.Trim().StartsWith("&lt;")) //NOXLATE
                        {
                            bounds = System.Web.HttpUtility.HtmlDecode(bounds);
                        }
                        bounds = "<root>" + bounds + "</root>";               //NOXLATE
                        doc.LoadXml(bounds);
                        System.Xml.XmlNode root = doc["root"];                //NOXLATE
                        if (root["Bounds"] != null)                           //NOXLATE
                        {
                            if (root["Bounds"].Attributes["SRS"] != null)     //NOXLATE
                            {
                                srs = root["Bounds"].Attributes["SRS"].Value; //NOXLATE
                            }
                        }
                        else
                        {
                            throw new Exception(Strings.ResProp_MissingBoundsError);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string msg = NestedExceptionMessageProcessor.GetFullMessage(ex);
                    warnedEPSG = true;
                    MessageBox.Show(this, string.Format(Strings.ResProp_BoundsDecodeError, msg), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                System.Globalization.CultureInfo ic = System.Globalization.CultureInfo.InvariantCulture;
                ILayerDefinition ldef = (ILayerDefinition)m_connection.ResourceService.GetResource(m_resourceId);
                string           csWkt;
                var env  = ldef.GetSpatialExtent(m_connection, true, out csWkt);
                var epsg = m_connection.CoordinateSystemCatalog.ConvertWktToEpsgCode(csWkt);
                if (!string.IsNullOrEmpty(epsg) && epsg != "0")
                {
                    if (epsg != "4326")
                    {
                        var targetWkt = m_connection.CoordinateSystemCatalog.ConvertEpsgCodeToWkt("4326"); //NOXLATE
                        env  = Utility.TransformEnvelope(env, csWkt, targetWkt);
                        epsg = "4326";
                    }

                    srs = $"EPSG:{epsg}";
                }

                //TODO: Convert to lon/lat

                bounds  = $"<Bounds west=\"{env.MinX.ToString(ic)}\" east=\"{env.MaxX.ToString(ic)}\" south=\"{env.MinY.ToString(ic)}\" north=\"{env.MaxY.ToString(ic)}\" "; //NOXLATE
                bounds += $" SRS=\"{srs}\"";                                                                                                                                 //NOXLATE
                bounds += " />";                                                                                                                                             //NOXLATE

                m_isUpdating   = false;
                WMSBounds.Text = bounds;

                if ((srs == string.Empty || srs == "EPSG:????") && !warnedEPSG) //NOXLATE
                {
                    MessageBox.Show(this, Strings.ResProp_EpsgMissingWarning, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    WMSBounds.SelectionStart  = WMSBounds.Text.IndexOf("SRS=\"") + "SRS=\"".Length; //NOXLATE
                    WMSBounds.SelectionLength = WMSBounds.Text.IndexOf("\"", WMSBounds.SelectionStart) - WMSBounds.SelectionStart;
                    WMSBounds.ScrollToCaret();
                    WMSBounds.Focus();
                }
            }
            catch (Exception ex)
            {
                string msg = NestedExceptionMessageProcessor.GetFullMessage(ex);
                MessageBox.Show(this, string.Format(Strings.ResProp_WMSBoundsReadError, msg), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                m_isUpdating = false;
            }
        }
Example #41
0
        /// <summary>
        /// Initializes this instances from the specified Layer Definition
        /// </summary>
        /// <param name="ldf"></param>
        /// <param name="suppressErrors"></param>
        protected void Initialize(ILayerDefinition ldf, bool suppressErrors)
        {
            Check.NotNull(ldf, "ldf"); //NOXLATE
            this.LayerDefinitionID = ldf.ResourceID;
            if (ldf.SubLayer.LayerType == LayerType.Vector)
            {
                var vl = ((IVectorLayerDefinition)ldf.SubLayer);
                _qualifiedClassName = vl.FeatureName;
                _geometryPropertyName = vl.Geometry;
                _featureSourceId = vl.ResourceId;
                _filter = vl.Filter;
                InitIdentityProperties(vl, suppressErrors);
                InitScaleRanges(vl);
                _hasTooltips = !string.IsNullOrEmpty(vl.ToolTip);
            }
            else if (ldf.SubLayer.LayerType == LayerType.Raster)
            {
                var rl = ((IRasterLayerDefinition)ldf.SubLayer);
                _qualifiedClassName = rl.FeatureName;
                _geometryPropertyName = rl.Geometry;
                _featureSourceId = rl.ResourceId;
                InitScaleRanges(rl);
            }
            else if (ldf.SubLayer.LayerType == LayerType.Drawing)
            {
                _featureSourceId = ldf.SubLayer.ResourceId;
                var dl = ((IDrawingLayerDefinition)ldf.SubLayer);
                _scaleRanges = new double[]
                {
                    dl.MinScale,
                    dl.MaxScale
                };
                EnsureOrderedMinMaxScales();
            }

            _expandInLegend = false;
            this.Name = ResourceIdentifier.GetName(ldf.ResourceID);
            _legendLabel = this.Name;
            _selectable = true;
            _showInLegend = true;
            _visible = true;
        }