Exemplo n.º 1
0
        public void TestCase_GetResourceContents()
        {
            try
            {
                var fact    = new MgdServiceFactory();
                var service = (MgResourceService)fact.CreateService(MgServiceType.ResourceService);

                //Try to get the content using NULL arguments
                Assert.Throws <MgNullArgumentException>(() => service.GetResourceContents(null, null));

                //Try to get the content of a resource that doesn't exist
                MgStringCollection resourceNotExistCol = new MgStringCollection();
                resourceNotExistCol.Add(resourceNotExist.ToString());
                resourceNotExistCol.Add(resourceIdentifier.ToString());
                Assert.Throws <MgResourceNotFoundException>(() => service.GetResourceContents(resourceNotExistCol, null));

                //Get the content of the resource that was added in TestCase_SetResource
                MgStringCollection resIds = new MgStringCollection();
                resIds.Add(resourceIdentifier.ToString());
                resIds.Add(resourceIdentifier4.ToString());
                var ret = service.GetResourceContents(resIds, null);
                Assert.AreEqual(2, ret.GetCount());

                for (int i = 0; i < ret.GetCount(); i++)
                {
                    Assert.False(string.IsNullOrEmpty(ret.GetItem(i)));
                }
            }
            catch (MgException ex)
            {
                Assert.Fail(ex.Message);
                ex.Dispose();
            }
        }
Exemplo n.º 2
0
        internal NameValueCollection GetPropertyMappings(MgLayerBase layer)
        {
            MgResourceIdentifier resId = layer.GetLayerDefinition();
            string resIdStr            = resId.ToString();

            if (_propertyMappings.ContainsKey(resIdStr))
            {
                return(_propertyMappings[resIdStr]);
            }

            MgByteReader content = _resSvc.GetResourceContent(resId);
            XmlDocument  doc     = new XmlDocument();
            string       xml     = content.ToString();

            doc.LoadXml(xml);

            XmlNodeList propMaps = doc.GetElementsByTagName("PropertyMapping"); //NOXLATE

            if (propMaps.Count > 0)
            {
                NameValueCollection propertyMappings = new NameValueCollection();
                foreach (XmlNode pm in propMaps)
                {
                    propertyMappings[pm["Name"].InnerText] = pm["Value"].InnerText; //NOXLATE
                }
                _propertyMappings[resIdStr] = propertyMappings;
            }
            else
            {
                //NULL is a legit dictionary value
                _propertyMappings[resIdStr] = null;
            }
            return(_propertyMappings[resIdStr]);
        }
Exemplo n.º 3
0
        private void btnDisplaySpatialReference_Click(object sender, EventArgs e)
        {
            MgMapBase            map   = _viewer.GetMap();
            MgResourceIdentifier resId = map.MapDefinition;
            string mapSrs = map.GetMapSRS();

            MessageBox.Show("Map: (" + resId.ToString() + ") uses this reference system: " + Environment.NewLine + Environment.NewLine + mapSrs);
        }
        public void Preview(IResource res, IEditorService edSvc, string locale)
        {
            IMapDefinition mapDef = null;
            var            conn   = edSvc.CurrentConnection;

            if (res.ResourceType == ResourceTypes.LayerDefinition.ToString())
            {
                var    ldf = (ILayerDefinition)res;
                string wkt;
                var    env = ldf.GetSpatialExtent(conn, true, out wkt);
                if (env == null)
                {
                    throw new ApplicationException(Strings.CouldNotComputeExtentsForPreview);
                }
                mapDef = Utility.CreateMapDefinition(conn, "Preview");
                mapDef.CoordinateSystem = wkt;
                mapDef.SetExtents(env.MinX, env.MinY, env.MaxX, env.MaxY);
                string resId = "Session:" + edSvc.SessionID + "//" + Guid.NewGuid() + "." + res.ResourceType.ToString();
                conn.ResourceService.SetResourceXmlData(resId, ObjectFactory.Serialize(res));
                mapDef.AddLayer(null, "PreviewLayer", resId);
            }
            else if (res.ResourceType == ResourceTypes.MapDefinition.ToString())
            {
                mapDef = (IMapDefinition)res;
            }
            else if (res.ResourceType == ResourceTypes.WatermarkDefinition.ToString())
            {
                string resId = "Session:" + edSvc.SessionID + "//" + Guid.NewGuid() + "." + res.ResourceType.ToString();
                conn.ResourceService.SetResourceXmlData(resId, ObjectFactory.Serialize(res));

                var csFact = new MgCoordinateSystemFactory();
                var arbXY  = csFact.ConvertCoordinateSystemCodeToWkt("XY-M");
                mapDef = ObjectFactory.CreateMapDefinition(new Version(2, 3, 0), "Preview");
                mapDef.CoordinateSystem = arbXY;
                mapDef.SetExtents(-100000, -100000, 100000, 100000);
                var wm = ((IMapDefinition2)mapDef).AddWatermark(((IWatermarkDefinition)res));
                wm.ResourceId = resId;
            }

            var mapResId = new MgResourceIdentifier("Session:" + edSvc.SessionID + "//" + mapDef.ResourceType.ToString() + "Preview" + Guid.NewGuid() + "." + mapDef.ResourceType.ToString());

            conn.ResourceService.SetResourceXmlData(mapResId.ToString(), ObjectFactory.Serialize(mapDef));

            //MgdMap map = new MgdMap(mapResId);

            //var diag = new MapPreviewWindow(map, conn);
            //diag.ShowDialog();

            var diag = new UI.MapPreviewWindow(conn);

            diag.Init(mapResId);
            diag.ShowDialog();
        }
Exemplo n.º 5
0
        public MgdLayer CreateBufferLayer(MgResourceService resourceService, MgResourceIdentifier bufferFeatureResId, String sessionId)
        {
            // Load the layer definition template into
            // a XmlDocument object, find the "ResourceId" element, and
            // modify its content to reference the temporary
            // feature source.

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(Layers.BufferLayerDefinition);
            XmlNode featureSourceNode = doc.GetElementsByTagName("ResourceId")[0];

            featureSourceNode.InnerText = bufferFeatureResId.ToString();

            // Get the updated layer definition from the XmlDocument
            // and save it to the session repository using the
            // ResourceService object.

            MgByteSource byteSource = null;

            using (MemoryStream ms = new MemoryStream())
            {
                doc.Save(ms);
                ms.Position = 0L;

                //Note we do this to ensure our XML content is free of any BOM characters
                byte[]   layerDefinition = ms.ToArray();
                Encoding utf8            = Encoding.UTF8;
                String   layerDefStr     = new String(utf8.GetChars(layerDefinition));
                layerDefinition = new byte[layerDefStr.Length - 1];
                int byteCount = utf8.GetBytes(layerDefStr, 1, layerDefStr.Length - 1, layerDefinition, 0);

                byteSource = new MgByteSource(layerDefinition, layerDefinition.Length);
                byteSource.SetMimeType(MgMimeType.Xml);
            }

            MgResourceIdentifier tempLayerResId = new MgResourceIdentifier("Session:" + sessionId + "//Buffer.LayerDefinition");

            resourceService.SetResource(tempLayerResId, byteSource.GetReader(), null);

            // Create an MgLayer object based on the new layer definition
            // and return it to the caller.

            MgdLayer bufferLayer = new MgdLayer(tempLayerResId, resourceService);

            bufferLayer.SetName("Buffer");
            bufferLayer.SetLegendLabel("Buffer");
            bufferLayer.SetDisplayInLegend(true);
            bufferLayer.SetSelectable(false);

            return(bufferLayer);
        }
Exemplo n.º 6
0
        public MgdLayer CreateBufferLayer(MgResourceService resourceService, MgResourceIdentifier bufferFeatureResId, String sessionId)
        {
            // Load the layer definition template into
            // a XmlDocument object, find the "ResourceId" element, and
            // modify its content to reference the temporary
            // feature source.

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(Layers.BufferLayerDefinition);
            XmlNode featureSourceNode = doc.GetElementsByTagName("ResourceId")[0];
            featureSourceNode.InnerText = bufferFeatureResId.ToString();

            // Get the updated layer definition from the XmlDocument
            // and save it to the session repository using the
            // ResourceService object.

            MgByteSource byteSource = null;
            using (MemoryStream ms = new MemoryStream())
            {
                doc.Save(ms);
                ms.Position = 0L;

                //Note we do this to ensure our XML content is free of any BOM characters
                byte[] layerDefinition = ms.ToArray();
                Encoding utf8 = Encoding.UTF8;
                String layerDefStr = new String(utf8.GetChars(layerDefinition));
                layerDefinition = new byte[layerDefStr.Length - 1];
                int byteCount = utf8.GetBytes(layerDefStr, 1, layerDefStr.Length - 1, layerDefinition, 0);

                byteSource = new MgByteSource(layerDefinition, layerDefinition.Length);
                byteSource.SetMimeType(MgMimeType.Xml);
            }

            MgResourceIdentifier tempLayerResId = new MgResourceIdentifier("Session:" + sessionId + "//Buffer.LayerDefinition");

            resourceService.SetResource(tempLayerResId, byteSource.GetReader(), null);

            // Create an MgLayer object based on the new layer definition
            // and return it to the caller.

            MgdLayer bufferLayer = new MgdLayer(tempLayerResId, resourceService);
            bufferLayer.SetName("Buffer");
            bufferLayer.SetLegendLabel("Buffer");
            bufferLayer.SetDisplayInLegend(true);
            bufferLayer.SetSelectable(false);

            return bufferLayer;
        }
Exemplo n.º 7
0
        private void btnListLayerGroups_Click(object sender, EventArgs e)
        {
            MgMapBase              map    = _viewer.GetMap();
            MgResourceIdentifier   resId  = map.MapDefinition;
            MgLayerGroupCollection groups = map.GetLayerGroups();

            List <string> results = new List <string>();

            for (int i = 0; i < groups.GetCount(); i++)
            {
                MgLayerGroup group = groups.GetItem(i);
                results.Add(group.Name + " (" + group.LegendLabel + ")");
            }

            MessageBox.Show("Map (" + resId.ToString() + ") has " + groups.GetCount() + " layers: " + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, results.ToArray()));
        }
Exemplo n.º 8
0
        public override void Execute(IPlatformFactory factory, ITestLogger logger)
        {
            try
            {
                MgResourceService resSvc = (MgResourceService)factory.CreateService(MgServiceType.ResourceService);

                var root = "../../TestData/TileService/";
                LoadResource(resSvc, "Library://UnitTests/Data/RoadCenterLines.FeatureSource", root + "UT_RoadCenterLines.fs");
                LoadResourceData(resSvc, "Library://UnitTests/Data/RoadCenterLines.FeatureSource", "UT_RoadCenterLines.sdf", MgResourceDataType.File, root + "UT_RoadCenterLines.sdf");
                LoadResource(resSvc, "Library://UnitTests/Layers/RoadCenterLines.LayerDefinition", root + "UT_RoadCenterLines.ldf");

                LoadResource(resSvc, "Library://UnitTests/Data/VotingDistricts.FeatureSource", root + "UT_VotingDistricts.fs");
                LoadResourceData(resSvc, "Library://UnitTests/Data/VotingDistricts.FeatureSource", "UT_VotingDistricts.sdf", MgResourceDataType.File, root + "UT_VotingDistricts.sdf");
                LoadResource(resSvc, "Library://UnitTests/Layers/VotingDistricts.LayerDefinition", root + "UT_VotingDistricts.ldf");

                LoadResource(resSvc, "Library://UnitTests/Data/Parcels.FeatureSource", root + "UT_Parcels.fs");
                LoadResourceData(resSvc, "Library://UnitTests/Data/Parcels.FeatureSource", "UT_Parcels.sdf", MgResourceDataType.File, root + "UT_Parcels.sdf");
                LoadResource(resSvc, "Library://UnitTests/Layers/Parcels.LayerDefinition", root + "UT_Parcels.ldf");

                byte[]               tsd        = Properties.Resources.UT_XYZ;
                MgByteSource         sourceTSD  = new MgByteSource(tsd, tsd.Length);
                MgByteReader         contentTSD = sourceTSD.GetReader();
                MgResourceIdentifier resTSD     = new MgResourceIdentifier("Library://UnitTests/TileSets/Test.TileSetDefinition");

                resSvc.SetResource(resTSD, contentTSD, null);

                string mdf = Encoding.UTF8.GetString(Properties.Resources.UT_BaseMap);
                mdf = string.Format(mdf, resTSD.ToString());
                byte[]               mdfBytes   = Encoding.UTF8.GetBytes(mdf);
                MgByteSource         sourceMDF  = new MgByteSource(mdfBytes, mdfBytes.Length);
                MgByteReader         contentMDF = sourceMDF.GetReader();
                MgResourceIdentifier resMDF     = new MgResourceIdentifier("Library://UnitTests/Maps/LinkedTileSet.MapDefinition");

                resSvc.SetResource(resMDF, contentMDF, null);

                //This should throw because making a MgMap from a Map Defintion that links to a XYZ tile set
                //is not supported
                MgMapBase map = factory.CreateMap(resMDF);

                Assert.Fail("Expected MgUnsupportedTileProviderException to be thrown");
            }
            catch (MgUnsupportedTileProviderException)
            {
            }
        }
Exemplo n.º 9
0
        private void btnCreate_Click(object sender, EventArgs e)
        {
            btnCreate.Enabled = false;
            try
            {
                var layerName = txtBufferLayer.Text.Trim();
                if (string.IsNullOrEmpty(layerName))
                {
                    MessageBox.Show(Strings.MsgEnterNameForLayer);
                    return;
                }

                if (lstLayers.SelectedItems.Count == 0)
                {
                    MessageBox.Show(Strings.MsgIncludeLayersToBuffer);
                    return;
                }

                var map      = _viewer.GetMap();
                var layers   = map.GetLayers();
                var provider = _viewer.GetProvider();

                //From here, it's the same logic as buffer.aspx in .net MapGuide AJAX viewer
                MgResourceIdentifier fsId  = new MgResourceIdentifier("Session:" + _sessionId + "//" + txtBufferLayer.Text + "_Buffer.FeatureSource");   //NOXLATE
                MgResourceIdentifier ldfId = new MgResourceIdentifier("Session:" + _sessionId + "//" + txtBufferLayer.Text + "_Buffer.LayerDefinition"); //NOXLATE

                MgLayerBase layer      = Util.FindLayer(layers, txtBufferLayer.Text);
                string[]    layerNames = GetLayerNames();

                double          distance = Convert.ToDouble(numBufferDistance.Value);
                MeasurementUnit bUnits   = (MeasurementUnit)cmbUnits.SelectedItem;
                switch (bUnits)
                {
                case MeasurementUnit.Feet:
                    distance *= 0.30480;
                    break;

                case MeasurementUnit.Kilometers:
                    distance *= 1000;
                    break;

                case MeasurementUnit.Miles:
                    distance *= 1609.35;
                    break;
                }

                String             srsDefMap   = Util.GetMapSrs(map);
                MgCoordinateSystem srsMap      = provider.GetMapCoordinateSystem();
                string             mapSrsUnits = "";
                bool arbitraryMapSrs           = (srsMap.GetType() == MgCoordinateSystemType.Arbitrary);
                if (arbitraryMapSrs)
                {
                    mapSrsUnits = srsMap.GetUnits();
                }

                String xtrans     = String.Format("{0:x2}", ((int)(255 * Convert.ToInt32(numFillTransparency.Value) / 100))); //NOXLATE
                var    lineColor  = Util.ToHtmlColor(pnlBorderColor.BackColor);
                var    foreColor  = Util.ToHtmlColor(pnlFillColor.BackColor);
                var    backColor  = Util.ToHtmlColor(pnlFillBackColor.BackColor);
                String layerTempl = string.Format(Properties.Resources.AreaLayerDef,
                                                  fsId.ToString(),
                                                  "BufferSchema:Buffer", //NOXLATE
                                                  "GEOM",                //NOXLATE
                                                  cmbFillPattern.SelectedItem,
                                                  xtrans + foreColor,
                                                  ((0 != 1 /*transparent*/) ? "ff" : "00") + backColor, //NOXLATE
                                                  cmbBorderPattern.SelectedItem,
                                                  numLineThickness.Value.ToString(NumberFormatInfo.InvariantInfo),
                                                  lineColor
                                                  );
                byte[]       bytes           = Encoding.UTF8.GetBytes(layerTempl);
                MgByteSource src             = new MgByteSource(bytes, bytes.Length);
                MgByteReader layerDefContent = src.GetReader();
                _resSvc.SetResource(ldfId, layerDefContent, null);

                bool newBuffer = false;
                if (layer == null)
                {
                    newBuffer = true;

                    //Targetting a new layer. create a data source for it
                    //
                    MgClassDefinition classDef = new MgClassDefinition();

                    classDef.SetName("Buffer");                                //NOXLATE
                    classDef.SetDescription("Feature class for buffer layer"); //NOXLATE
                    classDef.SetDefaultGeometryPropertyName("GEOM");           //NOXLATE

                    //Set KEY property
                    MgDataPropertyDefinition prop = new MgDataPropertyDefinition("KEY"); //NOXLATE
                    prop.SetDataType(MgPropertyType.Int32);
                    prop.SetAutoGeneration(true);
                    prop.SetReadOnly(true);
                    classDef.GetIdentityProperties().Add(prop);
                    classDef.GetProperties().Add(prop);

                    //Set ID property. Hold this segment ID
                    prop = new MgDataPropertyDefinition("ID"); //NOXLATE
                    prop.SetDataType(MgPropertyType.Int32);
                    classDef.GetProperties().Add(prop);

                    //Set geometry property
                    MgGeometricPropertyDefinition geomProp = new MgGeometricPropertyDefinition("GEOM"); //NOXLATE
                    //prop.SetGeometryTypes(MgFeatureGeometricType.mfgtSurface); //TODO use the constant when exposed
                    geomProp.SetGeometryTypes(4);
                    classDef.GetProperties().Add(geomProp);

                    //Create the schema
                    MgFeatureSchema schema = new MgFeatureSchema("BufferSchema", "Temporary buffer schema"); //NOXLATE
                    schema.GetClasses().Add(classDef);

                    //finally, creation of the feature source
                    MgFileFeatureSourceParams sdfParams = new MgFileFeatureSourceParams("OSGeo.SDF", "LatLong", map.GetMapSRS(), schema); //NOXLATE
                    _featSvc.CreateFeatureSource(fsId, sdfParams);

                    //Add layer to map
                    layer = provider.CreateLayer(ldfId);
                    layer.SetName(txtBufferLayer.Text);
                    layer.SetLegendLabel(txtBufferLayer.Text);
                    layer.SetDisplayInLegend(true);
                    layer.SetSelectable(true);
                    layers.Insert(0, layer);
                }
                else
                {
                    //data source already exist. clear its content
                    //
                    Util.ClearDataSource(_featSvc, fsId, "BufferSchema:Buffer"); //NOXLATE
                }

                var sel       = _viewer.GetSelection();
                var selLayers = sel.GetLayers();

                MgAgfReaderWriter    agfRW            = new MgAgfReaderWriter();
                MgGeometryCollection bufferGeometries = new MgGeometryCollection();
                MgGeometry           geomBuffer;

                MgFeatureCommandCollection commands = new MgFeatureCommandCollection();
                int featId = 0;

                MgBatchPropertyCollection propCollection = new MgBatchPropertyCollection();

                int excludedLayers                   = 0;
                MgCoordinateSystem   srsDs           = null;
                MgGeometryCollection inputGeometries = new MgGeometryCollection();

                int bufferFeatures = 0;
                for (int li = 0; li < selLayers.GetCount(); li++)
                {
                    MgLayerBase selLayer     = selLayers.GetItem(li);
                    bool        inputLayer   = false;
                    String      selLayerName = selLayer.GetName();
                    for (int il = 0; il < layerNames.Length; il++)
                    {
                        if (layerNames[il].Equals(selLayerName))
                        {
                            inputLayer = true;
                            break;
                        }
                    }
                    if (inputLayer == false)
                    {
                        continue;
                    }

                    // get the data source SRS
                    //
                    MgResourceIdentifier   featSourceId = new MgResourceIdentifier(selLayer.GetFeatureSourceId());
                    MgSpatialContextReader ctxs         = _featSvc.GetSpatialContexts(featSourceId, false);
                    String srsDefDs = string.Empty;
                    if (ctxs != null && ctxs.ReadNext())
                    {
                        srsDefDs = ctxs.GetCoordinateSystemWkt();
                    }

                    if (srsDefDs == null || srsDefDs.Length == 0)
                    {
                        excludedLayers++;
                        continue;
                    }

                    var srsFactory = new MgCoordinateSystemFactory();
                    srsDs = srsFactory.Create(srsDefDs);
                    bool   arbitraryDsSrs = (srsDs.GetType() == MgCoordinateSystemType.Arbitrary);
                    String dsSrsUnits     = string.Empty;

                    if (arbitraryDsSrs)
                    {
                        dsSrsUnits = srsDs.GetUnits();
                    }

                    // exclude layer if:
                    //  the map is non-arbitrary and the layer is arbitrary or vice-versa
                    //     or
                    //  layer and map are both arbitrary but have different units
                    //
                    if ((arbitraryDsSrs != arbitraryMapSrs) || (arbitraryDsSrs && (dsSrsUnits != mapSrsUnits)))
                    {
                        excludedLayers++;
                        continue;
                    }

                    // calculate distance in the data source SRS units
                    //
                    double dist = srsDs.ConvertMetersToCoordinateSystemUnits(distance);

                    // calculate great circle unless data source srs is arbitrary
                    MgCoordinateSystemMeasure measure;
                    if (!arbitraryDsSrs)
                    {
                        measure = srsDs.GetMeasure();
                    }
                    else
                    {
                        measure = null;
                    }

                    // create a SRS transformer if necessary
                    MgCoordinateSystemTransform srsXform;
                    if (!srsDefDs.Equals(srsDefMap))
                    {
                        srsXform = srsFactory.GetTransform(srsDs, srsMap);
                    }
                    else
                    {
                        srsXform = null;
                    }

                    String featureClassName = selLayer.GetFeatureClassName();
                    String filter           = sel.GenerateFilter(selLayer, featureClassName);
                    if (filter == null || filter.Length == 0)
                    {
                        continue;
                    }

                    MgFeatureQueryOptions query = new MgFeatureQueryOptions();
                    query.SetFilter(filter);

                    MgResourceIdentifier featureSource = new MgResourceIdentifier(selLayer.GetFeatureSourceId());

                    MgFeatureReader features = _featSvc.SelectFeatures(featureSource, featureClassName, query);

                    if (features.ReadNext())
                    {
                        MgClassDefinition classDef     = features.GetClassDefinition();
                        String            geomPropName = classDef.GetDefaultGeometryPropertyName();

                        do
                        {
                            MgByteReader geomReader = features.GetGeometry(geomPropName);
                            MgGeometry   geom       = agfRW.Read(geomReader);

                            if (!chkMergeBuffers.Checked)
                            {
                                geomBuffer = geom.Buffer(dist, measure);
                                if (geomBuffer != null)
                                {
                                    if (srsXform != null)
                                    {
                                        geomBuffer = (MgGeometry)geomBuffer.Transform(srsXform);
                                    }
                                    Util.AddFeatureToCollection(propCollection, agfRW, featId++, geomBuffer);
                                    bufferFeatures++;
                                }
                            }
                            else
                            {
                                if (srsXform != null)
                                {
                                    geom = (MgGeometry)geom.Transform(srsXform);
                                }
                                inputGeometries.Add(geom);
                            }
                        }while (features.ReadNext());

                        features.Close();
                    }
                }

                if (chkMergeBuffers.Checked)
                {
                    if (inputGeometries.GetCount() > 0)
                    {
                        double dist = srsMap.ConvertMetersToCoordinateSystemUnits(distance);
                        MgCoordinateSystemMeasure measure;
                        if (!arbitraryMapSrs)
                        {
                            measure = srsMap.GetMeasure();
                        }
                        else
                        {
                            measure = null;
                        }

                        MgGeometryFactory geomFactory = new MgGeometryFactory();
                        geomBuffer = geomFactory.CreateMultiGeometry(inputGeometries).Buffer(dist, measure);
                        if (geomBuffer != null)
                        {
                            Util.AddFeatureToCollection(propCollection, agfRW, featId, geomBuffer);
                            bufferFeatures = 1;
                        }
                    }
                }

                if (propCollection.GetCount() > 0)
                {
                    commands.Add(new MgInsertFeatures("BufferSchema:Buffer", propCollection)); //NOXLATE

                    //Insert the features in the temporary data source
                    //
                    Util.ReleaseReader(_featSvc.UpdateFeatures(fsId, commands, false), commands);
                }

                // Save the new map state
                //
                layer.ForceRefresh();
                _viewer.RefreshMap();

                //build report message
                if (newBuffer)
                {
                    MessageBox.Show(string.Format(Strings.MsgBufferLayerCreated, txtBufferLayer.Text));
                }
                else
                {
                    MessageBox.Show(string.Format(Strings.MsgBufferLayerUpdated, txtBufferLayer.Text));
                }
            }
            finally
            {
                btnCreate.Enabled = true;
            }
        }
Exemplo n.º 10
0
    // Create a temporary Layer to display geocode results.
    public MgLayer CreateLocationMarkerLayer(MgResourceService resourceService, MgResourceIdentifier locationMarkerDataResId, String sessionId)
    {
        // Load the AddressMarker layer definition template into
        // a ASPX XML object, find the "ResourceId" element, and
        // modify it's content to reference the temporary
        // feature source.

        XmlDocument doc = new XmlDocument();
        doc.PreserveWhitespace = true;
        string path =HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"] + "Extensions/findlocation/templates/locationmarker.xml";
        doc.Load(path);
        XmlNode featureSourceNode = doc.GetElementsByTagName("ResourceId").Item(0);
        XmlNode resContent = doc.CreateTextNode(locationMarkerDataResId.ToString());
        featureSourceNode.AppendChild(resContent);

        // Get the updated layer definition from the DOM object
        // and save it to the session repository using the
        // ResourceService object.
        MemoryStream xmlStream = new MemoryStream();
        doc.Save(xmlStream);
        byte[] layerDefinition = xmlStream.ToArray();
        Encoding utf8 = Encoding.UTF8;
        String layerDefStr = new String(utf8.GetChars(layerDefinition));
        layerDefinition = new byte[layerDefStr.Length - 1];
        int byteCount = utf8.GetBytes(layerDefStr, 1, layerDefStr.Length - 1, layerDefinition, 0);
        MgByteSource byteSource = new MgByteSource(layerDefinition, layerDefinition.Length);
        byteSource.SetMimeType(MgMimeType.Xml);

        MgResourceIdentifier tempLayerResId = new MgResourceIdentifier("Session:" + sessionId + "//LocationMarker.LayerDefinition");
        //MgResourceIdentifier tempLayerResId = new MgResourceIdentifier("Library://findLocation/" + sessionId + "/LocationMarker.LayerDefinition");
        resourceService.SetResource(tempLayerResId, byteSource.GetReader(), null);

        // Create an MgLayer object based on the new layer definition
        // and return it to the caller.

        MgLayer locationLayer = new MgLayer(tempLayerResId, resourceService);
        locationLayer.SetName("LocationMarker");
        locationLayer.SetLegendLabel("LocationMarker");
        locationLayer.SetDisplayInLegend(false);
        locationLayer.SetSelectable(false);

        return locationLayer;
    }
Exemplo n.º 11
0
        private bool MaintenanceForFeatureExists(MgResourceIdentifier featureSourceId, MgResourceIdentifier maintenanceResId)
        {
            bool result = false;
            if (_resourceService.ResourceExists(maintenanceResId))
            {
                MgFeatureQueryOptions opt = new MgFeatureQueryOptions();
                opt.SetFilter(String.Format("FeatureSource='{0}' AND UID = {1}", featureSourceId.ToString(), GetParameter(this.args, "MARKUPFEATURE")));

                MgFeatureReader reader = _featureService.SelectFeatures(maintenanceResId, "Maintenance:Maintenance", opt);
                if (reader.ReadNext())
                {
                    result = true;
                }
            }
            return result;
        }
Exemplo n.º 12
0
        private void CreateRedlineLayer()
        {
            MgMapBase map = mgMapViewer1.GetMap();
            MgdServiceFactory fact = new MgdServiceFactory();
            MgdFeatureService featSvc = (MgdFeatureService)fact.CreateService(MgServiceType.FeatureService);
            MgResourceService resSvc = (MgResourceService)fact.CreateService(MgServiceType.ResourceService);

            //Note that mg-desktop does not have a concept of sessions like the
            //official MapGuide API, but it *does* allow session-based resources 
            //as a way of having temporary resources. Such resources will reside
            //in a special directory for session resources (specified in Platform.ini)
            //
            //You can plug whatever string as the session id, but the resource identifier
            //must satisfy the session id pattern:
            //
            // Session:<session id string>//Path/To/Your.ResourceType
            //
            //These files are removed with MgPlatform.Terminate(), which is called in this
            //application as part of the exiting process.
            string sessionId = Guid.NewGuid().ToString();
            MgResourceIdentifier fsId = new MgResourceIdentifier("Session:" + sessionId + "//Redline.FeatureSource");
            MgResourceIdentifier ldfId = new MgResourceIdentifier("Session:" + sessionId + "//Redline.LayerDefinition");

            //Create our point redline schema. It looks like this:
            //
            // Default
            //    Redline
            //        ID (int32, autogenerated)
            //        Geometry (coordinate system same as map
            string featureClass = "Default:Redline";
            string geometry = "Geometry";

            MgFeatureSchema schema = new MgFeatureSchema("Default", "Redline schema");
            MgClassDefinition cls = new MgClassDefinition();
            cls.Name = "Redline";

            MgDataPropertyDefinition id = new MgDataPropertyDefinition("ID");
            id.DataType = MgPropertyType.Int32;
            id.SetAutoGeneration(true);

            MgGeometricPropertyDefinition geom = new MgGeometricPropertyDefinition(geometry);
            geom.SpatialContextAssociation = "Default";
            geom.GeometryTypes = MgFeatureGeometricType.Curve | MgFeatureGeometricType.Point | MgFeatureGeometricType.Solid | MgFeatureGeometricType.Surface;

            MgPropertyDefinitionCollection clsProps = cls.GetProperties();
            clsProps.Add(id);
            clsProps.Add(geom);

            MgPropertyDefinitionCollection idProps = cls.GetIdentityProperties();
            idProps.Add(id);

            cls.DefaultGeometryPropertyName = geometry;
            MgClassDefinitionCollection classes = schema.GetClasses();
            classes.Add(cls);

            //Create the feature source with this schema. We use the map's
            //coordinate system for the feature source to ensure features
            //that we create, will line up with the map
            MgCreateSdfParams create = new MgCreateSdfParams("Default", map.GetMapSRS(), schema);
            featSvc.CreateFeatureSource(fsId, create);

            //Then create the layer definition. RedlineLayer.xml contains the template
            string xml = string.Format(File.ReadAllText("RedlineLayer.xml"), fsId.ToString(), featureClass, geometry);
            var bytes = Encoding.UTF8.GetBytes(xml);
            MgByteSource source = new MgByteSource(bytes, bytes.Length);
            resSvc.SetResource(ldfId, source.GetReader(), null);

            //Now create the runtime layer and add to map
            _pointLayer = new MgdLayer(ldfId, resSvc);
            _pointLayer.LegendLabel = "Redlining";
            _pointLayer.Name = "Redline";
            _pointLayer.Visible = true;
            _pointLayer.Selectable = true;
            _pointLayer.DisplayInLegend = true;

            var layers = map.GetLayers();
            layers.Insert(0, _pointLayer);
        }
Exemplo n.º 13
0
        public void Preview(IResource res, IEditorService edSvc, string locale)
        {
            IMapDefinition mapDef = null;
            var conn = res.CurrentConnection;

            if (res.ResourceType == ResourceTypes.LayerDefinition)
            {
                var ldf = (ILayerDefinition)res;
                string wkt;
                var env = ldf.GetSpatialExtent(true, out wkt);
                if (env == null)
                    throw new ApplicationException(Strings.CouldNotComputeExtentsForPreview);
                mapDef = ObjectFactory.CreateMapDefinition(conn, "Preview");
                mapDef.CoordinateSystem = wkt;
                mapDef.SetExtents(env.MinX, env.MinY, env.MaxX, env.MaxY);
                string resId = "Session:" + edSvc.SessionID + "//" + Guid.NewGuid() + "." + res.ResourceType.ToString();
                edSvc.ResourceService.SetResourceXmlData(resId, ResourceTypeRegistry.Serialize(res));
                mapDef.AddLayer(null, "PreviewLayer", resId);
            }
            else if (res.ResourceType == ResourceTypes.MapDefinition)
            {
                mapDef = (IMapDefinition)res;
            }
            else if (res.ResourceType == ResourceTypes.WatermarkDefinition)
            {
                string resId = "Session:" + edSvc.SessionID + "//" + Guid.NewGuid() + "." + res.ResourceType.ToString();
                edSvc.ResourceService.SetResourceXmlData(resId, ResourceTypeRegistry.Serialize(res));

                var csFact = new MgCoordinateSystemFactory();
                var arbXY = csFact.ConvertCoordinateSystemCodeToWkt("XY-M");
                mapDef = ObjectFactory.CreateMapDefinition(conn, new Version(2, 3, 0), "Preview");
                mapDef.CoordinateSystem = arbXY;
                mapDef.SetExtents(-100000, -100000, 100000, 100000);
                var wm = ((IMapDefinition2)mapDef).AddWatermark(((IWatermarkDefinition)res));
                wm.ResourceId = resId;
            }

            var mapResId = new MgResourceIdentifier("Session:" + edSvc.SessionID + "//" + mapDef.ResourceType.ToString() + "Preview" + Guid.NewGuid() + "." + mapDef.ResourceType.ToString());
            edSvc.ResourceService.SetResourceXmlData(mapResId.ToString(), ResourceTypeRegistry.Serialize(mapDef));

            //MgdMap map = new MgdMap(mapResId);

            //var diag = new MapPreviewWindow(map, conn);
            //diag.ShowDialog();

            var diag = new UI.MapPreviewWindow(conn);
            diag.Init(mapResId);
            diag.ShowDialog();
        }
Exemplo n.º 14
0
    //---------------------------------------------------------------------------------------
    //
    //        ���ܣ�����Ԥ�����XML������
    //
    //         ���ߣ�
    //
    //         ���ڣ� 2007.5.23
    //        
    //         �޸���ʷ����
    //        
    //---------------------------------------------------------------------------------------
    private MgLayer createTempParcelLayer(MgResourceService resService, MgResourceIdentifier resId, string sessionId)
    {
        MgLayer tempParcelLayer = null;

        // ����XML�ĵ�
        XmlDocument doc = new XmlDocument();
        doc.PreserveWhitespace = false;
        doc.Load(@"C:\inetpub\wwwroot\MapguideTutorial\CH05-2\tempParcels.xml");
        // ��XML�ĵ��е�ResourceId���滻Ϊ�������ԴID���˴�ӦΪ�������ĻỰ�ִ��е���ʱ��ԴID
        XmlNode featureSourceNode = doc.GetElementsByTagName("ResourceId").Item(0);
        XmlNode resContent = doc.CreateTextNode(resId.ToString());
        featureSourceNode.AppendChild(resContent);
        // ����XML
        MemoryStream xmlStream = new MemoryStream();
        doc.Save(xmlStream);
        byte[] layerDef = xmlStream.ToArray();
        Encoding utf8 = Encoding.UTF8;
        string layerDefStr = new string(utf8.GetChars(layerDef));
        layerDef = new byte[layerDefStr.Length - 1];
        int byteCount = utf8.GetBytes(layerDefStr, 1, layerDefStr.Length - 1, layerDef, 0);

        MgByteSource byteSource = new MgByteSource(layerDef, layerDef.Length);
        byteSource.SetMimeType(MgMimeType.Xml);
        // ������Դ
        MgResourceIdentifier tempParcelLayerId = new MgResourceIdentifier("Session:" + sessionId + "//TempParcel.LayerDefinition");
        resService.SetResource(tempParcelLayerId, byteSource.GetReader(), null);
        //������ʱ��
        tempParcelLayer = new MgLayer(tempParcelLayerId, resService);
        tempParcelLayer.SetName("TempParcels");
        tempParcelLayer.SetLegendLabel("New Parcels");
        tempParcelLayer.SetDisplayInLegend(true);
        tempParcelLayer.SetSelectable(false);

        return tempParcelLayer;
    }
Exemplo n.º 15
0
        private void CreateRedlineLayer()
        {
            MgMapBase         map     = mgMapViewer1.GetMap();
            MgdServiceFactory fact    = new MgdServiceFactory();
            MgdFeatureService featSvc = (MgdFeatureService)fact.CreateService(MgServiceType.FeatureService);
            MgResourceService resSvc  = (MgResourceService)fact.CreateService(MgServiceType.ResourceService);

            //Note that mg-desktop does not have a concept of sessions like the
            //official MapGuide API, but it *does* allow session-based resources
            //as a way of having temporary resources. Such resources will reside
            //in a special directory for session resources (specified in Platform.ini)
            //
            //You can plug whatever string as the session id, but the resource identifier
            //must satisfy the session id pattern:
            //
            // Session:<session id string>//Path/To/Your.ResourceType
            //
            //These files are removed with MgPlatform.Terminate(), which is called in this
            //application as part of the exiting process.
            string sessionId           = Guid.NewGuid().ToString();
            MgResourceIdentifier fsId  = new MgResourceIdentifier("Session:" + sessionId + "//Redline.FeatureSource");
            MgResourceIdentifier ldfId = new MgResourceIdentifier("Session:" + sessionId + "//Redline.LayerDefinition");

            //Create our point redline schema. It looks like this:
            //
            // Default
            //    Redline
            //        ID (int32, autogenerated)
            //        Geometry (coordinate system same as map
            string featureClass = "Default:Redline";
            string geometry     = "Geometry";

            MgFeatureSchema   schema = new MgFeatureSchema("Default", "Redline schema");
            MgClassDefinition cls    = new MgClassDefinition();

            cls.Name = "Redline";

            MgDataPropertyDefinition id = new MgDataPropertyDefinition("ID");

            id.DataType = MgPropertyType.Int32;
            id.SetAutoGeneration(true);

            MgGeometricPropertyDefinition geom = new MgGeometricPropertyDefinition(geometry);

            geom.SpatialContextAssociation = "Default";
            geom.GeometryTypes             = MgFeatureGeometricType.Curve | MgFeatureGeometricType.Point | MgFeatureGeometricType.Solid | MgFeatureGeometricType.Surface;

            MgPropertyDefinitionCollection clsProps = cls.GetProperties();

            clsProps.Add(id);
            clsProps.Add(geom);

            MgPropertyDefinitionCollection idProps = cls.GetIdentityProperties();

            idProps.Add(id);

            cls.DefaultGeometryPropertyName = geometry;
            MgClassDefinitionCollection classes = schema.GetClasses();

            classes.Add(cls);

            //Create the feature source with this schema. We use the map's
            //coordinate system for the feature source to ensure features
            //that we create, will line up with the map
            MgFileFeatureSourceParams create = new MgFileFeatureSourceParams("OSGeo.SDF", "Default", map.GetMapSRS(), schema);

            featSvc.CreateFeatureSource(fsId, create);

            //Then create the layer definition. RedlineLayer.xml contains the template
            string       xml    = string.Format(File.ReadAllText("RedlineLayer.xml"), fsId.ToString(), featureClass, geometry);
            var          bytes  = Encoding.UTF8.GetBytes(xml);
            MgByteSource source = new MgByteSource(bytes, bytes.Length);

            resSvc.SetResource(ldfId, source.GetReader(), null);

            //Now create the runtime layer and add to map
            _pointLayer                 = new MgdLayer(ldfId, resSvc);
            _pointLayer.LegendLabel     = "Redlining";
            _pointLayer.Name            = "Redline";
            _pointLayer.Visible         = true;
            _pointLayer.Selectable      = true;
            _pointLayer.DisplayInLegend = true;

            var layers = map.GetLayers();

            layers.Insert(0, _pointLayer);
        }
Exemplo n.º 16
0
        public Hashtable GetAvailableMarkup()
        {
            Hashtable markup = new Hashtable();

            MgResourceService resourceService = (MgResourceService)this.site.CreateService(MgServiceType.ResourceService);
            MgResourceIdentifier resourceID = new MgResourceIdentifier(libraryPath);

            try
            {
                MgByteReader byteReader = resourceService.EnumerateResources(resourceID, 1, "LayerDefinition");
                String resourceListXML = byteReader.ToString();

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(resourceListXML);
                XmlNodeList nodeList = doc.GetElementsByTagName("ResourceId");

                foreach (XmlElement element in nodeList)
                {
                    MgResourceIdentifier resourceId = new MgResourceIdentifier(element.InnerText);
                    markup[resourceId.ToString()] = resourceId.GetName();
                }
            }
            catch (MgResourceNotFoundException mge)
            {
                // If the Library://Markup folder does not exist, create it.
                resourceService.SetResource(resourceID, null, null);
            }

            return markup;
        }
Exemplo n.º 17
0
        private void btnCreate_Click(object sender, EventArgs e)
        {
            btnCreate.Enabled = false;
            try
            {
                var layerName = txtBufferLayer.Text.Trim();
                if (string.IsNullOrEmpty(layerName))
                {
                    MessageBox.Show(Strings.MsgEnterNameForLayer);
                    return;
                }

                if (lstLayers.SelectedItems.Count == 0)
                {
                    MessageBox.Show(Strings.MsgIncludeLayersToBuffer);
                    return;
                }

                var map = _viewer.GetMap();
                var layers = map.GetLayers();
                var provider = _viewer.GetProvider();

                //From here, it's the same logic as buffer.aspx in .net MapGuide AJAX viewer
                MgResourceIdentifier fsId = new MgResourceIdentifier("Session:" + _sessionId + "//" + txtBufferLayer.Text + "_Buffer.FeatureSource"); //NOXLATE
                MgResourceIdentifier ldfId = new MgResourceIdentifier("Session:" + _sessionId + "//" + txtBufferLayer.Text + "_Buffer.LayerDefinition"); //NOXLATE

                MgLayerBase layer = Util.FindLayer(layers, txtBufferLayer.Text);
                string[] layerNames = GetLayerNames();

                double distance = Convert.ToDouble(numBufferDistance.Value);
                MeasurementUnit bUnits = (MeasurementUnit)cmbUnits.SelectedItem;
                switch (bUnits)
                {
                    case MeasurementUnit.Feet:
                        distance *= 0.30480;
                        break;
                    case MeasurementUnit.Kilometers:
                        distance *= 1000;
                        break;
                    case MeasurementUnit.Miles:
                        distance *= 1609.35;
                        break;
                }

                String srsDefMap = Util.GetMapSrs(map);
                MgCoordinateSystem srsMap = provider.GetMapCoordinateSystem();
                string mapSrsUnits = "";
                bool arbitraryMapSrs = (srsMap.GetType() == MgCoordinateSystemType.Arbitrary);
                if (arbitraryMapSrs)
                    mapSrsUnits = srsMap.GetUnits();

                String xtrans = String.Format("{0:x2}", ((int)(255 * Convert.ToInt32(numFillTransparency.Value) / 100))); //NOXLATE
                var lineColor = Util.ToHtmlColor(pnlBorderColor.BackColor);
                var foreColor = Util.ToHtmlColor(pnlFillColor.BackColor);
                var backColor = Util.ToHtmlColor(pnlFillBackColor.BackColor);
                String layerTempl = string.Format(Properties.Resources.AreaLayerDef,
                        fsId.ToString(),
                        "BufferSchema:Buffer", //NOXLATE
                        "GEOM", //NOXLATE
                        cmbFillPattern.SelectedItem,
                        xtrans + foreColor,
                        ((0 != 1/*transparent*/) ? "ff" : "00") + backColor, //NOXLATE
                        cmbBorderPattern.SelectedItem,
                        numLineThickness.Value.ToString(NumberFormatInfo.InvariantInfo),
                        lineColor
                );
                byte[] bytes = Encoding.UTF8.GetBytes(layerTempl);
                MgByteSource src = new MgByteSource(bytes, bytes.Length);
                MgByteReader layerDefContent = src.GetReader();
                _resSvc.SetResource(ldfId, layerDefContent, null);

                bool newBuffer = false;
                if (layer == null)
                {
                    newBuffer = true;

                    //Targetting a new layer. create a data source for it
                    //
                    MgClassDefinition classDef = new MgClassDefinition();

                    classDef.SetName("Buffer"); //NOXLATE
                    classDef.SetDescription("Feature class for buffer layer"); //NOXLATE
                    classDef.SetDefaultGeometryPropertyName("GEOM"); //NOXLATE

                    //Set KEY property
                    MgDataPropertyDefinition prop = new MgDataPropertyDefinition("KEY"); //NOXLATE
                    prop.SetDataType(MgPropertyType.Int32);
                    prop.SetAutoGeneration(true);
                    prop.SetReadOnly(true);
                    classDef.GetIdentityProperties().Add(prop);
                    classDef.GetProperties().Add(prop);

                    //Set ID property. Hold this segment ID
                    prop = new MgDataPropertyDefinition("ID"); //NOXLATE
                    prop.SetDataType(MgPropertyType.Int32);
                    classDef.GetProperties().Add(prop);

                    //Set geometry property
                    MgGeometricPropertyDefinition geomProp = new MgGeometricPropertyDefinition("GEOM"); //NOXLATE
                    //prop.SetGeometryTypes(MgFeatureGeometricType.mfgtSurface); //TODO use the constant when exposed
                    geomProp.SetGeometryTypes(4);
                    classDef.GetProperties().Add(geomProp);

                    //Create the schema
                    MgFeatureSchema schema = new MgFeatureSchema("BufferSchema", "Temporary buffer schema"); //NOXLATE
                    schema.GetClasses().Add(classDef);

                    //finally, creation of the feature source
                    MgFileFeatureSourceParams sdfParams = new MgFileFeatureSourceParams("OSGeo.SDF", "LatLong", map.GetMapSRS(), schema); //NOXLATE
                    _featSvc.CreateFeatureSource(fsId, sdfParams);

                    //Add layer to map
                    layer = provider.CreateLayer(ldfId);
                    layer.SetName(txtBufferLayer.Text);
                    layer.SetLegendLabel(txtBufferLayer.Text);
                    layer.SetDisplayInLegend(true);
                    layer.SetSelectable(true);
                    layers.Insert(0, layer);
                }
                else
                {
                    //data source already exist. clear its content
                    //
                    Util.ClearDataSource(_featSvc, fsId, "BufferSchema:Buffer"); //NOXLATE
                }

                var sel = _viewer.GetSelection();
                var selLayers = sel.GetLayers();

                MgAgfReaderWriter agfRW = new MgAgfReaderWriter();
                MgGeometryCollection bufferGeometries = new MgGeometryCollection();
                MgGeometry geomBuffer;

                MgFeatureCommandCollection commands = new MgFeatureCommandCollection();
                int featId = 0;

                MgBatchPropertyCollection propCollection = new MgBatchPropertyCollection();

                int excludedLayers = 0;
                MgCoordinateSystem srsDs = null;
                MgGeometryCollection inputGeometries = new MgGeometryCollection();

                int bufferFeatures = 0;
                for (int li = 0; li < selLayers.GetCount(); li++)
                {
                    MgLayerBase selLayer = selLayers.GetItem(li);
                    bool inputLayer = false;
                    String selLayerName = selLayer.GetName();
                    for (int il = 0; il < layerNames.Length; il++)
                    {
                        if (layerNames[il].Equals(selLayerName))
                        {
                            inputLayer = true;
                            break;
                        }
                    }
                    if (inputLayer == false)
                    {
                        continue;
                    }

                    // get the data source SRS
                    //
                    MgResourceIdentifier featSourceId = new MgResourceIdentifier(selLayer.GetFeatureSourceId());
                    MgSpatialContextReader ctxs = _featSvc.GetSpatialContexts(featSourceId, false);
                    String srsDefDs = string.Empty;
                    if (ctxs != null && ctxs.ReadNext())
                        srsDefDs = ctxs.GetCoordinateSystemWkt();

                    if (srsDefDs == null || srsDefDs.Length == 0)
                    {
                        excludedLayers++;
                        continue;
                    }

                    var srsFactory = new MgCoordinateSystemFactory();
                    srsDs = srsFactory.Create(srsDefDs);
                    bool arbitraryDsSrs = (srsDs.GetType() == MgCoordinateSystemType.Arbitrary);
                    String dsSrsUnits = string.Empty;

                    if (arbitraryDsSrs)
                        dsSrsUnits = srsDs.GetUnits();

                    // exclude layer if:
                    //  the map is non-arbitrary and the layer is arbitrary or vice-versa
                    //     or
                    //  layer and map are both arbitrary but have different units
                    //
                    if ((arbitraryDsSrs != arbitraryMapSrs) || (arbitraryDsSrs && (dsSrsUnits != mapSrsUnits)))
                    {
                        excludedLayers++;
                        continue;
                    }

                    // calculate distance in the data source SRS units
                    //
                    double dist = srsDs.ConvertMetersToCoordinateSystemUnits(distance);

                    // calculate great circle unless data source srs is arbitrary
                    MgCoordinateSystemMeasure measure;
                    if (!arbitraryDsSrs)
                        measure = srsDs.GetMeasure();
                    else
                        measure = null;

                    // create a SRS transformer if necessary
                    MgCoordinateSystemTransform srsXform;
                    if (!srsDefDs.Equals(srsDefMap))
                        srsXform = srsFactory.GetTransform(srsDs, srsMap);
                    else
                        srsXform = null;

                    String featureClassName = selLayer.GetFeatureClassName();
                    String filter = sel.GenerateFilter(selLayer, featureClassName);
                    if (filter == null || filter.Length == 0)
                        continue;

                    MgFeatureQueryOptions query = new MgFeatureQueryOptions();
                    query.SetFilter(filter);

                    MgResourceIdentifier featureSource = new MgResourceIdentifier(selLayer.GetFeatureSourceId());

                    MgFeatureReader features = _featSvc.SelectFeatures(featureSource, featureClassName, query);

                    if (features.ReadNext())
                    {
                        MgClassDefinition classDef = features.GetClassDefinition();
                        String geomPropName = classDef.GetDefaultGeometryPropertyName();

                        do
                        {
                            MgByteReader geomReader = features.GetGeometry(geomPropName);
                            MgGeometry geom = agfRW.Read(geomReader);

                            if (!chkMergeBuffers.Checked)
                            {
                                geomBuffer = geom.Buffer(dist, measure);
                                if (geomBuffer != null)
                                {
                                    if (srsXform != null)
                                        geomBuffer = (MgGeometry)geomBuffer.Transform(srsXform);
                                    Util.AddFeatureToCollection(propCollection, agfRW, featId++, geomBuffer);
                                    bufferFeatures++;
                                }
                            }
                            else
                            {
                                if (srsXform != null)
                                    geom = (MgGeometry)geom.Transform(srsXform);
                                inputGeometries.Add(geom);
                            }
                        }
                        while (features.ReadNext());

                        features.Close();
                    }
                }

                if (chkMergeBuffers.Checked)
                {
                    if (inputGeometries.GetCount() > 0)
                    {
                        double dist = srsMap.ConvertMetersToCoordinateSystemUnits(distance);
                        MgCoordinateSystemMeasure measure;
                        if (!arbitraryMapSrs)
                            measure = srsMap.GetMeasure();
                        else
                            measure = null;

                        MgGeometryFactory geomFactory = new MgGeometryFactory();
                        geomBuffer = geomFactory.CreateMultiGeometry(inputGeometries).Buffer(dist, measure);
                        if (geomBuffer != null)
                        {
                            Util.AddFeatureToCollection(propCollection, agfRW, featId, geomBuffer);
                            bufferFeatures = 1;
                        }
                    }
                }

                if (propCollection.GetCount() > 0)
                {
                    commands.Add(new MgInsertFeatures("BufferSchema:Buffer", propCollection)); //NOXLATE

                    //Insert the features in the temporary data source
                    //
                    Util.ReleaseReader(_featSvc.UpdateFeatures(fsId, commands, false), commands);
                }

                // Save the new map state
                //
                layer.ForceRefresh();
                _viewer.RefreshMap();

                //build report message
                if (newBuffer)
                    MessageBox.Show(string.Format(Strings.MsgBufferLayerCreated, txtBufferLayer.Text));
                else
                    MessageBox.Show(string.Format(Strings.MsgBufferLayerUpdated, txtBufferLayer.Text));
            }
            finally
            {
                btnCreate.Enabled = true;
            }
        }
Exemplo n.º 18
0
        private string CreateRedlineLayerDefinitionContent(MgResourceIdentifier fsId, string className, RedlineStyle style, RedlineStylizationType type)
        {
            double transpc           = (100 - style.FillTransparency) / 100;
            string hexFgTransparency = string.Format("{0:X2}", Convert.ToInt32(255 * transpc)); //Convert % to alpha value
            string hexBgTransparency = style.FillBackTransparency ? "FF" : "00";                //All or nothing

            if (type == RedlineStylizationType.Basic)
            {
                string template = Strings.markuplayerdefinition;
                return(Util.Substitute(template,
                                       new string [] {
                    fsId.ToString(),                                                //<ResourceId> - Feature Source
                    className,                                                      //<FeatureName> - Class Name
                    style.LabelSizeUnits.ToString(),                                //<Unit> - Mark Label
                    style.LabelFontSize.ToString(CultureInfo.InvariantCulture),     //<SizeX> - Mark Label Size
                    style.LabelFontSize.ToString(CultureInfo.InvariantCulture),     //<SizeY> - Mark Label Size
                    "FF" + Util.ToHtmlColor(style.LabelForeColor),                  //<ForegroundColor> - Mark Label
                    "FF" + Util.ToHtmlColor(style.LabelBackColor),                  //<BackgroundColor> - Mark Label
                    style.LabelBackStyle.ToString(),                                //<BackgroundStyle> - Mark Label
                    style.LabelBold.ToString().ToLower(),                           //<Bold> - Mark Label
                    style.LabelItalic.ToString().ToLower(),                         //<Bold> - Mark Label
                    style.LabelUnderline.ToString().ToLower(),                      //<Underlined> - Mark Label
                    style.MarkerSizeUnits.ToString(),                               //<Unit> - Mark
                    style.MarkerSize.ToString(CultureInfo.InvariantCulture),        //<SizeX> - Mark
                    style.MarkerSize.ToString(CultureInfo.InvariantCulture),        //<SizeY> - Mark
                    style.MarkerType.ToString(),                                    //<Shape> - Mark
                    "FF" + Util.ToHtmlColor(style.MarkerColor),                     //<ForegroundColor> - Mark
                    "FF" + Util.ToHtmlColor(style.MarkerColor),                     //<Color> - Mark
                    style.LabelSizeUnits.ToString(),                                //<Unit> - Line Label
                    style.LabelFontSize.ToString(CultureInfo.InvariantCulture),     //<SizeX> - Line Label Size
                    style.LabelFontSize.ToString(CultureInfo.InvariantCulture),     //<SizeY> - Line Label Size
                    "FF" + Util.ToHtmlColor(style.LabelForeColor),                  //<ForegroundColor> - Line Label
                    "FF" + Util.ToHtmlColor(style.LabelBackColor),                  //<BackgroundColor> - Line Label
                    style.LabelBackStyle.ToString(),                                //<BackgroundStyle> - Line Label
                    style.LabelBold.ToString().ToLower(),                           //<Bold> - Line Label
                    style.LabelItalic.ToString().ToLower(),                         //<Bold> - Line Label
                    style.LabelUnderline.ToString().ToLower(),                      //<Underlined> - Line Label
                    style.LinePattern.ToString(),                                   //<LineStyle> - Line
                    style.LineThickness.ToString(CultureInfo.InvariantCulture),     //<Thickness> - Line
                    "FF" + Util.ToHtmlColor(style.LineColor),                       //<Color> - Line
                    style.LineSizeUnits.ToString(),                                 //<Unit> - Line
                    style.LabelSizeUnits.ToString(),                                //<Unit> - Polygon Label
                    style.LabelFontSize.ToString(CultureInfo.InvariantCulture),     //<SizeX> - Polygon Label Size
                    style.LabelFontSize.ToString(CultureInfo.InvariantCulture),     //<SizeY> - Polygon Label Size
                    "FF" + Util.ToHtmlColor(style.LabelForeColor),                  //<ForegroundColor> - Polygon Label
                    "FF" + Util.ToHtmlColor(style.LabelBackColor),                  //<BackgroundColor> - Polygon Label
                    style.LabelBackStyle.ToString(),                                //<BackgroundStyle> - Polygon Label
                    style.LabelBold.ToString().ToLower(),                           //<Bold> - Polygon Label
                    style.LabelItalic.ToString().ToLower(),                         //<Bold> - Polygon Label
                    style.LabelUnderline.ToString().ToLower(),                      //<Underlined> - Polygon Label
                    style.FillPattern.ToString(),                                   //<FillPattern> - Fill
                    hexFgTransparency + Util.ToHtmlColor(style.FillForeColor),      //<ForegroundColor> - Fill
                    hexBgTransparency + Util.ToHtmlColor(style.FillBackColor),      //<BackgroundColor> - Fill
                    style.BorderPattern.ToString(),                                 //<LineStyle> - Fill
                    style.BorderThickness.ToString(CultureInfo.InvariantCulture),   //<Thickness> - Fill
                    "FF" + Util.ToHtmlColor(style.BorderColor),                     //<Color> - Fill
                    style.BorderSizeUnits.ToString()                                //<Unit> - Fill
                }));
            }
            else
            {
                StringBuilder template       = new StringBuilder(Strings.markuplayerdefinition_advanced);
                double        fontHeight     = SizeInMM(style.LabelFontSize, style.LabelSizeUnits);
                string        labelForeColor = "FF" + Util.ToHtmlColor(style.LabelForeColor);
                string        labelBackColor = "FF" + Util.ToHtmlColor(style.LabelBackColor);

                //Substitute inner templates first, so their placeholders tokens are also brought in
                template.Replace("#{FILL_PATTERN_TEMPLATE}", GetFillPatternTemplate(style.FillPattern));
                template.Replace("#{BORDER_PATTERN_TEMPLATE}", GetBorderPatternGeometry(style.BorderPattern));

                //For non-opaque labels we need to empty the frame fill color
                if (style.LabelBackStyle == LabelStyle.Opaque)
                {
                    template.Replace("#{FRAME_FILL_COLOR}", "0xffffffff");
                }
                else
                {
                    template.Replace("#{FRAME_FILL_COLOR}", string.Empty);
                    if (style.LabelBackStyle == LabelStyle.Transparent)
                    {
                        labelBackColor = string.Empty;
                    }
                }

                //I don't think this is correct wrt to the UI, but this is to replicate the behaviour that we currently have under basic stylization
                //If fill is solid and background color is fully transparent, comment that portion out of the composite type style as it will interfere
                //with the area foreground symbol
                if (style.FillPattern == FillPattern.Solid && hexBgTransparency == "FF")
                {
                    template.Replace("#{START_BACKGROUND_FILL}", "<!--");
                    template.Replace("#{END_BACKGROUND_FILL}", "-->");
                }
                else
                {
                    template.Replace("#{START_BACKGROUND_FILL}", "");
                    template.Replace("#{END_BACKGROUND_FILL}", "");
                }

                //Then do a find/replace of all known tokens
                template.Replace("#{RESOURCE_ID}", fsId.ToString());
                template.Replace("#{FEATURE_CLASS}", className);
                template.Replace("#{FONT_HEIGHT}", fontHeight.ToString(CultureInfo.InvariantCulture));
                template.Replace("#{LABEL_FORE_COLOR}", labelForeColor);
                template.Replace("#{LABEL_BACK_COLOR}", labelBackColor);
                template.Replace("#{BOLD}", style.LabelBold.ToString().ToLower());
                template.Replace("#{ITALIC}", style.LabelItalic.ToString().ToLower());
                template.Replace("#{UNDERLINE}", style.LabelUnderline.ToString().ToLower());
                template.Replace("#{MARKER_GEOMETRY}", GetMarkerGeometry(style.MarkerType));
                template.Replace("#{MARKER_SIZE_X}", GetMarkerSize(style.MarkerSize, style.MarkerSizeUnits));
                template.Replace("#{MARKER_SIZE_Y}", GetMarkerSize(style.MarkerSize, style.MarkerSizeUnits));
                template.Replace("#{MARKER_COLOR}", "FF" + Util.ToHtmlColor(style.MarkerColor));
                template.Replace("#{LINE_PATTERN_GEOMETRY}", GetLinePatternGeometry(style.LinePattern));
                template.Replace("#{LINE_THICKNESS}", GetLineThickness(style.LineThickness, style.LineSizeUnits));
                template.Replace("#{LINE_COLOR}", "FF" + Util.ToHtmlColor(style.LineColor));
                template.Replace("#{FILL_BACK_COLOR}", hexBgTransparency + Util.ToHtmlColor(style.FillBackColor));
                template.Replace("#{FILL_FORE_COLOR}", hexFgTransparency + Util.ToHtmlColor(style.FillForeColor));
                template.Replace("#{BORDER_THICKNESS}", SizeInMM(style.BorderThickness, style.BorderSizeUnits).ToString(CultureInfo.InvariantCulture));
                template.Replace("#{BORDER_COLOR}", "FF" + Util.ToHtmlColor(style.BorderColor));

                //Fill in the UI values under ExtendedData, so we can read from this element if we need to go back to Edit Style UI
                template.Replace("#{MG_RESOURCE_ID}", fsId.ToString());
                template.Replace("#{MG_FEATURE_CLASS}", className);
                template.Replace("#{MG_FILL_PATTERN}", style.FillPattern.ToString());
                template.Replace("#{MG_BORDER_PATTERN}", style.BorderPattern.ToString());
                template.Replace("#{MG_LINE_PATTERN}", style.LinePattern.ToString());
                template.Replace("#{MG_LABEL_FONT_SIZE}", style.LabelFontSize.ToString(CultureInfo.InvariantCulture));
                template.Replace("#{MG_LABEL_FONT_UNITS}", style.LabelSizeUnits.ToString());
                template.Replace("#{MG_LABEL_FORECOLOR}", Util.ToHtmlColor(style.LabelForeColor));
                template.Replace("#{MG_LABEL_BACKCOLOR}", Util.ToHtmlColor(style.LabelBackColor));
                template.Replace("#{MG_BOLD}", style.LabelBold.ToString().ToLower());
                template.Replace("#{MG_ITALIC}", style.LabelItalic.ToString().ToLower());
                template.Replace("#{MG_UNDERLINE}", style.LabelUnderline.ToString().ToLower());
                template.Replace("#{MG_MARKER_TYPE}", style.MarkerType.ToString());
                template.Replace("#{MG_MARKER_SIZE}", style.MarkerSize.ToString(CultureInfo.InvariantCulture));
                template.Replace("#{MG_MARKER_UNITS}", style.MarkerSizeUnits.ToString());
                template.Replace("#{MG_MARKER_COLOR}", Util.ToHtmlColor(style.MarkerColor));
                template.Replace("#{MG_LINE_THICKNESS}", style.LineThickness.ToString(CultureInfo.InvariantCulture));
                template.Replace("#{MG_LINE_UNITS}", style.LineSizeUnits.ToString());
                template.Replace("#{MG_LINE_COLOR}", Util.ToHtmlColor(style.LineColor));
                template.Replace("#{MG_FILL_BACK_COLOR}", Util.ToHtmlColor(style.FillBackColor));
                template.Replace("#{MG_FILL_FORE_COLOR}", Util.ToHtmlColor(style.FillForeColor));
                template.Replace("#{MG_FILL_FORE_TRANSPARENCY}", hexFgTransparency);
                template.Replace("#{MG_FILL_BACK_TRANSPARENCY}", hexBgTransparency);
                template.Replace("#{MG_BORDER_THICKNESS}", style.BorderThickness.ToString(CultureInfo.InvariantCulture));
                template.Replace("#{MG_BORDER_UNITS}", style.BorderSizeUnits.ToString());
                template.Replace("#{MG_BORDER_COLOR}", Util.ToHtmlColor(style.BorderColor));
                template.Replace("#{MG_LABEL_STYLE}", style.LabelBackStyle.ToString());

                return(template.ToString());
            }
        }
Exemplo n.º 19
0
        private void CheckRedlineLayer()
        {
            if (_redlineLayer == null)
            {
                MgdMap map = (MgdMap)_viewer.GetMap();
                MgMapViewerProvider provider = _viewer.GetProvider();
                MgdFeatureService featSvc = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService);
                MgResourceService resSvc = (MgResourceService)provider.CreateService(MgServiceType.ResourceService);

                string sessionId = Guid.NewGuid().ToString();
                MgResourceIdentifier fsId = new MgResourceIdentifier("Session:" + sessionId + "//Redline.FeatureSource");
                MgResourceIdentifier ldfId = new MgResourceIdentifier("Session:" + sessionId + "//Redline.LayerDefinition");
                string featureClass = "Default:Redline";
                string geometry = "Geometry";
                string xml = string.Format(Layers.Redline, fsId.ToString(), featureClass, geometry);

                //Construct our schema for the redline data store
                MgFeatureSchema schema = new MgFeatureSchema("Default", "Redline schema");
                MgClassDefinition cls = new MgClassDefinition();
                cls.Name = "Redline";

                MgDataPropertyDefinition id = new MgDataPropertyDefinition("ID");
                id.DataType = MgPropertyType.Int32;
                id.SetAutoGeneration(true);

                MgGeometricPropertyDefinition geom = new MgGeometricPropertyDefinition(geometry);
                geom.SpatialContextAssociation = "Default";
                geom.GeometryTypes = MgFeatureGeometricType.Curve | MgFeatureGeometricType.Point | MgFeatureGeometricType.Solid | MgFeatureGeometricType.Surface;

                MgPropertyDefinitionCollection clsProps = cls.GetProperties();
                clsProps.Add(id);
                clsProps.Add(geom);

                MgPropertyDefinitionCollection idProps = cls.GetIdentityProperties();
                idProps.Add(id);

                cls.DefaultGeometryPropertyName = geometry;
                MgClassDefinitionCollection classes = schema.GetClasses();
                classes.Add(cls);

                //Create the feature source
                MgCreateSdfParams create = new MgCreateSdfParams("Default", map.GetMapSRS(), schema);
                featSvc.CreateFeatureSource(fsId, create);

                //Then the layer definition
                byte[] bytes = Encoding.UTF8.GetBytes(xml);
                MgByteSource source = new MgByteSource(bytes, bytes.Length);
                resSvc.SetResource(ldfId, source.GetReader(), null);

                //Now create the runtime layer and add to map
                _redlineLayer = new MgdLayer(ldfId, resSvc);
                _redlineLayer.LegendLabel = "Redlining";
                _redlineLayer.Name = "Redline";
                _redlineLayer.Visible = true;
                _redlineLayer.Selectable = true;
                _redlineLayer.DisplayInLegend = true;

                MgLayerCollection layers = map.GetLayers();
                layers.Insert(0, _redlineLayer);
            }
        }
Exemplo n.º 20
0
        public RedlineLayer CreateRedlineLayer(CreateRedlineLayerParams param, out bool bAddedToMap)
        {
            bAddedToMap = false;
            MgResourceIdentifier fsId = GenerateRedlineFeatureSourceId(param);

            string className    = null;
            string providerName = null;

            if (_resSvc.ResourceExists(fsId))
            {
                MgFeatureSchemaCollection   schemas = _featSvc.DescribeSchema(fsId, string.Empty, null);
                MgFeatureSchema             schema  = schemas.GetItem(0);
                MgClassDefinitionCollection classes = schema.GetClasses();
                MgClassDefinition           cls     = classes.GetItem(0);
                className = schema.Name + ":" + cls.Name;
            }
            else
            {
                MgFeatureSchema schema = RedlineSchemaFactory.CreateSchema(param.GeometryTypes);

                providerName = "OSGeo.SDF";
                if (param.Format == RedlineDataStoreFormat.SHP)
                {
                    providerName = "OSGeo.SHP";
                }
                else if (param.Format == RedlineDataStoreFormat.SQLite)
                {
                    providerName = "OSGeo.SQLite";
                }

                MgFileFeatureSourceParams createParams = new MgFileFeatureSourceParams(providerName, RedlineSchemaFactory.SPATIAL_CONTEXT, _map.GetMapSRS(), schema);
                _featSvc.CreateFeatureSource(fsId, createParams);

                //HACK: SQLite leaky abstraction (hard-coded schema name), SHP probably has some leaks of its own, so we can't assume MarkupSchema:Markup
                //as the class name so re-interrogate our schema to figure it out
                MgFeatureSchemaCollection schemas = _featSvc.DescribeSchema(fsId, string.Empty, null);
                schema = schemas.GetItem(0);
                MgClassDefinitionCollection classes = schema.GetClasses();
                MgClassDefinition           cls     = classes.GetItem(0);
                className = schema.Name + ":" + cls.Name;
            }

            MgResourceIdentifier ldfId = GenerateRedlineLayerDefinitionId(param);

            if (!_resSvc.ResourceExists(ldfId))
            {
                string       layerDefContent = CreateRedlineLayerDefinitionContent(fsId, className, param.Style, param.StyleType);
                byte[]       bytes           = Encoding.UTF8.GetBytes(layerDefContent);
                MgByteSource byteSource      = new MgByteSource(bytes, bytes.Length);
                MgByteReader byteReader      = byteSource.GetReader();

                _resSvc.SetResource(ldfId, byteReader, null);
            }

            if (param.AddToMap)
            {
                AddRedlineLayerToMap(ldfId);
                bAddedToMap = true;
            }

            var layer = new RedlineLayer(ldfId.Name, fsId.ToString(), ldfId.ToString(), param.GeometryTypes, param.StyleType);

            //If provider name was set, then we register this layer in the registry. Otherwise it means
            //the layer already exists and by extension already registered
            if (providerName != null)
            {
                _registry.AddRedlineLayer(layer, providerName);
            }
            return(layer);
        }
Exemplo n.º 21
0
        public override void Execute(IPlatformFactory factory, ITestLogger logger)
        {
            //For a map definition that links to a default provider tile set and both have the same coordinate
            //system, it should be using the map definition's extents and we should not have null extents or view
            //center

            MgCoordinateSystemFactory csFactory = new MgCoordinateSystemFactory();
            string csWkt = csFactory.ConvertCoordinateSystemCodeToWkt("LL84");

            MgResourceService resSvc = (MgResourceService)factory.CreateService(MgServiceType.ResourceService);

            var root = "../../TestData/TileService/";

            LoadResource(resSvc, "Library://UnitTests/Data/RoadCenterLines.FeatureSource", root + "UT_RoadCenterLines.fs");
            LoadResourceData(resSvc, "Library://UnitTests/Data/RoadCenterLines.FeatureSource", "UT_RoadCenterLines.sdf", MgResourceDataType.File, root + "UT_RoadCenterLines.sdf");
            LoadResource(resSvc, "Library://UnitTests/Layers/RoadCenterLines.LayerDefinition", root + "UT_RoadCenterLines.ldf");

            LoadResource(resSvc, "Library://UnitTests/Data/VotingDistricts.FeatureSource", root + "UT_VotingDistricts.fs");
            LoadResourceData(resSvc, "Library://UnitTests/Data/VotingDistricts.FeatureSource", "UT_VotingDistricts.sdf", MgResourceDataType.File, root + "UT_VotingDistricts.sdf");
            LoadResource(resSvc, "Library://UnitTests/Layers/VotingDistricts.LayerDefinition", root + "UT_VotingDistricts.ldf");

            LoadResource(resSvc, "Library://UnitTests/Data/Parcels.FeatureSource", root + "UT_Parcels.fs");
            LoadResourceData(resSvc, "Library://UnitTests/Data/Parcels.FeatureSource", "UT_Parcels.sdf", MgResourceDataType.File, root + "UT_Parcels.sdf");
            LoadResource(resSvc, "Library://UnitTests/Layers/Parcels.LayerDefinition", root + "UT_Parcels.ldf");

            string tsd = Encoding.UTF8.GetString(Properties.Resources.UT_BaseMapTileSet);

            tsd = string.Format(tsd, csWkt, -87.5, 43.5, -86.5, 44.5);
            byte[]               tsdBytes   = Encoding.UTF8.GetBytes(tsd);
            MgByteSource         sourceTSD  = new MgByteSource(tsdBytes, tsdBytes.Length);
            MgByteReader         contentTSD = sourceTSD.GetReader();
            MgResourceIdentifier resTSD     = new MgResourceIdentifier("Library://UnitTests/TileSets/Test.TileSetDefinition");

            resSvc.SetResource(resTSD, contentTSD, null);

            string mdf = Encoding.UTF8.GetString(Properties.Resources.UT_LinkedTileSet);

            mdf = string.Format(mdf, csWkt, -87.0, 43.0, -86.0, 44.0, resTSD.ToString());
            byte[]               mdfBytes   = Encoding.UTF8.GetBytes(mdf);
            MgByteSource         sourceMDF  = new MgByteSource(mdfBytes, mdfBytes.Length);
            MgByteReader         contentMDF = sourceMDF.GetReader();
            MgResourceIdentifier resMDF     = new MgResourceIdentifier("Library://UnitTests/Maps/LinkedTileSet.MapDefinition");

            resSvc.SetResource(resMDF, contentMDF, null);

            MgMapBase  map    = factory.CreateMap(resMDF);
            MgEnvelope extent = map.GetMapExtent();

            Assert.IsNotNull(extent);
            Assert.IsNotNull(map.MapExtent);
            MgPoint center = map.GetViewCenter();

            Assert.IsNotNull(center);
            Assert.IsNotNull(map.ViewCenter);

            MgCoordinate ll = extent.GetLowerLeftCoordinate();
            MgCoordinate ur = extent.GetUpperRightCoordinate();

            Assert.IsNotNull(ll);
            Assert.IsNotNull(ur);

            Assert.AreEqual(-87.0, ll.X);
            Assert.AreEqual(43.0, ll.Y);
            Assert.AreEqual(-86.0, ur.X);
            Assert.AreEqual(44.0, ur.Y);
        }
Exemplo n.º 22
0
        public void CreateMarkup(string mgSessionId,string  mgMap)
        {
            //Response.Write("CreateMarkup" );
            MgUserInformation userInfo = new MgUserInformation(mgSessionId);
            MgSiteConnection siteConnection = new MgSiteConnection();
            siteConnection.Open(userInfo);

            MgResourceService resourceService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService);
            MgFeatureService featureService = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService);

            MgMap map = new MgMap();
            map.Open(resourceService, mgMap);
            //    map.Open(resourceService, GetParameter(args, "MAPNAME"));

            // Create the Markup Feature Source (SDF)

            MgResourceIdentifier markupSdfResId = new MgResourceIdentifier(libraryPath + GetParameter(this.args, "MARKUPNAME") + ".FeatureSource");

            MgFeatureSchema markupSchema = MarkupSchemaFactory.CreateMarkupSchema();
            MgCreateSdfParams sdfParams = new MgCreateSdfParams("XY-M", map.MapSRS, markupSchema);
            featureService.CreateFeatureSource(markupSdfResId, sdfParams);

            String url = "concat(&apos;" + GetParameter(this.args, "MARKUPURL") + "&apos;, concat(&apos;?key=&apos;, &quot;ID&quot;))";
            //Link to ProjectManager
              /*  if (GetParameter(this.args, "LINKTOPROJECTMANAGER").ToLower() == "on"
                && !String.IsNullOrEmpty(GetParameter(this.args, "ProjectCollectionName"))
                && GetParameter(this.args, "ProjectCollectionName") != "áçø îøùéîä")
            {
                string projectCollectionName = GetParameter(this.args, "ProjectCollectionName");
                if (projectCollectionName == "àçø...")
                {
                    projectCollectionName = GetParameter(this.args, "ProjectCollectionOtherName");
                }
                int projectId = 0;
                using (var conn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["ProjectManagerConnectionString"].ConnectionString))
                {
                    var cmd = conn.CreateCommand();
                    cmd.CommandText = "INSERT INTO ProjectCollections(LayoutId, FeatureId, ProjectCollectionName) VALUES(@LayoutId, @FeatureId, @ProjectCollectionName); SELECT @@IDENTITY AS [NEWID]";
                    cmd.CommandType = System.Data.CommandType.Text;

                    var layoutIdParam = new System.Data.SqlClient.SqlParameter("@LayoutId", System.Data.SqlDbType.NVarChar, 255);
                    layoutIdParam.Value = GetParameter(args, "LAYOUT");
                    cmd.Parameters.Add(layoutIdParam);

                    var featureIdParam = new System.Data.SqlClient.SqlParameter("@FeatureId", System.Data.SqlDbType.NVarChar, 255);
                    featureIdParam.Value = markupSdfResId.ToString();
                    cmd.Parameters.Add(featureIdParam);

                    var pcNameParam = new System.Data.SqlClient.SqlParameter("@ProjectCollectionName", System.Data.SqlDbType.NVarChar, 50);
                    pcNameParam.Value = projectCollectionName;
                    cmd.Parameters.Add(pcNameParam);

                    conn.Open();
                    //projectId = (int)cmd.ExecuteScalar();
                    using (var reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            projectId = Convert.ToInt32(reader[0]);
                        }
                    }
                }
                string host = HttpContext.Current.Request.Url.Host;
                url = String.Format("concat('http://{0}/MgExtensions/ProjectManager/default.aspx?ProjectId={1}&UID=', \"UID\")", host, projectId);
            }
            */
            // Create the Markup Layer Definition

            String hexFgTransparency = String.Format("{0:X2}", 255 * (100 - Int32.Parse(GetParameter(this.args, "FILLTRANSPARENCY"))) / 100); // Convert % to an alpha value
            String hexBgTransparency = GetParameter(this.args, "FILLBACKTRANS").Length > 0 ? "FF" : "00";							 // All or nothing
            String bold = GetParameter(this.args, "LABELBOLD").Length > 0 ? "true" : "false";
            String italic = GetParameter(this.args, "LABELITALIC").Length > 0 ? "true" : "false";
            String underline = GetParameter(this.args, "LABELUNDERLINE").Length > 0 ? "true" : "false";

            String markupLayerDefinition = File.ReadAllText(HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"] + "Extensions\\markup\\templates\\markuplayerdefinition.xml");
            markupLayerDefinition = String.Format(markupLayerDefinition,
                markupSdfResId.ToString(),						                //<ResourceId> - Feature Source
                GetParameter(this.args, "LABELSIZEUNITS"),						//<Unit> - Mark Label
                GetParameter(this.args, "LABELFONTSIZE"),						//<SizeX> - Mark Label Size
                GetParameter(this.args, "LABELFONTSIZE"),						//<SizeY> - Mark Label Size
                "FF" + GetParameter(this.args, "LABELFORECOLOR"),				//<ForegroundColor> - Mark Label
                "FF" + GetParameter(this.args, "LABELBACKCOLOR"),				//<BackgroundColor> - Mark Label
                GetParameter(this.args, "LABELBACKSTYLE"),						//<BackgroundStyle> - Mark Label
                bold,												            //<Bold> - Mark Label
                italic,											                //<Bold> - Mark Label
                underline,											            //<Underlined> - Mark Label
                GetParameter(this.args, "MARKERSIZEUNITS"),						//<Unit> - Mark
                GetParameter(this.args, "MARKERSIZE"),							//<SizeX> - Mark
                GetParameter(this.args, "MARKERSIZE"),							//<SizeY> - Mark
                GetParameter(this.args, "MARKERTYPE"),							//<Shape> - Mark
                "FF" + GetParameter(this.args, "MARKERCOLOR"),					//<ForegroundColor> - Mark
                "FF" + GetParameter(this.args, "MARKERCOLOR"),					//<Color> - Mark
                GetParameter(this.args, "LABELSIZEUNITS"),						//<Unit> - Line Label
                GetParameter(this.args, "LABELFONTSIZE"),						//<SizeX> - Line Label Size
                GetParameter(this.args, "LABELFONTSIZE"),						//<SizeY> - Line Label Size
                "FF" + GetParameter(this.args, "LABELFORECOLOR"),				//<ForegroundColor> - Line Label
                "FF" + GetParameter(this.args, "LABELBACKCOLOR"),				//<BackgroundColor> - Line Label
                GetParameter(this.args, "LABELBACKSTYLE"),						//<BackgroundStyle> - Line Label
                bold,												            //<Bold> - Line Label
                italic,											                //<Bold> - Line Label
                underline,											            //<Underlined> - Line Label
                GetParameter(this.args, "LINEPATTERN"),							//<LineStyle> - Line
                GetParameter(this.args, "LINETHICKNESS"),						//<Thickness> - Line
                "FF" + GetParameter(this.args, "LINECOLOR"),					//<Color> - Line
                GetParameter(this.args, "LINESIZEUNITS"),						//<Unit> - Line
                GetParameter(this.args, "LABELSIZEUNITS"),						//<Unit> - Polygon Label
                GetParameter(this.args, "LABELFONTSIZE"),						//<SizeX> - Polygon Label Size
                GetParameter(this.args, "LABELFONTSIZE"),						//<SizeY> - Polygon Label Size
                "FF" + GetParameter(this.args, "LABELFORECOLOR"),				//<ForegroundColor> - Polygon Label
                "FF" + GetParameter(this.args, "LABELBACKCOLOR"),				//<BackgroundColor> - Polygon Label
                GetParameter(this.args, "LABELBACKSTYLE"),						//<BackgroundStyle> - Polygon Label
                bold,												            //<Bold> - Polygon Label
                italic,											                //<Bold> - Polygon Label
                underline,											            //<Underlined> - Polygon Label
                GetParameter(this.args, "FILLPATTERN"), 						//<FillPattern> - Fill
                hexFgTransparency + GetParameter(this.args, "FILLFORECOLOR"), 	//<ForegroundColor> - Fill
                hexBgTransparency + GetParameter(this.args, "FILLBACKCOLOR"), 	//<BackgroundColor> - Fill
                GetParameter(this.args, "BORDERPATTERN"),						//<LineStyle> - Fill
                GetParameter(this.args, "BORDERTHICKNESS"), 					//<Thickness> - Fill
                "FF" + GetParameter(this.args, "BORDERCOLOR"), 					//<Color> - Fill
                GetParameter(this.args, "BORDERSIZEUNITS"), 					//<Unit> - Fill
                HttpContext.Current.Server.HtmlEncode(url)); //<Url> - url link

            MgByteReader byteReader = new MgByteReader(markupLayerDefinition, "text/xml");
            resourceService.SetResource(new MgResourceIdentifier(libraryPath + GetParameter(this.args, "MARKUPNAME") + ".LayerDefinition"), byteReader, null);
        }
Exemplo n.º 23
0
        private void CreateDebugFeatureSource()
        {
            var id = new MgDataPropertyDefinition("ID"); //NOXLATE
            id.DataType = MgPropertyType.Int32;
            id.Nullable = false;
            id.SetAutoGeneration(true);

            var geom = new MgGeometricPropertyDefinition("Geometry"); //NOXLATE
            geom.GeometryTypes = MgFeatureGeometricType.Point;
            geom.SpatialContextAssociation = "MapCs"; //NOXLATE

            var cls = new MgClassDefinition();
            cls.Name = "Debug"; //NOXLATE
            var props = cls.GetProperties();
            props.Add(id);
            props.Add(geom);

            var idProps = cls.GetIdentityProperties();
            idProps.Add(id);

            cls.DefaultGeometryPropertyName = "Geometry"; //NOXLATE

            var schema = new MgFeatureSchema("Default", "Default schema"); //NOXLATE
            var classes = schema.GetClasses();
            classes.Add(cls);

            //We can make anything up here, there's no real concept of sessions
            var sessionId = Guid.NewGuid().ToString();

            var debugFsId = new MgResourceIdentifier("Session:" + sessionId + "//Debug" + Guid.NewGuid().ToString() + ".FeatureSource"); //NOXLATE
            var createSdf = new MgCreateSdfParams("MapCs", _map.GetMapSRS(), schema); //NOXLATE
            var featureSvc = (MgdFeatureService)fact.CreateService(MgServiceType.FeatureService);
            var resSvc = (MgResourceService)fact.CreateService(MgServiceType.ResourceService);
            featureSvc.CreateFeatureSource(debugFsId, createSdf);

            byte[] bytes = Encoding.UTF8.GetBytes(string.Format(Debug.DebugLayer, debugFsId.ToString(), "Default:Debug", "Geometry")); //NOXLATE
            var source = new MgByteSource(bytes, bytes.Length);

            var debugLayerId = new MgResourceIdentifier("Session:" + sessionId + "//" + debugFsId.Name + ".LayerDefinition"); //NOXLATE
            var breader = source.GetReader();
            resSvc.SetResource(debugLayerId, breader, null);
            
            _debugLayer = new MgdLayer(debugLayerId, resSvc);
            _debugLayer.SetLegendLabel("Debug Layer"); //NOXLATE
            _debugLayer.SetVisible(true);
            _debugLayer.SetDisplayInLegend(true);

            var mapLayers = _map.GetLayers();
            mapLayers.Insert(0, _debugLayer);

            UpdateCenterDebugPoint();
        }
Exemplo n.º 24
0
    public bool ShowSpatialFilter()
    {
        bool result = true;
        MgUserInformation userInfo = new MgUserInformation(Request["SESSION"]);
        MgSiteConnection siteConnection = new MgSiteConnection();
        siteConnection.Open(userInfo);

        MgResourceIdentifier sdfResId = new MgResourceIdentifier("Session:" + Request["SESSION"] + "//Filter.FeatureSource");

        MgResourceService resourceService = siteConnection.CreateService(MgServiceType.ResourceService) as MgResourceService;
        MgFeatureService featureService = siteConnection.CreateService(MgServiceType.FeatureService) as MgFeatureService;

        MgFeatureCommandCollection updateCommands = new MgFeatureCommandCollection();

        MgMap map = new MgMap();
        map.Open(resourceService, Request["MAPNAME"]);

        MgLayer layer = null;
        MgLayerCollection layers = map.GetLayers();
        if (layers.Contains("_QuerySpatialFilter"))
        {
            layer = (MgLayer)layers.GetItem("_QuerySpatialFilter");
            //updateCommands.Add(new MgDeleteFeatures("Filter", "ID > 0"));
        }
        else
        {
            // Create the Feature Source (SDF)

            MgFeatureSchema sdfSchema = this.CreateFilterSchema();
            MgCreateSdfParams sdfParams = new MgCreateSdfParams("MAPCS", map.GetMapSRS(), sdfSchema);
            featureService.CreateFeatureSource(sdfResId, sdfParams);

            // Create the Layer

            MgResourceIdentifier layerResId = new MgResourceIdentifier("Session:" + Request["SESSION"] + "//Filter.LayerDefinition");
            String layerDefinition = File.ReadAllText(GetQueryXmlTemplatePath());
            layerDefinition = layerDefinition.Replace("%s", sdfResId.ToString());

            MgByteReader reader = new MgByteReader(layerDefinition, "text/xml");
            resourceService.SetResource(layerResId, reader, null);

            layer = new MgLayer(layerResId, resourceService);

            layer.SetName("_QuerySpatialFilter");
            layer.SetLegendLabel("תחום זמני");
            layer.SetDisplayInLegend(true);
            layer.SetSelectable(true);
            layer.ForceRefresh();
            layer.NeedsRefresh();

            layers.Insert(0, layer);
        }

        // Make the layer visible

        layer.SetVisible(true);
        map.Save(resourceService);

        // Add the geometry to the filter feature source
        MgPolygon polygon = this.CreatePolygonFromGeomText(Request["GEOMTEXT"].ToString());
        MgAgfReaderWriter agfWriter = new MgAgfReaderWriter();
        MgByteReader byteReader = agfWriter.Write(polygon);

        MgPropertyCollection propertyValues = new MgPropertyCollection();
        propertyValues.Add(new MgGeometryProperty("Geometry", byteReader));
        try
        {
            updateCommands.Add(new MgInsertFeatures("Filter", propertyValues));

            featureService.UpdateFeatures(sdfResId, updateCommands, false);
        }
        catch { }

        return result;
    }
Exemplo n.º 25
0
        private void CheckRedlineLayer()
        {
            if (_redlineLayer == null)
            {
                MgdMap map = (MgdMap)_viewer.GetMap();
                MgMapViewerProvider provider = _viewer.GetProvider();
                MgdFeatureService   featSvc  = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService);
                MgResourceService   resSvc   = (MgResourceService)provider.CreateService(MgServiceType.ResourceService);

                string sessionId           = Guid.NewGuid().ToString();
                MgResourceIdentifier fsId  = new MgResourceIdentifier("Session:" + sessionId + "//Redline.FeatureSource");
                MgResourceIdentifier ldfId = new MgResourceIdentifier("Session:" + sessionId + "//Redline.LayerDefinition");
                string featureClass        = "Default:Redline";
                string geometry            = "Geometry";
                string xml = string.Format(Layers.Redline, fsId.ToString(), featureClass, geometry);

                //Construct our schema for the redline data store
                MgFeatureSchema   schema = new MgFeatureSchema("Default", "Redline schema");
                MgClassDefinition cls    = new MgClassDefinition();
                cls.Name = "Redline";

                MgDataPropertyDefinition id = new MgDataPropertyDefinition("ID");
                id.DataType = MgPropertyType.Int32;
                id.SetAutoGeneration(true);

                MgGeometricPropertyDefinition geom = new MgGeometricPropertyDefinition(geometry);
                geom.SpatialContextAssociation = "Default";
                geom.GeometryTypes             = MgFeatureGeometricType.Curve | MgFeatureGeometricType.Point | MgFeatureGeometricType.Solid | MgFeatureGeometricType.Surface;

                MgPropertyDefinitionCollection clsProps = cls.GetProperties();
                clsProps.Add(id);
                clsProps.Add(geom);

                MgPropertyDefinitionCollection idProps = cls.GetIdentityProperties();
                idProps.Add(id);

                cls.DefaultGeometryPropertyName = geometry;
                MgClassDefinitionCollection classes = schema.GetClasses();
                classes.Add(cls);

                //Create the feature source
                MgFileFeatureSourceParams create = new MgFileFeatureSourceParams("OSGeo.SDF", "Default", map.GetMapSRS(), schema);
                featSvc.CreateFeatureSource(fsId, create);

                //Then the layer definition
                byte[]       bytes  = Encoding.UTF8.GetBytes(xml);
                MgByteSource source = new MgByteSource(bytes, bytes.Length);
                resSvc.SetResource(ldfId, source.GetReader(), null);

                //Now create the runtime layer and add to map
                _redlineLayer                 = new MgdLayer(ldfId, resSvc);
                _redlineLayer.LegendLabel     = "Redlining";
                _redlineLayer.Name            = "Redline";
                _redlineLayer.Visible         = true;
                _redlineLayer.Selectable      = true;
                _redlineLayer.DisplayInLegend = true;

                MgLayerCollection layers = map.GetLayers();
                layers.Insert(0, _redlineLayer);
            }
        }