public ActionResult LoadSampleData(SetupInputModel input)
        {
            MgUserInformation user = new MgUserInformation(input.Username, input.Password);
            MgSiteConnection  conn = new MgSiteConnection();

            conn.Open(user);

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

            //Load the package file if specified
            if (input.Package != null && input.Package.ContentLength > 0)
            {
                var path = Path.GetTempFileName();
                try
                {
                    input.Package.SaveAs(path);
                    MgByteSource bs = new MgByteSource(path);
                    MgByteReader br = bs.GetReader();

                    resSvc.ApplyResourcePackage(br);
                }
                finally
                {
                    try
                    {
                        if (System.IO.File.Exists(path))
                        {
                            System.IO.File.Delete(path);
                        }
                    }
                    catch { }
                }
            }

            //Load in our sample-specific resources
            MgResourceIdentifier sample1 = new MgResourceIdentifier(AJAX_LAYOUT);
            MgResourceIdentifier sample2 = new MgResourceIdentifier(FLEX_LAYOUT);

            MgByteSource bs1 = new MgByteSource(Server.MapPath("~/App_Data/SheboyganAspMvc.WebLayout.xml"));
            MgByteReader br1 = bs1.GetReader();

            resSvc.SetResource(sample1, br1, null);

            MgByteSource bs2 = new MgByteSource(Server.MapPath("~/App_Data/SheboyganAspMvc.ApplicationDefinition.xml"));
            MgByteReader br2 = bs2.GetReader();

            resSvc.SetResource(sample2, br2, null);

            return(RedirectToAction("Index"));
        }
Exemplo n.º 2
0
        private static void LoadResource(MgResourceService resSvc, string resIdStr, string path)
        {
            MgResourceIdentifier resId = new MgResourceIdentifier(resIdStr);
            MgByteSource         bs    = new MgByteSource(path);
            MgByteReader         br    = bs.GetReader();

            resSvc.SetResource(resId, br, null);
        }
Exemplo n.º 3
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.º 4
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.º 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
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                var fact = new MgdServiceFactory();
                MgResourceService    resSvc = (MgResourceService)fact.CreateService(MgServiceType.ResourceService);
                MgResourceIdentifier resId  = new MgResourceIdentifier(textBox1.Text);
                MgByteSource         source = new MgByteSource(textBox2.Text);
                MgByteReader         reader = source.GetReader();

                resSvc.SetResource(resId, reader, null);
                MessageBox.Show("Success!");
            }
            catch (MgException ex)
            {
                MessageBox.Show(ex.ToString(), "Error from MapGuide");
            }
        }
Exemplo n.º 7
0
        private string ApplyTheme(ThemeParams themeParams)
        {
            var provider = _viewer.GetProvider();
            var map      = _viewer.GetMap();
            var layers   = map.GetLayers();

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

            MgResourceIdentifier resId         = new MgResourceIdentifier(themeParams.layer.GetFeatureSourceId());
            MgResourceIdentifier layerDefResId = themeParams.layer.GetLayerDefinition();
            MgByteReader         byteReader    = resourceService.GetResourceContent(layerDefResId);

            // Load the Layer Definition and Navigate to the specified <VectorScaleRange>

            XmlDocument doc         = new XmlDocument();
            String      xmlLayerDef = byteReader.ToString();

            doc.LoadXml(xmlLayerDef);
            XmlNodeList nodeList = doc.GetElementsByTagName("VectorScaleRange"); //NOXLATE

            XmlElement vectorScaleRangecElement = (XmlElement)nodeList.Item(themeParams.scaleRangeIndex);
            XmlElement areaTypeStyle            = (XmlElement)vectorScaleRangecElement.GetElementsByTagName("AreaTypeStyle").Item(0); //NOXLATE

            // Remove any existing <AreaRule> elements.

            XmlNodeList areaRuleList = areaTypeStyle.GetElementsByTagName("AreaRule"); //NOXLATE
            int         count        = areaRuleList.Count;

            for (int i = 0; i < count; i++)
            {
                //The areaRuleList shrinks as we remove items, so always
                //remove the first item (don't use the index i)
                areaTypeStyle.RemoveChild(areaRuleList.Item(0));
            }

            // Now create the new <AreaRule> elements.

            String areaRuleTemplate = Properties.Resources.AreaRuleTemplate;
            MgFeatureAggregateOptions aggregateOptions = new MgFeatureAggregateOptions();

            String      value       = null;
            String      filterText  = null;
            String      areaRuleXML = null;
            XmlDocument areaDoc     = null;
            XmlNode     areaNode    = null;
            double      portion     = 0.0;
            double      increment   = (themeParams.numRules > 1) ? 1.0 / (themeParams.numRules - 1) : 1.0;

            if (THEME_INDIVIDUAL == themeParams.distro)
            {
                aggregateOptions.AddComputedProperty("THEME_VALUE", "UNIQUE(\"" + themeParams.property.Name + "\")"); //NOXLATE

                MgDataReader dataReader = featureService.SelectAggregate(resId, themeParams.layer.GetFeatureClassName(), aggregateOptions);
                while (dataReader.ReadNext())
                {
                    value = Util.GetFeaturePropertyValue(dataReader, "THEME_VALUE"); //NOXLATE

                    filterText = "&quot;" + themeParams.property.Name + "&quot; = "; //NOXLATE
                    if (themeParams.property.DataType == MgPropertyType.String)
                    {
                        filterText = filterText + "'" + value + "'"; //NOXLATE
                    }
                    else
                    {
                        filterText = filterText + value;
                    }

                    areaRuleXML = String.Format(areaRuleTemplate,
                                                themeParams.property.Name + ":" + value, //NOXLATE
                                                filterText,
                                                Util.InterpolateColor(portion, themeParams.fillFrom, themeParams.fillTo, themeParams.fillTrans),
                                                Util.InterpolateColor(portion, themeParams.borderFrom, themeParams.borderTo, 0));
                    areaDoc = new XmlDocument();
                    areaDoc.LoadXml(areaRuleXML);
                    areaNode = doc.ImportNode(areaDoc.DocumentElement, true);
                    areaTypeStyle.AppendChild(areaNode);

                    portion = portion + increment;
                }
                dataReader.Close();
            }
            else
            {
                var values = new List <string>();

                var expr = themeParams.distro + "(\"" + themeParams.property.Name + "\"," + themeParams.numRules + "," + themeParams.minValue + "," + themeParams.maxValue + ")"; //NOXLATE
                aggregateOptions.AddComputedProperty("THEME_VALUE", expr);                                                                                                        //NOXLATE
                MgDataReader dataReader = featureService.SelectAggregate(resId, themeParams.layer.GetFeatureClassName(), aggregateOptions);
                while (dataReader.ReadNext())
                {
                    value = Util.GetFeaturePropertyValue(dataReader, "THEME_VALUE"); //NOXLATE
                    values.Add(value);
                }
                dataReader.Close();

                for (int i = 0; i < values.Count - 1; i++)
                {
                    filterText = "&quot;" + themeParams.property.Name + "&quot; &gt;= " + values[i] + " AND &quot;" + themeParams.property.Name; //NOXLATE
                    if (i == values.Count - 1)
                    {
                        filterText = filterText + "&quot; &lt;= " + values[i + 1]; //NOXLATE
                    }
                    else
                    {
                        filterText = filterText + "&quot; &lt; " + values[i + 1]; //NOXLATE
                    }
                    areaRuleXML = String.Format(areaRuleTemplate,
                                                themeParams.property.Name + ":" + values[i] + " - " + values[i + 1], //NOXLATE
                                                filterText,
                                                Util.InterpolateColor(portion, themeParams.fillFrom, themeParams.fillTo, themeParams.fillTrans),
                                                Util.InterpolateColor(portion, themeParams.borderFrom, themeParams.borderTo, 0));

                    areaDoc = new XmlDocument();
                    areaDoc.LoadXml(areaRuleXML);
                    areaNode = doc.ImportNode(areaDoc.DocumentElement, true);
                    areaTypeStyle.AppendChild(areaNode);

                    portion = portion + increment;
                }
            }

            // Now save our new layer definition to the session and add it to the map.

            String xmlString   = doc.DocumentElement.OuterXml;
            String uniqueName  = Util.MakeUniqueLayerName(map, themeParams.layer.Name, themeParams.themeName);
            String legendLabel = themeParams.layer.GetLegendLabel();

            if (!string.IsNullOrEmpty(themeParams.themeName))
            {
                legendLabel = legendLabel + " (" + themeParams.themeName + ")";                                                           //NOXLATE
            }
            MgResourceIdentifier layerResId = new MgResourceIdentifier("Session:" + _sessionId + "//" + uniqueName + ".LayerDefinition"); //NOXLATE

            resourceService.SetResource(layerResId, new MgByteReader(xmlString, "text/xml"), null);                                       //NOXLATE

            var newLayer = provider.CreateLayer(layerResId);

            newLayer.SetName(uniqueName);
            newLayer.SetLegendLabel(legendLabel);
            newLayer.SetDisplayInLegend(themeParams.layer.GetDisplayInLegend());
            newLayer.SetVisible(true);
            newLayer.SetSelectable(themeParams.layer.GetSelectable());
            //HACK: This has to be true otherwise owner-drawn nodes will not display its children (the theme rules)
            provider.SetLayerExpandInLegend(newLayer, true);
            layers.Insert(layers.IndexOf(themeParams.layer), newLayer);

            //map.Save(resourceService);

            return(uniqueName);
        }
Exemplo n.º 8
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.º 9
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.º 10
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.º 11
0
        private void btnCreatePointsOfInterest_Click(object sender, EventArgs e)
        {
            string layerName   = "Points";
            string legendLabel = "Points of Interest";
            string groupName   = "Analysis";

            MgMapViewerProvider provider        = _viewer.GetProvider();
            MgResourceService   resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService);
            //We use MgdFeatureService instead of MgFeatureService as this sample demonstrates APIs unique to mg-desktop
            MgdFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService);

            MgMapBase              map    = _viewer.GetMap();
            MgLayerCollection      layers = map.GetLayers();
            MgLayerGroupCollection groups = map.GetLayerGroups();

            //NOTE: mg-desktop has no formal concept of a session repository, but we still
            //support session-based resources as a form of temporary resource (for the duration
            //of the application). Session ids in mg-desktop can be any arbitrary string
            string sessionId = Guid.NewGuid().ToString();

            if (layers.IndexOf(layerName) >= 0)
            {
                MessageBox.Show("Layer (" + layerName + ") already created");
                return;
            }

            //---------------------------------------------------//
            // Create a feature source with point data.
            // (The Sheboygan sample data does not contain such data,
            // so we"ll create it.)

            // Create a feature class definition for the new feature source
            MgClassDefinition classDefinition = new MgClassDefinition();

            classDefinition.SetName("Points");
            classDefinition.SetDescription("Feature class with point data.");
            classDefinition.SetDefaultGeometryPropertyName("GEOM");

            MgPropertyDefinitionCollection idProps  = classDefinition.GetIdentityProperties();
            MgPropertyDefinitionCollection clsProps = classDefinition.GetProperties();

            // Create an identify property
            MgDataPropertyDefinition identityProperty = new MgDataPropertyDefinition("KEY");

            identityProperty.SetDataType(MgPropertyType.Int32);
            identityProperty.SetAutoGeneration(true);
            identityProperty.SetReadOnly(true);
            // Add the identity property to the class definition
            clsProps.Add(identityProperty);
            idProps.Add(identityProperty);

            // Create a name property
            MgDataPropertyDefinition nameProperty = new MgDataPropertyDefinition("NAME");

            nameProperty.SetDataType(MgPropertyType.String);
            // Add the name property to the class definition
            clsProps.Add(nameProperty);

            // Create a geometry property
            MgGeometricPropertyDefinition geometryProperty = new MgGeometricPropertyDefinition("GEOM");

            geometryProperty.SetGeometryTypes(MgFeatureGeometricType.Point);
            // Add the geometry property to the class definition
            clsProps.Add(geometryProperty);

            // Create a feature schema
            MgFeatureSchema             featureSchema = new MgFeatureSchema("PointSchema", "Point schema");
            MgClassDefinitionCollection classes       = featureSchema.GetClasses();

            // Add the feature schema to the class definition
            classes.Add(classDefinition);

            // Create the feature source
            String featureSourceName = "Library://Samples/DevGuide/Data/points.FeatureSource";
            MgResourceIdentifier resourceIdentifier = new MgResourceIdentifier(featureSourceName);
            //wkt = "LOCALCS[\"*XY-MT*\",LOCAL_DATUM[\"*X-Y*\",10000],UNIT[\"Meter\", 1],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH]]";
            String wkt = "GEOGCS[\"LL84\",DATUM[\"WGS84\",SPHEROID[\"WGS84\",6378137.000,298.25722293]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.01745329251994]]";
            MgFileFeatureSourceParams sdfParams = new MgFileFeatureSourceParams("OSGeo.SDF", "LatLong", wkt, featureSchema);

            featureService.CreateFeatureSource(resourceIdentifier, sdfParams);

            // We need to add some data to the sdf before using it.  The spatial context
            // reader must have an extent.
            MgBatchPropertyCollection batchPropertyCollection = new MgBatchPropertyCollection();
            MgWktReaderWriter         wktReaderWriter         = new MgWktReaderWriter();
            MgAgfReaderWriter         agfReaderWriter         = new MgAgfReaderWriter();
            MgGeometryFactory         geometryFactory         = new MgGeometryFactory();

            // Make four points
            batchPropertyCollection.Add(MakePoint("Point A", -87.727, 43.748, wktReaderWriter, agfReaderWriter));

            batchPropertyCollection.Add(MakePoint("Point B", -87.728, 43.730, wktReaderWriter, agfReaderWriter));

            batchPropertyCollection.Add(MakePoint("Point C", -87.726, 43.750, wktReaderWriter, agfReaderWriter));

            batchPropertyCollection.Add(MakePoint("Point D", -87.728, 43.750, wktReaderWriter, agfReaderWriter));

            // Old way commented out

            /*
             * // Add the batch property collection to the feature source
             * MgInsertFeatures cmd = new MgInsertFeatures("Points", batchPropertyCollection);
             * MgFeatureCommandCollection featureCommandCollection = new MgFeatureCommandCollection();
             * featureCommandCollection.Add(cmd);
             *
             * // Execute the "add" commands
             * featureService.UpdateFeatures(resourceIdentifier, featureCommandCollection, false);
             */

            // Here's the mg-desktop way
            MgFeatureReader insertResult = featureService.InsertFeatures(resourceIdentifier, "Points", batchPropertyCollection);

            insertResult.Close();

            // ...
            //---------------------------------------------------//
            // Create a new layer

            LayerDefinitionFactory factory = new LayerDefinitionFactory();

            // Create a mark symbol
            String resourceId = "Library://Samples/Sheboygan/Symbols/BasicSymbols.SymbolLibrary";
            String symbolName = "PushPin";
            String width      = "24"; // unit = points
            String height     = "24"; // unit = points
            String color      = "FFFF0000";
            String markSymbol = factory.CreateMarkSymbol(resourceId, symbolName, width, height, color);

            // Create a text symbol
            String text            = "ID";
            String fontHeight      = "12";
            String foregroundColor = "FF000000";
            String textSymbol      = factory.CreateTextSymbol(text, fontHeight, foregroundColor);

            // Create a point rule.
            String ruleLegendLabel = "trees";
            String filter          = "";
            String pointRule       = factory.CreatePointRule(ruleLegendLabel, filter, textSymbol, markSymbol);

            // Create a point type style.
            String pointTypeStyle = factory.CreatePointTypeStyle(pointRule);

            // Create a scale range.
            String minScale        = "0";
            String maxScale        = "1000000000000";
            String pointScaleRange = factory.CreateScaleRange(minScale, maxScale, pointTypeStyle);

            // Create the layer definiton.
            String featureName     = "PointSchema:Points";
            String geometry        = "GEOM";
            String layerDefinition = factory.CreateLayerDefinition(featureSourceName, featureName, geometry, pointScaleRange);
            //---------------------------------------------------//
            // ...

            XmlDocument domDocument = new XmlDocument();

            domDocument.LoadXml(layerDefinition);

            //Add the layer to the map
            // TODO: Should probably validate this XML content
            using (MemoryStream ms = new MemoryStream())
            {
                domDocument.Save(ms);
                ms.Position = 0L;
                //Note we do this to ensure our XML content is free of any BOM characters
                byte[]   ldfBytes    = ms.ToArray();
                Encoding utf8        = Encoding.UTF8;
                String   layerDefStr = new String(utf8.GetChars(ldfBytes));
                ldfBytes = new byte[layerDefStr.Length - 1];
                int byteCount = utf8.GetBytes(layerDefStr, 1, layerDefStr.Length - 1, ldfBytes, 0);
                // Save the new layer definition to the session repository
                MgByteSource         byteSource = new MgByteSource(ldfBytes, ldfBytes.Length);
                MgResourceIdentifier resourceID = new MgResourceIdentifier("Session:" + sessionId + "//" + layerName + ".LayerDefinition");
                resourceService.SetResource(resourceID, byteSource.GetReader(), null);

                //Insert this layer to our map
                MgdLayer newLayer = new MgdLayer(resourceID, resourceService);
                newLayer.Name            = layerName;
                newLayer.LegendLabel     = legendLabel;
                newLayer.DisplayInLegend = true;
                newLayer.SetVisible(true);
                layers.Insert(0, newLayer);

                //Create analysis group if not already created
                if (groups.IndexOf(groupName) < 0)
                {
                    MgLayerGroup group = new MgLayerGroup(groupName);
                    group.LegendLabel     = groupName;
                    group.DisplayInLegend = true;
                    groups.Add(group);
                    newLayer.Group = group;
                }

                MessageBox.Show("Layer (" + layerName + ") created");
                _viewer.RefreshMap();
                IMapLegend legend = Shell.Instance.Legend;
                if (legend != null)
                {
                    legend.RefreshLegend();
                }
            }
        }
Exemplo n.º 12
0
        private void btnShowBuildings_Click(object sender, EventArgs e)
        {
            MgMapViewerProvider provider        = _viewer.GetProvider();
            MgResourceService   resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService);

            string layerName   = "RecentlyBuilt";
            string legendLabel = "Built after 1980";
            string groupName   = "Analysis";

            MgMapBase              map    = _viewer.GetMap();
            MgLayerCollection      layers = map.GetLayers();
            MgLayerGroupCollection groups = map.GetLayerGroups();

            if (layers.IndexOf(layerName) >= 0)
            {
                MessageBox.Show("Layer (" + layerName + ") already created");
                return;
            }

            //NOTE: mg-desktop has no formal concept of a session repository, but we still
            //support session-based resources as a form of temporary resource (for the duration
            //of the application). Session ids in mg-desktop can be any arbitrary string
            string sessionId = Guid.NewGuid().ToString();

            XmlDocument domDocument = new XmlDocument();

            domDocument.LoadXml(Layers.RecentlyBuilt);

            // Get a list of all the <AreaRule><Filter> elements in
            // the XML.
            XmlNodeList nodes = domDocument.SelectNodes("//AreaRule/Filter");

            // Find the correct node and change it
            foreach (XmlNode node in nodes)
            {
                if (node.InnerText == "YRBUILT > 1950")
                {
                    node.InnerText = "YRBUILT > 1980";
                }
            }

            // Get a list of all the <LegendLabel> elements in the
            // XML.
            nodes = domDocument.SelectNodes("//LegendLabel");
            // Find the correct node and change it
            foreach (XmlNode node in nodes)
            {
                if (node.InnerText == "Built after 1950")
                {
                    node.InnerText = "Built after 1980";
                }
            }

            //Add the layer to the map
            // TODO: Should probably validate this XML content
            using (MemoryStream ms = new MemoryStream())
            {
                domDocument.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);
                // Save the new layer definition to the session repository
                MgByteSource         byteSource = new MgByteSource(layerDefinition, layerDefinition.Length);
                MgResourceIdentifier resourceID = new MgResourceIdentifier("Session:" + sessionId + "//" + layerName + ".LayerDefinition");
                resourceService.SetResource(resourceID, byteSource.GetReader(), null);

                //Insert this layer to our map
                MgdLayer newLayer = new MgdLayer(resourceID, resourceService);
                newLayer.Name            = layerName;
                newLayer.LegendLabel     = legendLabel;
                newLayer.DisplayInLegend = true;
                newLayer.SetVisible(true);
                layers.Insert(0, newLayer);

                //Create analysis group if not already created
                if (groups.IndexOf(groupName) < 0)
                {
                    MgLayerGroup group = new MgLayerGroup(groupName);
                    group.LegendLabel     = groupName;
                    group.DisplayInLegend = true;
                    groups.Add(group);
                    newLayer.Group = group;
                }

                //Turn off square footage if it exists
                if (layers.IndexOf("SquareFootage") >= 0)
                {
                    MgLayerBase layer = layers.GetItem("SquareFootage");
                    layer.SetVisible(false);
                }

                MessageBox.Show("Layer (" + layerName + ") created");
                _viewer.RefreshMap();
                IMapLegend legend = Shell.Instance.Legend;
                if (legend != null)
                {
                    legend.RefreshLegend();
                }
            }
        }
Exemplo n.º 13
0
        private void btnCreateHydroLine_Click(object sender, EventArgs e)
        {
            string layerName   = "Hydro";
            string legendLabel = "Hydro";
            string groupName   = "Analysis";

            MgMapViewerProvider provider        = _viewer.GetProvider();
            MgResourceService   resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService);

            MgMapBase              map    = _viewer.GetMap();
            MgLayerCollection      layers = map.GetLayers();
            MgLayerGroupCollection groups = map.GetLayerGroups();

            //NOTE: mg-desktop has no formal concept of a session repository, but we still
            //support session-based resources as a form of temporary resource (for the duration
            //of the application). Session ids in mg-desktop can be any arbitrary string
            string sessionId = Guid.NewGuid().ToString();

            if (layers.IndexOf(layerName) >= 0)
            {
                MessageBox.Show("Layer (" + layerName + ") already created");
                return;
            }

            //---------------------------------------------------//
            // Create a new layer

            LayerDefinitionFactory factory = new LayerDefinitionFactory();

            // Create a line rule.
            String ruleLegendLabel = "";
            String filter          = "";
            String color           = "FF0000FF";
            String lineRule        = factory.CreateLineRule(ruleLegendLabel, filter, color);

            // Create a line type style.
            String lineTypeStyle = factory.CreateLineTypeStyle(lineRule);

            // Create a scale range.
            String minScale       = "0";
            String maxScale       = "1000000000000";
            String lineScaleRange = factory.CreateScaleRange(minScale, maxScale, lineTypeStyle);

            // Create the layer definiton.
            String featureClass    = "Library://Samples/Sheboygan/Data/HydrographicLines.FeatureSource";
            String featureName     = "SHP_Schema:HydrographicLines";
            String geometry        = "SHPGEOM";
            String layerDefinition = factory.CreateLayerDefinition(featureClass, featureName, geometry, lineScaleRange);

            //---------------------------------------------------//
            // ...

            XmlDocument domDocument = new XmlDocument();

            domDocument.LoadXml(layerDefinition);

            //Add the layer to the map
            // TODO: Should probably validate this XML content
            using (MemoryStream ms = new MemoryStream())
            {
                domDocument.Save(ms);
                ms.Position = 0L;
                //Note we do this to ensure our XML content is free of any BOM characters
                byte[]   ldfBytes    = ms.ToArray();
                Encoding utf8        = Encoding.UTF8;
                String   layerDefStr = new String(utf8.GetChars(ldfBytes));
                ldfBytes = new byte[layerDefStr.Length - 1];
                int byteCount = utf8.GetBytes(layerDefStr, 1, layerDefStr.Length - 1, ldfBytes, 0);
                // Save the new layer definition to the session repository
                MgByteSource         byteSource = new MgByteSource(ldfBytes, ldfBytes.Length);
                MgResourceIdentifier resourceID = new MgResourceIdentifier("Session:" + sessionId + "//" + layerName + ".LayerDefinition");
                resourceService.SetResource(resourceID, byteSource.GetReader(), null);

                //Insert this layer to our map
                MgdLayer newLayer = new MgdLayer(resourceID, resourceService);
                newLayer.Name            = layerName;
                newLayer.LegendLabel     = legendLabel;
                newLayer.DisplayInLegend = true;
                newLayer.SetVisible(true);
                layers.Insert(0, newLayer);

                //Create analysis group if not already created
                if (groups.IndexOf(groupName) < 0)
                {
                    MgLayerGroup group = new MgLayerGroup(groupName);
                    group.LegendLabel     = groupName;
                    group.DisplayInLegend = true;
                    groups.Add(group);
                    newLayer.Group = group;
                }

                MessageBox.Show("Layer (" + layerName + ") created");
                _viewer.RefreshMap();
                IMapLegend legend = Shell.Instance.Legend;
                if (legend != null)
                {
                    legend.RefreshLegend();
                }
            }
        }
Exemplo n.º 14
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.º 15
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.º 16
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.º 17
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);
            }
        }