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

                Assert.Throws <MgNullArgumentException>(() => service.SetResourceData(null, "", "", null));

                var dataSource = new MgByteSource(dataFileName);
                var dataReader = dataSource.GetReader();

                Assert.Throws <MgNullArgumentException>(() => service.SetResourceData(resourceIdentifier, "", "File", dataReader));

                dataSource = new MgByteSource(dataFileName);
                dataReader = dataSource.GetReader();
                service.SetResourceData(resourceIdentifier, resourceDataName, "File", dataReader);

                var    reader = service.EnumerateResourceData(resourceIdentifier);
                string xml    = reader.ToString();

                Assert.True(xml.Contains("<Name>" + resourceDataName + "</Name>"));
            }
            catch (MgException ex)
            {
                Assert.Fail(ex.Message);
                ex.Dispose();
            }
        }
Esempio n. 2
0
        public override TestResult Execute(int paramSetId)
        {
            try
            {
                var param = new NameValueCollection();
                _unitTestVm.ReadParameterValue(paramSetId, "RESOURCEID", param);
                _unitTestVm.ReadParameterValue(paramSetId, "DATANAME", param);
                _unitTestVm.ReadParameterValue(paramSetId, "DATATYPE", param);
                _unitTestVm.ReadParameterValue(paramSetId, "DATA", param, true);

                MgResourceIdentifier resId = null;
                if (param["RESOURCEID"] != null)
                {
                    resId = new MgResourceIdentifier(param["RESOURCEID"]);
                }

                string       extension  = CommonUtility.GetExtension(param["DATANAME"]);
                string       mimeType   = CommonUtility.GetMimeType(extension);
                MgByteSource dataSource = new MgByteSource(param["DATA"]);
                dataSource.SetMimeType(mimeType);
                MgByteReader dataReader = dataSource.GetReader();

                _resourceService.SetResourceData(resId, param["DATANAME"], param["DATATYPE"], dataReader);

                return(TestResult.FromByteReader(null));
            }
            catch (MgException ex)
            {
                return(TestResult.FromMgException(ex));
            }
            catch (Exception ex)
            {
                return(TestResult.FromException(ex));
            }
        }
Esempio n. 3
0
 public static void SetResourceFromXml(HtzMgHelper helper, MgResourceIdentifier resourceId, XmlDocument doc)
 {
     byte[] layerDef = new UTF8Encoding().GetBytes(doc.InnerXml);
     MgByteSource byteSource = new MgByteSource(layerDef, layerDef.Length);
     byteSource.SetMimeType("text/xml");
     helper.ResourceService.SetResource(resourceId, byteSource.GetReader(), null);
 }
Esempio n. 4
0
        // public void TestCase_EnumerateResources() {}

        public void TestCase_SetResource()
        {
            try
            {
                var fact    = new MgdServiceFactory();
                var service = (MgResourceService)fact.CreateService(MgServiceType.ResourceService);

                //Try to use NULL arguments
                Assert.Throws <MgNullArgumentException>(() => service.SetResource(null, null, null));
                Assert.Throws <MgNullArgumentException>(() => service.SetResource(resourceIdentifier, null, null));

                //Add a new resource
                MgByteSource source = new MgByteSource(resourceContentFileName);
                MgByteReader reader = source.GetReader();
                service.SetResource(resourceIdentifier, reader, null);

                //Try to add the same resource again (should be fine and just update it)
                source = new MgByteSource(resourceContentFileName);
                reader = source.GetReader();
                service.SetResource(resourceIdentifier, reader, null);

                //Add another resource layer definition, which references to the feature source. This is for cascade MoveResource test.
                source = new MgByteSource(resourceContentFileName2);
                reader = source.GetReader();
                service.SetResource(resourceIdentifier4, reader, null);
            }
            catch (MgException ex)
            {
                Assert.Fail(ex.Message);
                ex.Dispose();
            }
        }
Esempio n. 5
0
        public void Execute(IPlatformFactory factory, ITestLogger logger)
        {
            string tmp = Path.GetTempFileName();

            try
            {
                File.WriteAllText(tmp, "Hello World");

                MgByteSource bs     = new MgByteSource(tmp);
                MgByteReader reader = bs.GetReader();

                MgGeometryProperty gp      = new MgGeometryProperty("GeomPropName", reader);
                MgByteSource       bs2     = new MgByteSource("../../TestData/DrawingService/SpaceShip.dwf");
                MgByteReader       reader2 = bs2.GetReader();

                gp.Value = reader2;
                Assert.AreEqual(reader2.GetLength(), gp.Value.GetLength());

                Assert.AreEqual(MgPropertyType.Geometry, gp.PropertyType);
            }
            finally
            {
                try
                {
                    File.Delete(tmp);
                }
                catch { }
            }
        }
Esempio n. 6
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);
        }
Esempio n. 7
0
        private static void LoadResourceData(MgResourceService resSvc, string resIdStr, string dataName, string dataType, string path)
        {
            MgResourceIdentifier resId = new MgResourceIdentifier(resIdStr);
            MgByteSource         bs    = new MgByteSource(path);
            MgByteReader         br    = bs.GetReader();

            resSvc.SetResourceData(resId, dataName, dataType, br);
        }
Esempio n. 8
0
        public void ByteReader()
        {
            MgByteSource source = new MgByteSource("d:/MgDev/UnitTest/TestData/DrawingService/SpaceShip.dwf");
            source.MimeType = MgMimeType.Dwf;
            MgByteReader reader = source.GetReader();

            Assert.AreEqual(MgMimeType.Dwf, reader.MimeType);
        }
Esempio n. 9
0
        public void Execute(IPlatformFactory factory, ITestLogger logger)
        {
            MgByteSource source = new MgByteSource("../../TestData/DrawingService/SpaceShip.dwf");

            source.MimeType = MgMimeType.Dwf;
            MgByteReader reader = source.GetReader();

            Assert.AreEqual(MgMimeType.Dwf, reader.MimeType);
        }
        public void SetResourceContent(string resourceId, string resourceContent)
        {
            MgResourceIdentifier resId = new MgResourceIdentifier(resourceId);

            byte[]       bytes = Encoding.UTF8.GetBytes(resourceContent);
            MgByteSource src   = new MgByteSource(bytes, bytes.Length);

            src.SetMimeType(MgMimeType.Xml);
            ResourceService.SetResource(resId, src.GetReader(), null);
        }
Esempio n. 11
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);
        }
        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"));
        }
Esempio n. 13
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;
        }
Esempio n. 14
0
        public void BlobProperty()
        {
            MgByteSource bs = new MgByteSource("d:/mgdev/web/src/webconfig.ini");
            MgByteReader reader = bs.GetReader();
            MgBlobProperty bp = new MgBlobProperty("BlobPropName", reader);

            Assert.AreEqual("BlobPropName", bp.Name);
            Assert.Greater((int)bp.Value.GetLength(), 0);
            Assert.AreEqual(reader.GetLength(), bp.Value.GetLength());
            Assert.AreEqual(MgPropertyType.Blob, bp.PropertyType);

            MgByteSource bs2 = new MgByteSource("d:/MgDev/UnitTest/TestData/DrawingService/SpaceShip.dwf");
            MgByteReader reader2 = bs2.GetReader();
            bp.Value = reader2;
            Assert.AreEqual(reader2.GetLength(), bp.Value.GetLength());
        }
        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");
        }
Esempio n. 16
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)
            {
            }
        }
Esempio n. 17
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");
            }
        }
Esempio n. 18
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");
            }
        }
Esempio n. 19
0
 public static MgByteReader GetByteReaderFromPath(string path, bool bCheck = true)
 {
     if (bCheck)
     {
         if (File.Exists(path))
         {
             MgByteSource source = new MgByteSource(path);
             MgByteReader reader = source.GetReader();
             return(reader);
         }
         return(null);
     }
     else
     {
         MgByteSource source = new MgByteSource(path);
         MgByteReader reader = source.GetReader();
         return(reader);
     }
 }
Esempio n. 20
0
        protected override void OnLoad(EventArgs e)
        {
            mgMapViewer1.UseRenderMapIfTiledLayersExist = true;
            mgMapViewer1.RespectFiniteDisplayScales     = true;
            new MapViewerController(mgMapViewer1,          //The MgMapViewer
                                    mgLegend1,             //The MgLegend
                                    this,                  //The IMapStatusBar
                                    mgPropertyPane1,       //The MgPropertyPane
                                    mgDefaultToolbar1);    //The MgDefaultToolbar

            MgdServiceFactory    factory  = new MgdServiceFactory();
            MgdResourceService   resSvc   = (MgdResourceService)factory.CreateService(MgServiceType.ResourceService);
            MgResourceIdentifier mapDefId = new MgResourceIdentifier("Library://Samples/Sheboygan/Maps/Sheboygan.MapDefinition");

            //If this map definition doesn't exist, we ask the user to
            //load the Sheboygan package
            if (!resSvc.ResourceExists(mapDefId))
            {
                using (OpenFileDialog diag = new OpenFileDialog())
                {
                    diag.Filter = "MapGuide Packages (*.mgp)|*.mgp";
                    if (diag.ShowDialog() == DialogResult.OK)
                    {
                        MgByteSource source = new MgByteSource(diag.FileName);
                        MgByteReader reader = source.GetReader();
                        resSvc.ApplyResourcePackage(reader);
                    }
                    else
                    {
                        //No map, nothing to do here
                        Application.Exit();
                    }
                }
            }

            //Create our runtime map
            MgdMap map = new MgdMap(mapDefId);
            //Create our viewer provider
            MgMapViewerProvider provider = new MgDesktopMapViewerProvider(map);

            //Initialize our viewer with this provider
            mgMapViewer1.Init(provider);
        }
Esempio n. 21
0
        public void TestCase_ApplyResourcePackage()
        {
            try
            {
                var fact = new MgdServiceFactory();
                var service = (MgResourceService)fact.CreateService(MgServiceType.ResourceService);
                Assert.Throws<MgNullArgumentException>(() => service.ApplyResourcePackage(null));

                MgByteSource source = new MgByteSource(packageName);
                source.SetMimeType(MgMimeType.Binary);
                MgByteReader reader = source.GetReader();

                service.ApplyResourcePackage(reader);
            }
            catch (MgException ex)
            {
                Assert.Fail(ex.Message);
                ex.Dispose();
            }
        }
Esempio n. 22
0
        public void TestCase_ApplyResourcePackage()
        {
            try
            {
                var fact    = new MgdServiceFactory();
                var service = (MgResourceService)fact.CreateService(MgServiceType.ResourceService);
                Assert.Throws <MgNullArgumentException>(() => service.ApplyResourcePackage(null));

                MgByteSource source = new MgByteSource(packageName);
                source.SetMimeType(MgMimeType.Binary);
                MgByteReader reader = source.GetReader();

                service.ApplyResourcePackage(reader);
            }
            catch (MgException ex)
            {
                Assert.Fail(ex.Message);
                ex.Dispose();
            }
        }
Esempio n. 23
0
        public void TestCase_DeleteResource()
        {
            try
            {
                var fact    = new MgdServiceFactory();
                var service = (MgResourceService)fact.CreateService(MgServiceType.ResourceService);
                var featSvc = (MgdFeatureService)fact.CreateService(MgServiceType.FeatureService);

                Assert.Throws <MgNullArgumentException>(() => service.DeleteResource(null));

                service.DeleteResource(resourceNotExist);

                service.DeleteResource(resourceIdentifier);
                service.DeleteResource(resourceIdentifier2);
                service.DeleteResource(resourceIdentifier3);

                var resource = new MgResourceIdentifier("Library://UnitTests/Data/TEST.FeatureSource");

                var source = new MgByteSource("..\\UnitTestFiles\\TEST.FeatureSource");
                var reader = source.GetReader();
                service.SetResource(resource, reader, null);

                var dataSource = new MgByteSource("..\\UnitTestFiles\\TEST.sdf");
                var dataReader = dataSource.GetReader();
                service.SetResourceData(resource, "TEST.sdf", "File", dataReader);

                MgFeatureAggregateOptions agg = new MgFeatureAggregateOptions();
                agg.AddFeatureProperty("Data");

                var mgdr = featSvc.SelectAggregate(resource, "TEST", agg);
                Assert.True(mgdr.ReadNext());
                mgdr.Close();

                service.DeleteResource(resource);
            }
            catch (MgException ex)
            {
                Assert.Fail(ex.Message);
                ex.Dispose();
            }
        }
Esempio n. 24
0
        protected override void OnLoad(EventArgs e)
        {
            _wktRw = new MgWktReaderWriter();
            _geomFact = new MgGeometryFactory();
            new MapViewerController(mgMapViewer1,          //The MgMapViewer
                                    mgLegend1,             //The MgLegend
                                    this,                  //The IMapStatusBar
                                    mgPropertyPane1);      //The MgPropertyPane

            MgdServiceFactory factory = new MgdServiceFactory();
            MgdResourceService resSvc = (MgdResourceService)factory.CreateService(MgServiceType.ResourceService);
            MgResourceIdentifier mapDefId = new MgResourceIdentifier("Library://Samples/Sheboygan/Maps/Sheboygan.MapDefinition");
            //If this map definition doesn't exist, we ask the user to
            //load the Sheboygan package
            if (!resSvc.ResourceExists(mapDefId))
            {
                using (OpenFileDialog diag = new OpenFileDialog())
                {
                    diag.Filter = "MapGuide Packages (*.mgp)|*.mgp";
                    if (diag.ShowDialog() == DialogResult.OK)
                    {
                        MgByteSource source = new MgByteSource(diag.FileName);
                        MgByteReader reader = source.GetReader();
                        resSvc.ApplyResourcePackage(reader);
                    }
                    else
                    {
                        //No map, nothing to do here
                        Application.Exit();
                    }
                }
            }

            //Create our runtime map
            MgdMap map = new MgdMap(mapDefId);
            //Create our viewer provider
            MgMapViewerProvider provider = new MgDesktopMapViewerProvider(map);
            //Initialize our viewer with this provider
            mgMapViewer1.Init(provider);
            UpdateButtonCheckedState();
        }
Esempio n. 25
0
        public override void Invoke()
        {
            using (var open = new OpenFileDialog())
            {
                open.Title = Strings.TextLoadPackage;
                open.Filter = "*.mgp|*.mgp";
                if (open.ShowDialog() == DialogResult.OK)
                {
                    var viewer = this.Viewer;
                    var provider = viewer.GetProvider();
                    var resSvc = (MgResourceService)provider.CreateService(MgServiceType.ResourceService);
                    var source = new MgByteSource(open.FileName);
                    var br = source.GetReader();

                    resSvc.ApplyResourcePackage(br);
                    MessageBox.Show(Strings.TextPackageLoaded);
                    if (this.InvokeOnPackageLoad != null)
                        this.InvokeOnPackageLoad.Invoke();
                }
            }
        }
Esempio n. 26
0
        internal void UpdateLayerStyle(RedlineLayer layer, RedlineStyle updatedStyle)
        {
            //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 interrogate our schema to figure it out
            MgResourceIdentifier fsId = new MgResourceIdentifier(layer.FeatureSource);

            MgFeatureSchemaCollection   schemas = _featSvc.DescribeSchema(fsId, string.Empty, null);
            MgFeatureSchema             schema  = schemas.GetItem(0);
            MgClassDefinitionCollection classes = schema.GetClasses();
            MgClassDefinition           cls     = classes.GetItem(0);
            string className = schema.Name + ":" + cls.Name;

            MgResourceIdentifier ldfId = new MgResourceIdentifier(layer.LayerDefinition);

            string layerDefContent = CreateRedlineLayerDefinitionContent(fsId, className, updatedStyle, layer.StyleType);

            byte[]       bytes      = Encoding.UTF8.GetBytes(layerDefContent);
            MgByteSource byteSource = new MgByteSource(bytes, bytes.Length);
            MgByteReader byteReader = byteSource.GetReader();

            _resSvc.SetResource(ldfId, byteReader, null);
        }
Esempio n. 27
0
        public void Execute(IPlatformFactory factory, ITestLogger logger)
        {
            string tmp = Path.GetTempFileName();

            try
            {
                File.WriteAllText(tmp, "Hello World");

                MgByteSource source = new MgByteSource(tmp);
                source.MimeType = "text/plain";

                Assert.AreEqual(MgMimeType.Text, source.MimeType);
            }
            finally
            {
                try
                {
                    File.Delete(tmp);
                }
                catch { }
            }
        }
Esempio n. 28
0
        public override void Invoke()
        {
            using (var open = new OpenFileDialog())
            {
                open.Title  = Strings.TextLoadPackage;
                open.Filter = "*.mgp|*.mgp";
                if (open.ShowDialog() == DialogResult.OK)
                {
                    var viewer   = this.Viewer;
                    var provider = viewer.GetProvider();
                    var resSvc   = (MgResourceService)provider.CreateService(MgServiceType.ResourceService);
                    var source   = new MgByteSource(open.FileName);
                    var br       = source.GetReader();

                    resSvc.ApplyResourcePackage(br);
                    MessageBox.Show(Strings.TextPackageLoaded);
                    if (this.InvokeOnPackageLoad != null)
                    {
                        this.InvokeOnPackageLoad.Invoke();
                    }
                }
            }
        }
Esempio n. 29
0
        public void Execute(IPlatformFactory factory, ITestLogger logger)
        {
            var resSvc  = (MgResourceService)factory.CreateService(MgServiceType.ResourceService);
            var featSvc = (MgFeatureService)factory.CreateService(MgServiceType.FeatureService);
            var fsId    = new MgResourceIdentifier("Library://UnitTests/Data/Metadata.FeatureSource");

            try
            {
                if (resSvc.ResourceExists(fsId))
                {
                    resSvc.DeleteResource(fsId);
                }

                string metadata = resSvc.EnumerateResourceDocuments(null, MgResourceType.FeatureSource, MgResourceHeaderProperties.Metadata);
                File.WriteAllText("metadata.txt", metadata);

                string className = FeatureServiceTestUtil.CreateTestDataStore(fsId, "OSGeo.SDF", featSvc);
                string headerXml = string.Format(Properties.Resources.ResourceHeaderTemplate, "Foo", "Bar");
                var    bytes     = Encoding.UTF8.GetBytes(headerXml);
                var    source    = new MgByteSource(bytes, bytes.Length);
                var    rdr       = source.GetReader();

                resSvc.SetResource(fsId, null, rdr);
                string metadata2 = resSvc.EnumerateResourceDocuments(null, MgResourceType.FeatureSource, MgResourceHeaderProperties.Metadata);
                File.WriteAllText("metadata2.txt", metadata2);

                Assert.IsFalse(metadata == metadata2);
            }
            finally
            {
                if (resSvc.ResourceExists(fsId))
                {
                    resSvc.DeleteResource(fsId);
                }
            }
        }
Esempio n. 30
0
        public override void UploadPackage(string filename, OSGeo.MapGuide.MaestroAPI.Utility.StreamCopyProgressDelegate callback)
        {
            System.IO.FileInfo fi = new System.IO.FileInfo(filename);

            if (callback != null)
                callback(0, fi.Length, fi.Length);

            MgResourceService res = this.Connection.CreateService(MgServiceType.ResourceService) as MgResourceService;
            MgByteSource pkgSource = new MgByteSource(filename);
            MgByteReader rd = pkgSource.GetReader();
            res.ApplyResourcePackage(rd);
            rd.Dispose();
            LogMethodCall("MgResourceService::ApplyResourcePackage", true, "MgByteReader");

            if (callback != null)
                callback(fi.Length, 0, fi.Length);
        }
Esempio n. 31
0
        // public void TestCase_EnumerateResources() {} 
        
        public void TestCase_SetResource()
        {
            try
            {
                var fact = new MgdServiceFactory();
                var service = (MgResourceService)fact.CreateService(MgServiceType.ResourceService);

                //Try to use NULL arguments
                Assert.Throws<MgNullArgumentException>(() => service.SetResource(null, null, null));
                Assert.Throws<MgNullArgumentException>(() => service.SetResource(resourceIdentifier, null, null));

                //Add a new resource
                MgByteSource source = new MgByteSource(resourceContentFileName);
                MgByteReader reader = source.GetReader();
                service.SetResource(resourceIdentifier, reader, null);

                //Try to add the same resource again (should be fine and just update it)
                source = new MgByteSource(resourceContentFileName);
                reader = source.GetReader();
                service.SetResource(resourceIdentifier, reader, null);

                //Add another resource layer definition, which references to the feature source. This is for cascade MoveResource test.
                source = new MgByteSource(resourceContentFileName2);
                reader = source.GetReader();
                service.SetResource(resourceIdentifier4, reader, null);
            }
            catch (MgException ex)
            {
                Assert.Fail(ex.Message);
                ex.Dispose();
            }
        }
Esempio n. 32
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();
                }
            }
        }
Esempio n. 33
0
        public string getPlanMapImageAsBase64String(string planID, string imageWidth, string imageHeight)
        {
            try
            {
                MgUserInformation userInfo = null;
                string mapWebTierInit = ConfigurationManager.AppSettings["MGWebTierInit"].ToString();
                MapGuideApi.MgInitializeWebTier(mapWebTierInit);

                // Om kartsession finns för applikationssession använd den annars skapa ny kartssitesession
                string mapSiteSessionID = null;
                if (Session["MapSiteSessionID"] != null)
                {
                    mapSiteSessionID = Session["MapSiteSessionID"].ToString();
                    userInfo = new MgUserInformation(mapSiteSessionID);
                }
                else
                {
                    // Initierar kartsite och kartsession
                    string mapUserName = ConfigurationManager.AppSettings["MGUserName"].ToString();
                    string mapUserPass = ConfigurationManager.AppSettings["MGUserPass"].ToString();

                    userInfo = new MgUserInformation(mapUserName, mapUserPass);
                    MgSite mapSite = new MgSite();
                    mapSite.Open(userInfo);

                    userInfo.Dispose();

                    mapSiteSessionID = mapSite.CreateSession();

                    //mapSite.Close();

                    Session["MapSiteSessionID"] = mapSiteSessionID;

                    userInfo = new MgUserInformation(mapSiteSessionID);
                }

                //bool test = resSvc.ResourceExists(mapResId);

                string mapSurfaceFactor = ConfigurationManager.AppSettings["MGMapSurfaceFactor"].ToString();
                string mapRes = ConfigurationManager.AppSettings["MGMapResource"].ToString();
                string planRes = ConfigurationManager.AppSettings["MGPlanytorResource"].ToString();
                string planClassName = ConfigurationManager.AppSettings["MGPlanytorClassName"].ToString();
                string planFilterColumn = ConfigurationManager.AppSettings["MGPlanytorFilterColumn"].ToString();
                string planGeometryColumn = ConfigurationManager.AppSettings["MGPlanytorGeometryColumn"].ToString();
                string planytorStrokeRgbaColor = ConfigurationManager.AppSettings["MGPlanytorStrokeRgbaColor"].ToString();
                string planytorForegroundRgbaColor = ConfigurationManager.AppSettings["MGPlanytorForegroundRgbaColor"].ToString();

                string mapImageSizeFromServer = ConfigurationManager.AppSettings["MGMapImageSizeFromServer"].ToString();

                // Standardvärde för storlek på kartbild, används om värde ej finns i Settings.config eller skickas in som parametrar i webbmetod
                string mapImageWidthPixel = "400";
                string mapImageHeightPixel = "300";
                // Väljer bredd och höjd på kartbild om värde ska finnas i Settings.config samt indikeras att de ska användas
                // annars förväntas värde skickas med i webbmetod
                if (mapImageSizeFromServer.ToLower() == "true")
                {
                    mapImageWidthPixel = ConfigurationManager.AppSettings["MGMapImageWidth"].ToString();
                    mapImageHeightPixel = ConfigurationManager.AppSettings["MGMapImageHeight"].ToString();
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(imageWidth) && !string.IsNullOrWhiteSpace(imageHeight))
                    {
                        mapImageWidthPixel = imageWidth;
                        mapImageHeightPixel = imageHeight;
                    }
                }

                MgSiteConnection siteConnection = new MgSiteConnection();
                siteConnection.Open(userInfo);

                MgResourceService resSvc = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService);
                MgResourceIdentifier mapResId = new MgResourceIdentifier(mapRes);
                MgFeatureService featSvc = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService);
                MgResourceIdentifier planResId = new MgResourceIdentifier(planRes);

                // Filter för planDoc efter planDoc-ID
                MgFeatureQueryOptions featureQuery = new MgFeatureQueryOptions();
                featureQuery.SetFilter(planFilterColumn + " = " + planID);

                MgFeatureReader featureReader = featSvc.SelectFeatures(planResId, planClassName, featureQuery);
                MgByteReader byteReaderGeometry = null;
                MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter();
                MgGeometryCollection geometryCollection = new MgGeometryCollection();
                int featureCount = 0;
                try
                {
                    while (featureReader.ReadNext())
                    {
                        byteReaderGeometry = featureReader.GetGeometry(planGeometryColumn);
                        MgGeometry districtGeometry = agfReaderWriter.Read(byteReaderGeometry);
                        geometryCollection.Add(districtGeometry);

                        featureCount++;
                    }
                }
                finally
                {
                    featureReader.Close();
                }

                MgGeometryFactory geometryFactory = new MgGeometryFactory();
                MgMultiGeometry multiGeometry = geometryFactory.CreateMultiGeometry(geometryCollection);

                MgMap map = new MgMap(siteConnection);

                MgEnvelope envelope = multiGeometry.Envelope();

                // Anpassar ev. punkt till komma i tal som hanteras som textsträng för kommande konvertering
                if (mapImageHeightPixel.IndexOf(".") != -1)
                {
                    mapImageHeightPixel = mapImageHeightPixel.Replace(".", ",");
                }
                if (mapImageWidthPixel.IndexOf(".") != -1)
                {
                    mapImageWidthPixel = mapImageWidthPixel.Replace(".", ",");
                }

                // Önskad bilds höjd och bredd i punkter
                double imageHeightPixel = Convert.ToDouble(mapImageHeightPixel);
                double imageWidthPixel = Convert.ToDouble(mapImageWidthPixel);

                map.DisplayDpi = 120;

                double heightEnvelopeN = envelope.Height;
                double widthEnvelopeE = envelope.Width;

                // Anpassar utbredningen på sökta planer (envelope) till bildens format för att bevara skalriktighet
                string mapFarthest = string.Empty;
                if (heightEnvelopeN > widthEnvelopeE)
                    mapFarthest = "height";
                else
                    mapFarthest = "width";

                string imageFarthest = string.Empty;
                if (imageHeightPixel > imageWidthPixel)
                    imageFarthest = "height";
                else
                    imageFarthest = "width";

                double scale = 1.0;
                const double inch = 2.54;

                // Ändring av kartans utbredning och addering av utrymme i kartans bild runt planavgränsningen
                // Map = avgränsning enligt planytan (utbredning i kartan), Image = önskad bild att skapa med kartan
                // Om: kartans höjd är längst & bildens bredd är längst
                if (mapFarthest == "height" && imageFarthest == "width")
                {
                    scale = imageWidthPixel / imageHeightPixel * inch;

                    widthEnvelopeE = imageWidthPixel / imageHeightPixel * heightEnvelopeN * scale;
                }
                // Om: kartans bredd är längst & bildens höjd är längst
                else if (mapFarthest == "width" && imageFarthest == "height")
                {
                    scale = imageHeightPixel / imageWidthPixel * inch;

                    heightEnvelopeN = imageHeightPixel / imageWidthPixel * widthEnvelopeE * scale;
                }
                // Om: kartans höjd är längst & bildens höjd är längst
                else if (mapFarthest == "height" && imageFarthest == "height")
                {
                    double compareSide = (heightEnvelopeN / (imageHeightPixel / imageWidthPixel));
                    bool isCompareSideFarthest = false;
                    if (compareSide > widthEnvelopeE)
                    {
                        isCompareSideFarthest = true;
                    }
                    else
                    {
                        isCompareSideFarthest = false;
                    }

                    scale = imageHeightPixel / imageWidthPixel * inch;

                    if (isCompareSideFarthest)
                    {
                        widthEnvelopeE = heightEnvelopeN / (imageHeightPixel / imageWidthPixel) * scale;
                    }
                    else
                    {
                        heightEnvelopeN = (imageHeightPixel / imageWidthPixel) * widthEnvelopeE * scale;
                    }
                }
                // Om(annars): kartans bredd är längst & bildens bredd är längst
                else
                {
                    double compareSide = (widthEnvelopeE / (imageWidthPixel / imageHeightPixel));
                    bool isCompareSideFarthest = false;
                    if (compareSide > heightEnvelopeN)
                    {
                        isCompareSideFarthest = true;
                    }
                    else
                    {
                        isCompareSideFarthest = false;
                    }

                    scale = imageWidthPixel / imageHeightPixel * inch;

                    if (isCompareSideFarthest)
                    {
                        heightEnvelopeN = widthEnvelopeE / (imageWidthPixel / imageHeightPixel) * scale;
                    }
                    else
                    {
                        widthEnvelopeE = heightEnvelopeN * (imageWidthPixel / imageHeightPixel) * scale;
                    }
                }

                double mapSurfaceFactorDbl = Convert.ToDouble(mapSurfaceFactor.Replace('.', ','));
                double newHeightN = heightEnvelopeN * mapSurfaceFactorDbl;
                double newWidthE = widthEnvelopeE * mapSurfaceFactorDbl;
                MgCoordinate lowerLeft = envelope.LowerLeftCoordinate;
                MgCoordinate upperRight = envelope.UpperRightCoordinate;
                envelope = new MgEnvelope(lowerLeft.X - (newWidthE - widthEnvelopeE) / 2,
                                          lowerLeft.Y - (newHeightN - heightEnvelopeN) / 2,
                                          upperRight.X + (newWidthE - widthEnvelopeE) / 2,
                                          upperRight.Y + (newHeightN - heightEnvelopeN) / 2);

                map.Create(resSvc, mapResId, mapResId.Name);

                // Skapa lagerdefinition i XML
                DefineAreaLayer areaLayer = new DefineAreaLayer();
                areaLayer.FeatureName = planClassName;
                areaLayer.FeatureSourceName = planRes;
                areaLayer.GeometryColumnName = planGeometryColumn;
                areaLayer.Filter = planFilterColumn + " = " + planID;

                LayerScaleRangeCollection lsrCollection = new LayerScaleRangeCollection();

                LayerScaleRange lsr = new LayerScaleRange();
                // MinScale applikations-default till 0 (inklusive) om utelämnat, MaxScale applikations-default till kartans maxskala (exklusive) om utelämnat
                //lsr.MinScale = "0";
                //lsr.MaxScale = "100000000";
                AreaTypeStyle ats = new AreaTypeStyle();

                AreaRuleCollection arCollection = new AreaRuleCollection();

                AreaRule ar = new AreaRule();
                //ar.Filter = planFilterColumn + " = " + planID;
                ar.LegendLabel = "Plan" + planID;
                AreaSymbolization2D symb2D = new AreaSymbolization2D();
                Fill fill = new Fill();
                fill.BackgroundColor = "FFFF0000";
                fill.FillPattern = "Solid";
                fill.ForegroundColor = convertRgbsToHexColor(planytorForegroundRgbaColor);
                Stroke stroke = new Stroke();
                stroke.Color = convertRgbsToHexColor(planytorStrokeRgbaColor);
                stroke.LineStyle = "Solid";
                stroke.Thickness = "1";
                stroke.Unit = "Points";
                symb2D.Fill = fill;
                symb2D.Stroke = stroke;
                ar.Symbolization2D = symb2D;
                arCollection.Add(ar);

                ats.AreaRules = arCollection;

                lsr.AreaTypeStyle = ats;

                lsrCollection.Add(lsr);

                areaLayer.LayerScaleRanges = lsrCollection;

                XmlDocument xmlFile = new XmlDocument();
                //XDocument xmlFile = new XDocument();
                // om returnerande av xml-dokument
                //xmlFile = areaLayer.CreateLayerDefinitionAsXmlDocument();
                // om returnerande av xml-sträng
                xmlFile.LoadXml(areaLayer.CreateLayerDefinitionAsXmlString());
                //xmlFile = areaLayer.CreateLayerDefinitionAsXDocument();
                //xmlFile.Save(Server.MapPath(this.Context.Request.ApplicationPath) + "XmlTestLayerDefinition.xml");

                using (MemoryStream msNewPlanLayer = new MemoryStream())
                {
                    xmlFile.Save(msNewPlanLayer);
                    msNewPlanLayer.Position = 0L;
                    //Note we do this to ensure our XML content is free of any BOM characters
                    byte[] layerDefinition = msNewPlanLayer.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 layerResourceID = new MgResourceIdentifier("Session:" + mapSiteSessionID + "//" + "planytor" + ".LayerDefinition"); //"SearchedPlan" + planID + ".LayerDefinition");
                    resSvc.SetResource(layerResourceID, byteSource.GetReader(), null);

                    MgLayer newPlanLayer = new MgLayer(layerResourceID, resSvc);
                    newPlanLayer.SetName("Sökta planer");
                    newPlanLayer.SetVisible(true);
                    newPlanLayer.SetLegendLabel("Sökta planer");
                    newPlanLayer.SetDisplayInLegend(true);
                    MgLayerCollection layerCollection = map.GetLayers();
                    if (!layerCollection.Contains(newPlanLayer))
                    {
                        // Insert the new layer at position 0 so it is at the top
                        // of the drawing order
                        layerCollection.Insert(0, newPlanLayer);
                    }
                    else
                    {
                        layerCollection.Remove(newPlanLayer);
                        layerCollection.Insert(0, newPlanLayer);
                    }

                    map.Save();
                }

                double mapScale = map.ViewScale;

                // XML-dokument till ren text
                //StringWriter stringWriter = new StringWriter();
                //XmlWriter xmlTextWriter = XmlWriter.Create(stringWriter);
                //xmlFile.WriteTo(xmlTextWriter);
                //xmlTextWriter.Flush();
                string xmlSelection = string.Empty;
                //string xmlSelection = stringWriter.GetStringBuilder().ToString();

                MgSelection selection = null;
                if (!string.IsNullOrEmpty(xmlSelection))
                {
                    selection = new MgSelection(map, xmlSelection);
                }
                else
                {
                    selection = new MgSelection(map);
                }

                MgColor color = new MgColor("255,255,255");

                // Skapar bild av kartan
                MgRenderingService renderingService = (MgRenderingService)siteConnection.CreateService(MgServiceType.RenderingService);
                //MgByteReader byteReader = renderingService.RenderMap(map, selection, "PNG");
                MgByteReader byteReader = renderingService.RenderMap(map, selection, envelope, Convert.ToInt32(imageWidthPixel), Convert.ToInt32(imageHeightPixel), color, "PNG");
                MemoryStream ms = new MemoryStream();
                byte[] byteBuffer = new byte[1024];
                int numBytes = byteReader.Read(byteBuffer, 1024);
                while (numBytes > 0)
                {
                    ms.Write(byteBuffer, 0, numBytes);
                    numBytes = byteReader.Read(byteBuffer, 1024);
                }
                byte[] mapImageByte = ms.ToArray();
                string imageBase64String = Convert.ToBase64String(mapImageByte);

                map.Dispose();
                siteConnection.Dispose();

                DataTable dtResult = new DataTable();
                DataColumn dc = new DataColumn("MAPIMAGEBASE64");
                dtResult.Columns.Add(dc);
                dc = new DataColumn("WIDTH");
                dtResult.Columns.Add(dc);
                dc = new DataColumn("HEIGHT");
                dtResult.Columns.Add(dc);
                DataRow dr = dtResult.NewRow();
                dr["MAPIMAGEBASE64"] = imageBase64String;
                dr["WIDTH"] = imageWidthPixel;
                dr["HEIGHT"] = imageHeightPixel;
                dtResult.Rows.Add(dr);

                //TODO: MAP: Vad kan returneras, base64 eller länk där bild temporärt genereras på server
                //JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
                //return jsonSerializer.Serialize(imageBase64String);

                return getDatatableAsJson(dtResult);
            }
            catch (System.Exception ex)
            {
                UtilityException.LogException(ex, "Webbmetod : getPlanMapImageAsBase64String", true);
                return null;
            }
        }
Esempio n. 34
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;
            }
        }
Esempio n. 35
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();
                }
            }
        }
Esempio n. 36
0
        public void ByteSource()
        {
            MgByteSource source = new MgByteSource("d:/mgdev/web/src/webconfig.ini");
            source.MimeType = "text/plain";

            Assert.AreEqual(MgMimeType.Text, source.MimeType);
        }
Esempio n. 37
0
    //----------------------------------------------------------------------------------------
    // �� �ܣ� ������ʱ��
    //
    // �� �ߣ�
    //
    //
    // �� �ڣ�2007.05.#
    //
    //-----------------------------------------------------------------------------------------
    public bool CreatePointsLayer(String rootPath, String sessionId)
    {
        // ��ȡҪ�ط������Դ����
        MgResourceService resourceService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService);
        MgFeatureService featureService = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService);

        //  �򿪵�ͼ
        MgMap map = new MgMap();
        map.Open(resourceService, "Sheboygan");
        // ---Ҫ�����Ҫ�ز������û��������������滹Ҫ���ܣ�--��ʼ
        // ���������ݵ�Ҫ��Դ
        CreateFeatureSource(sessionId);
        String featureSourceName = "Session:" + sessionId + "//Points.FeatureSource";
        MgResourceIdentifier resourceIdentifier = new MgResourceIdentifier(featureSourceName);

        MgBatchPropertyCollection batchPropertyCollection = new MgBatchPropertyCollection();
        MgWktReaderWriter wktReaderWriter = new MgWktReaderWriter();
        MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter();
        MgGeometryFactory geometryFactory = new MgGeometryFactory();

        // �������¼
        MgPropertyCollection propertyCollection = MakePoint("Point A", -87.727, 43.748);
        batchPropertyCollection.Add(propertyCollection);

        propertyCollection = MakePoint("Point B", -87.728, 43.730);
        batchPropertyCollection.Add(propertyCollection);

        propertyCollection = MakePoint("Point C", -87.726, 43.750);
        batchPropertyCollection.Add(propertyCollection);

        propertyCollection = MakePoint("Point D", -87.728, 43.750);
        batchPropertyCollection.Add(propertyCollection);

        // ��������Ҫ��������ӵ�Ҫ��Դ
        MgInsertFeatures Insertcmd = new MgInsertFeatures("Points", batchPropertyCollection);
        MgFeatureCommandCollection featureCommandCollection = new MgFeatureCommandCollection();
        featureCommandCollection.Add(Insertcmd);
        featureService.UpdateFeatures(resourceIdentifier, featureCommandCollection, false);
        MgResourceIdentifier resourceID = null;
        //--------------Ҫ�����Ҫ�ز��� ����

        // �����㣬ͨ���㹤��LayerDefinitionFactory
        LayerDefinitionFactory factory = new LayerDefinitionFactory();
        factory.RootDirectoryPath = rootPath;

        //-------------------��������ʽ------------------------//
        // ������Ƿ���l
        string resourceSymbel = "Library://MgTutorial/Symbols/BasicSymbols.SymbolLibrary";
        string symbolName = "PushPin";
        string width = "24";  // unit = points
        string height = "24"; // unit = points
        string color = "FFFF0000";
        string markSymbol = factory.CreateMarkSymbol(resourceSymbel, symbolName, width, height, color);

        // �����ı�
        string text = "ID";
        string fontHeight = "12";
        string foregroundColor = "FF000000";
        string textSymbol = factory.CreateTextSymbol(text, fontHeight, foregroundColor);

        // ���������
        string legendLabel = "trees";
        string filter = "";
        string pointRule = factory.CreatePointRule(legendLabel, filter, textSymbol, markSymbol);

        // ��������ʽ
        string pointTypeStyle = factory.CreatePointTypeStyle(pointRule);

        // �������ŷ�Χ
        string minScale = "0";
        string maxScale = "1000000000000";
        string pointScaleRange = factory.CreateScaleRange(minScale, maxScale, pointTypeStyle);

        // �����㶨��
        string featureName = "PointSchema:Points";
        string geometry = "GEOM";
        string layerDefinition = factory.CreateLayerDefinition(featureSourceName, featureName, geometry, pointScaleRange);

        MgByteSource byteSource = new MgByteSource(Encoding.UTF8.GetBytes(layerDefinition), layerDefinition.Length);
        MgByteReader byteReader = byteSource.GetReader();

        resourceID = new MgResourceIdentifier("Session:" + sessionId + "//Points.LayerDefinition");
        resourceService.SetResource(resourceID, byteReader, null);
        //��������IJ㶨�����ݣ������ã�
        MgByteSink byteSink = new MgByteSink(resourceService.GetResourceContent(resourceID));
        string filePath = "C:\\Temp\\LayerDefinition.xml";
        byteSink.ToFile(filePath);

        // �����㲢��ӵ�����͵�ͼ��
        MgLayer newLayer = CreateLayerResource(resourceID, resourceService, "Points", "��ʱ��", map);

        AddLayerToGroup(newLayer, "Analysis", "����", map);

        MgLayerCollection layerCollection = map.GetLayers();
        if (layerCollection.Contains("Points"))
        {
            MgLayer pointsLayer = layerCollection.GetItem("Points");
            pointsLayer.SetVisible(true);
        }
        // �����ͼ
        map.Save(resourceService);

        return true;
    }
Esempio n. 38
0
        public override void SetResourceXmlData(string resourceid, System.IO.Stream content, System.IO.Stream header)
        {
            bool exists = ResourceExists(resourceid);

            var res = GetResourceService();
            byte[] bufHeader = header == null ? new byte[0] : Utility.StreamAsArray(header);
            byte[] bufContent = content == null ? new byte[0] : Utility.StreamAsArray(content);
            //MgByteReader rH = bufHeader.Length == 0 ? null : new MgByteReader(bufHeader, bufHeader.Length, "text/xml");
            //MgByteReader rC = bufContent.Length == 0 ? null : new MgByteReader(bufContent, bufContent.Length, "text/xml");
            MgByteReader rH = null;
            MgByteReader rC = null;

            if (bufHeader.Length > 0)
            {
                MgByteSource source = new MgByteSource(bufHeader, bufHeader.Length);
                source.SetMimeType("text/xml");
                rH = source.GetReader();
            }

            if (bufContent.Length > 0)
            {
                MgByteSource source = new MgByteSource(bufContent, bufContent.Length);
                source.SetMimeType("text/xml");
                rC = source.GetReader();
            }

            res.SetResource(new MgResourceIdentifier(resourceid), rC, rH);
            LogMethodCall("MgResourceService::SetResource", true, resourceid, "MgByteReader", "MgByteReader");
            if (exists)
                OnResourceUpdated(resourceid);
            else
                OnResourceAdded(resourceid);
        }
Esempio n. 39
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);
        }
Esempio n. 40
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);
        }
 public void SetResourceContent(string resourceId, string resourceContent)
 {
     MgResourceIdentifier resId = new MgResourceIdentifier(resourceId);
     byte[] bytes = Encoding.UTF8.GetBytes(resourceContent);
     MgByteSource src = new MgByteSource(bytes, bytes.Length);
     src.SetMimeType(MgMimeType.Xml);
     ResourceService.SetResource(resId, src.GetReader(), null);
 }
Esempio n. 42
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]]";
            MgCreateSdfParams sdfParams = new MgCreateSdfParams("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
            MgPropertyCollection insertResult = featureService.InsertFeatures(resourceIdentifier, "Points", batchPropertyCollection);
            for (int i = 0; i < insertResult.GetCount(); i++)
            {
                MgFeatureProperty fp = insertResult.GetItem(i) as MgFeatureProperty;
                if (fp != null)
                {
                    MgFeatureReader fr = fp.GetValue();
                    fr.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();
            }
        }
Esempio n. 43
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);
        }
Esempio n. 44
0
        public void TestCase_DeleteResource()
        {
            try
            {
                var fact = new MgdServiceFactory();
                var service = (MgResourceService)fact.CreateService(MgServiceType.ResourceService);
                var featSvc = (MgdFeatureService)fact.CreateService(MgServiceType.FeatureService);

                Assert.Throws<MgNullArgumentException>(() => service.DeleteResource(null));

                service.DeleteResource(resourceNotExist);
                
                service.DeleteResource(resourceIdentifier);
                service.DeleteResource(resourceIdentifier2);
                service.DeleteResource(resourceIdentifier3);

                var resource = new MgResourceIdentifier("Library://UnitTests/Data/TEST.FeatureSource");

                var source = new MgByteSource("..\\UnitTestFiles\\TEST.FeatureSource");
                var reader = source.GetReader();
                service.SetResource(resource, reader, null);

                var dataSource = new MgByteSource("..\\UnitTestFiles\\TEST.sdf");
                var dataReader = dataSource.GetReader();
                service.SetResourceData(resource, "TEST.sdf", "File", dataReader);

                MgFeatureAggregateOptions agg = new MgFeatureAggregateOptions();
                agg.AddFeatureProperty("Data");

                var mgdr = featSvc.SelectAggregate(resource, "TEST", agg);
                Assert.True(mgdr.ReadNext());
                mgdr.Close();

                service.DeleteResource(resource);
            }
            catch (MgException ex)
            {
                Assert.Fail(ex.Message);
                ex.Dispose();
            }
        }
Esempio n. 45
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();
                }
            }
        }
Esempio n. 46
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();
        }
Esempio n. 47
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;
    }
Esempio n. 48
0
        public void TestCase_SetResourceData()
        {
            try
            {
                var fact = new MgdServiceFactory();
                var service = (MgResourceService)fact.CreateService(MgServiceType.ResourceService);

                Assert.Throws<MgNullArgumentException>(() => service.SetResourceData(null, "", "", null));

                var dataSource = new MgByteSource(dataFileName);
                var dataReader = dataSource.GetReader();

                Assert.Throws<MgNullArgumentException>(() => service.SetResourceData(resourceIdentifier, "", "File", dataReader));

                dataSource = new MgByteSource(dataFileName);
                dataReader = dataSource.GetReader();
                service.SetResourceData(resourceIdentifier, resourceDataName, "File", dataReader);

                var reader = service.EnumerateResourceData(resourceIdentifier);
                string xml = reader.ToString();

                Assert.True(xml.Contains("<Name>" + resourceDataName + "</Name>"));
            }
            catch (MgException ex)
            {
                Assert.Fail(ex.Message);
                ex.Dispose();
            }
        }
Esempio n. 49
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);
        }
Esempio n. 50
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;
    }
Esempio n. 51
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;
            }
        }
Esempio n. 52
0
 public override void SetResourceData(string resourceid, string dataname, ResourceDataType datatype, Stream stream, OSGeo.MapGuide.MaestroAPI.Utility.StreamCopyProgressDelegate callback)
 {
     MgResourceService res = this.Connection.CreateService(MgServiceType.ResourceService) as MgResourceService;
     MgByteReader reader = null;
     string tmpPath = null;
     //If stream is under our hard-coded limit (and it's seekable, which is how we're able to get that number), use the
     //overload of MgByteSource that accepts a byte[]. Otherwise dump the stream to a temp file and use the
     //file name overload (otherwise if our input stream happens to be several GBs, we run risk of
     //System.OutOfMemoryExceptions being thrown back at us)
     if (stream.CanSeek && stream.Length < (MAX_INPUT_STREAM_SIZE_MB * 1024 * 1024))
     {
         byte[] data = Utility.StreamAsArray(stream);
         MgByteSource source = new MgByteSource(data, data.Length);
         reader = source.GetReader();
     }
     else
     {
         tmpPath = Path.GetTempFileName();
         using (FileStream fs = File.OpenWrite(tmpPath))
         {
             stream.CopyTo(fs);
         }
         MgByteSource source = new MgByteSource(tmpPath);
         reader = source.GetReader();
     }
     try
     {
         res.SetResourceData(new MgResourceIdentifier(resourceid), dataname, datatype.ToString(), reader);
         LogMethodCall("MgResourceService::SetResourceData", true, resourceid, dataname, datatype.ToString(), "MgByteReader");
     }
     finally
     {
         if (!string.IsNullOrEmpty(tmpPath) && File.Exists(tmpPath))
         {
             //Be a responsible citizen and clean up our temp files when done
             try
             {
                 File.Delete(tmpPath);
             }
             catch { }
         }
     }
 }
Esempio n. 53
0
        public override void UploadPackage(string filename, Utility.StreamCopyProgressDelegate callback)
        {
            System.IO.FileInfo fi = new System.IO.FileInfo(filename);

            if (callback != null)
                callback(0, fi.Length, fi.Length);

            var res = GetResourceService();
            MgByteSource pkgSource = new MgByteSource(filename);
            MgByteReader rd = pkgSource.GetReader();
            res.ApplyResourcePackage(rd);
            rd.Dispose();
            LogMethodCall("MgResourceService::ApplyResourcePackage", true, "MgByteReader");
            if (callback != null)
                callback(fi.Length, 0, fi.Length);
        }
Esempio n. 54
0
        internal static void Update(MgPropertyCollection props, IRecord record)
        {
            if (props.Count != record.FieldCount)
            {
                throw new InvalidOperationException("Number of values to update does not match. Ensure the MgPropertyCollection was initialized first with PropertyUtil.Populate() first and that the input IRecord comes from the same source used to initialize this MgPropertyCollection"); //LOCALIZEME
            }
            //Flip the null bit first
            for (int i = 0; i < props.Count; i++)
            {
                var p  = props.GetItem(i);
                var np = p as MgNullableProperty;
                if (np != null)
                {
                    np.SetNull(true);
                }

                string name = p.Name;
                if (!record.IsNull(name))
                {
                    switch (p.PropertyType)
                    {
                    case MgPropertyType.Blob:
                    {
                        var bytes = record.GetBlob(name);
                        var bs    = new MgByteSource(bytes, bytes.Length);
                        ((MgBlobProperty)p).SetValue(bs.GetReader());
                    }
                    break;

                    case MgPropertyType.Boolean:
                    {
                        ((MgBooleanProperty)p).SetValue(record.GetBoolean(name));
                    }
                    break;

                    case MgPropertyType.Byte:
                    {
                        ((MgByteProperty)p).SetValue(record.GetByte(name));
                    }
                    break;

                    case MgPropertyType.Clob:
                    {
                        var bytes = record.GetBlob(name);
                        var bs    = new MgByteSource(bytes, bytes.Length);
                        ((MgClobProperty)p).SetValue(bs.GetReader());
                    }
                    break;

                    case MgPropertyType.DateTime:
                    {
                        var dt  = record.GetDateTime(i);
                        var mdt = new MgDateTime((short)dt.Year, (short)dt.Month, (short)dt.Day, (short)dt.Hour, (short)dt.Minute, (short)dt.Second, dt.Millisecond * 1000);
                        ((MgDateTimeProperty)p).SetValue(mdt);
                    }
                    break;

                    case MgPropertyType.Decimal:
                    case MgPropertyType.Double:
                    {
                        ((MgDoubleProperty)p).SetValue(record.GetDouble(name));
                    }
                    break;

                    case MgPropertyType.Geometry:
                    {
                        var agf = GeomConverter.GetAgf(record.GetGeometry(name));
                        ((MgGeometryProperty)p).SetValue(agf);
                    }
                    break;

                    case MgPropertyType.Int16:
                    {
                        ((MgInt16Property)p).SetValue(record.GetInt16(name));
                    }
                    break;

                    case MgPropertyType.Int32:
                    {
                        ((MgInt32Property)p).SetValue(record.GetInt32(name));
                    }
                    break;

                    case MgPropertyType.Int64:
                    {
                        ((MgInt64Property)p).SetValue(record.GetInt64(name));
                    }
                    break;

                    case MgPropertyType.Single:
                    {
                        ((MgSingleProperty)p).SetValue(record.GetSingle(name));
                    }
                    break;

                    case MgPropertyType.String:
                    {
                        ((MgStringProperty)p).SetValue(record.GetString(name));
                    }
                    break;

                    default:
                        throw new NotSupportedException();
                    }
                }
            }
        }
Esempio n. 55
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);
            }
        }
Esempio n. 56
0
        public void GeometryProperty()
        {
            MgByteSource bs = new MgByteSource("d:/mgdev/web/src/webconfig.ini");
            MgByteReader reader = bs.GetReader();

            MgGeometryProperty gp = new MgGeometryProperty("GeomPropName", reader);
            MgByteSource bs2 = new MgByteSource("d:/MgDev/UnitTest/TestData/DrawingService/SpaceShip.dwf");
            MgByteReader reader2 = bs2.GetReader();

            gp.Value = reader2;
            Assert.AreEqual(reader2.GetLength(), gp.Value.GetLength());

            Assert.AreEqual(MgPropertyType.Geometry, gp.PropertyType);
        }
Esempio n. 57
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();
            }
        }
Esempio n. 58
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();
            }
        }
Esempio n. 59
0
        internal static void Populate(MgPropertyCollection props, IMutableRecord record)
        {
            for (int i = 0; i < record.FieldCount; i++)
            {
                var    pt   = record.GetPropertyType(i);
                string name = record.GetName(i);
                if (record.IsNull(i))
                {
                    switch (pt)
                    {
                    case PropertyValueType.Blob:
                    {
                        var propVal = new MgBlobProperty(name, null);
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    case PropertyValueType.Boolean:
                    {
                        var propVal = new MgBooleanProperty(name, false);
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    case PropertyValueType.Byte:
                    {
                        var propVal = new MgByteProperty(name, 0);
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    case PropertyValueType.Clob:
                    {
                        var propVal = new MgClobProperty(name, null);
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    case PropertyValueType.DateTime:
                    {
                        var propVal = new MgDateTimeProperty(name, null);
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    case PropertyValueType.Double:
                    {
                        var propVal = new MgDoubleProperty(name, 0.0);
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    case PropertyValueType.Geometry:
                    {
                        var propVal = new MgGeometryProperty(name, null);
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    case PropertyValueType.Int16:
                    {
                        var propVal = new MgInt16Property(name, 0);
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    case PropertyValueType.Int32:
                    {
                        var propVal = new MgInt32Property(name, 0);
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    case PropertyValueType.Int64:
                    {
                        var propVal = new MgInt64Property(name, 0L);
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    case PropertyValueType.Single:
                    {
                        var propVal = new MgSingleProperty(name, 0.0f);
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    case PropertyValueType.String:
                    {
                        var propVal = new MgStringProperty(name, "");
                        propVal.SetNull(true);
                        props.Add(propVal);
                    }
                    break;

                    default:
                        throw new NotSupportedException();
                    }
                }
                else
                {
                    switch (pt)
                    {
                    case PropertyValueType.Blob:
                    {
                        var bytes = record.GetBlob(i);
                        var br    = new MgByteSource(bytes, bytes.Length);
                        var bv    = new MgBlobProperty(name, br.GetReader());
                        props.Add(bv);
                    }
                    break;

                    case PropertyValueType.Boolean:
                    {
                        props.Add(new MgBooleanProperty(name, record.GetBoolean(i)));
                    }
                    break;

                    case PropertyValueType.Byte:
                    {
                        props.Add(new MgByteProperty(name, record.GetByte(i)));
                    }
                    break;

                    case PropertyValueType.Clob:
                    {
                        var bytes = record.GetBlob(i);
                        var br    = new MgByteSource(bytes, bytes.Length);
                        var bv    = new MgClobProperty(name, br.GetReader());
                        props.Add(bv);
                    }
                    break;

                    case PropertyValueType.DateTime:
                    {
                        var dt  = record.GetDateTime(i);
                        var mdt = new MgDateTime((short)dt.Year, (short)dt.Month, (short)dt.Day, (short)dt.Hour, (short)dt.Minute, (short)dt.Second, dt.Millisecond * 1000);
                        props.Add(new MgDateTimeProperty(name, mdt));
                    }
                    break;

                    case PropertyValueType.Double:
                    {
                        props.Add(new MgDoubleProperty(name, record.GetDouble(i)));
                    }
                    break;

                    case PropertyValueType.Geometry:
                    {
                        MgByteReader agf = GeomConverter.GetAgf(record.GetGeometry(i));
                        props.Add(new MgGeometryProperty(name, agf));
                    }
                    break;

                    case PropertyValueType.Int16:
                    {
                        props.Add(new MgInt16Property(name, record.GetInt16(i)));
                    }
                    break;

                    case PropertyValueType.Int32:
                    {
                        props.Add(new MgInt32Property(name, record.GetInt32(i)));
                    }
                    break;

                    case PropertyValueType.Int64:
                    {
                        props.Add(new MgInt64Property(name, record.GetInt64(i)));
                    }
                    break;

                    case PropertyValueType.Single:
                    {
                        props.Add(new MgSingleProperty(name, record.GetSingle(i)));
                    }
                    break;

                    case PropertyValueType.String:
                    {
                        props.Add(new MgStringProperty(name, record.GetString(i)));
                    }
                    break;

                    default:
                        throw new NotSupportedException();
                    }
                }
            }
        }
Esempio n. 60
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);
            }
        }