Exemplo n.º 1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string agent = ConfigurationManager.AppSettings["MapAgentUrl"];

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

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

            RuntimeMap rtMap = mpSvc.OpenMap(rtMapId);

            RuntimeMapGroup group = rtMap.Groups[Request.Params["GROUPNAME"]];

            if (group != null)
            {
                group.Visible = !group.Visible;

                rtMap.Save(); //Always save changes after modifying

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

                lblMessage.Text = "Group (" + group.Name + ") visible: " + group.Visible;
            }
            else
            {
                lblMessage.Text = "Group (" + group.Name + ") not found!";
            }
        }
        /// <summary>
        /// Fetches the thumbnail of a symbol in a symbol library
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="symbolLibId"></param>
        /// <param name="symbolName"></param>
        /// <returns></returns>
        internal static Image GetSymbol(IServerConnection conn, string symbolLibId, string symbolName)
        {
            //NOTE: This could be nasty performance-wise if invoked at lot of times in succession
            //But these types of symbols are deprecated anyway, so we can live with it, because people
            //shouldn't be using these anymore (and thus this method by extension)

            var ds = ImageSymbolConverter.PrepareSymbolDrawingSource(conn, symbolLibId);

            //Now we should be able to query it via Drawing Service APIs
            var drawSvc = (IDrawingService)conn.GetService((int)ServiceType.Drawing);

            //Each section in the symbols.dwf represents a symbol
            var sectionList = drawSvc.EnumerateDrawingSections(ds.ResourceID);

            foreach (var sect in sectionList.Section)
            {
                if (sect.Title == symbolName)
                {
                    var sectResources = drawSvc.EnumerateDrawingSectionResources(ds.ResourceID, sect.Name);

                    foreach (var res in sectResources.SectionResource)
                    {
                        if (res.Role.ToUpper() == StringConstants.Thumbnail.ToUpper())
                        {
                            using (var rs = drawSvc.GetSectionResource(ds.ResourceID, res.Href))
                            {
                                return(Image.FromStream(rs));
                            }
                        }
                    }
                }
            }
            return(null);
        }
Exemplo n.º 3
0
        protected override void OnLoad(EventArgs e)
        {
            //Anytime we work with the Maestro API, we require an IServerConnection
            //reference. The Maestro.Login.LoginDialog provides a UI to obtain such a
            //reference.

            //If you need to obtain an IServerConnection reference programmatically and
            //without user intervention, use the ConnectionProviderRegistry class
            var login = new Maestro.Login.LoginDialog();

            if (login.ShowDialog() == DialogResult.OK)
            {
                _conn = login.Connection;

                //Connections carry a capability property that tells you what is and isn't supported.
                //Here we need to check if this connection supports the IDrawingService interface. If
                //it doesn't we can't continue.
                if (Array.IndexOf(_conn.Capabilities.SupportedServices, (int)ServiceType.Drawing) < 0)
                {
                    MessageBox.Show("This particular connection does not support the Drawing Service API");
                    Application.Exit();
                    return;
                }

                //For any non-standard service interface, we call GetService() passing in the service type and casting
                //it to the required service interface.
                _dwSvc = (IDrawingService)_conn.GetService((int)ServiceType.Drawing);
            }
            else //This sample does not work without an IServerConnection
            {
                Application.Exit();
            }
        }
Exemplo n.º 4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string agent = ConfigurationManager.AppSettings["MapAgentUrl"];

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

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

            RuntimeMap rtMap = mpSvc.OpenMap(rtMapId);

            string xml = Request.Params["SELECTION"];

            //The map selection contains one or more layer selections
            //each containing a one or more sets of identity property values
            //(because a feature may have multiple identity properties)

            MapSelection selection = new MapSelection(rtMap, HttpUtility.UrlDecode(xml));

            if (selection.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < selection.Count; i++)
                {
                    MapSelection.LayerSelection layerSel = selection[i];
                    sb.Append("<p>Layer: " + layerSel.Layer.Name + " (" + layerSel.Count + " selected item)");
                    sb.Append("<table>");

                    for (int j = 0; j < layerSel.Count; j++)
                    {
                        sb.Append("<tr>");
                        object[] values = layerSel[j];
                        for (int k = 0; k < values.Length; k++)
                        {
                            sb.Append("<td>");
                            sb.Append(values[k].ToString());
                            sb.Append("</td>");
                        }
                        sb.AppendFormat("<td><a href='FeatureInfo.aspx?MAPNAME={0}&SESSION={1}&LAYERID={2}&ID={3}'>More Info</a></td>",
                                        rtMap.Name,
                                        conn.SessionID,
                                        layerSel.Layer.ObjectId,
                                        HttpUtility.UrlEncode(layerSel.EncodeIDString(values)));
                        sb.Append("</tr>");
                    }
                    sb.Append("</table>");

                    lblMessage.Text = "Showing IDs of selected features";

                    result.InnerHtml = sb.ToString();
                }
            }
            else
            {
                lblMessage.Text = "Nothing selected. Select some features first then run this sample again.";
            }
        }
Exemplo n.º 5
0
        private void MakeTempMap()
        {
            if (m_tempmap == null)
            {
                IMapDefinition m = Utility.CreateMapDefinition(m_connection, string.Empty);
                m.CoordinateSystem = @"LOCAL_CS[""*XY-M*"", LOCAL_DATUM[""*X-Y*"", 10000], UNIT[""Meter"", 1], AXIS[""X"", EAST], AXIS[""Y"", NORTH]]"; //NOXLATE
                m.SetExtents(-1, -1, 1, 1);

                //AIMS 2012 demands this checks out. Can't flub it anymore
                m.ResourceID = "Session:" + m_connection.SessionID + "//non-existing.MapDefinition"; //NOXLATE
                var mpsvc = (IMappingService)m_connection.GetService((int)ServiceType.Mapping);
                var rid   = new ResourceIdentifier(Guid.NewGuid().ToString(), ResourceTypes.Map, m_connection.SessionID);

                m_tempmap = mpsvc.CreateMap(m);
            }
        }
Exemplo n.º 6
0
        protected void btnDescribe_Click(object sender, EventArgs e)
        {
            string agent = ConfigurationManager.AppSettings["MapAgentUrl"];

            MAPNAME.Value = Request.Params["MAPNAME"];
            SESSION.Value = Request.Params["SESSION"];

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

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

            RuntimeMap rtMap = mpSvc.OpenMap(rtMapId);

            //Get the selected layer
            RuntimeMapLayer rtLayer = rtMap.Layers.GetByObjectId(ddlLayers.SelectedValue);

            //Get the class definition
            ClassDefinition clsDef = conn.FeatureService.GetClassDefinition(rtLayer.FeatureSourceID, rtLayer.QualifiedClassName);

            StringBuilder sb = new StringBuilder();

            sb.Append("<h3>Layer Properties</h3><hr/>");
            sb.Append("<p>Name: " + rtLayer.Name + "</p>");
            sb.Append("<p>Legend Label: " + rtLayer.LegendLabel + "</p>");
            sb.Append("<p>Display Level: " + rtLayer.DisplayOrder + "</p>");
            sb.Append("<p>Expand In Legend: " + rtLayer.ExpandInLegend + "</p>");
            sb.Append("<p>Show In Legend: " + rtLayer.ShowInLegend + "</p>");
            sb.Append("<p>Visible: " + rtLayer.Visible + "</p>");
            sb.Append("<p>Layer Definition: " + rtLayer.LayerDefinitionID + "</p>");
            sb.Append("<p>Has Tooltips: " + rtLayer.HasTooltips + "</p>");
            sb.Append("<p>Filter: " + rtLayer.Filter + "</p>");

            sb.Append("<h3>Class Definition</h3><hr/>");

            sb.Append("<p>Schema: " + clsDef.QualifiedName.Split(':')[0] + "</p>");
            sb.Append("<p>Class Name: " + clsDef.Name + "</p>");
            sb.Append("<strong>Properties (* indicates identity):</strong>");
            sb.Append("<ul>");
            for (int i = 0; i < clsDef.Properties.Count; i++)
            {
                PropertyDefinition prop = clsDef.Properties[i];
                bool isIdentity         = false;

                if (prop.Type == PropertyDefinitionType.Data)
                {
                    isIdentity = clsDef.IdentityProperties.Contains((DataPropertyDefinition)prop);
                }
                string name = (isIdentity ? "* " + prop.Name : prop.Name);
                sb.AppendFormat("<li><p>Name: {0}</p><p>Type: {1}</p></li>", name, prop.Type.ToString());
            }
            sb.Append("</ul>");

            classDef.InnerHtml = sb.ToString();
        }
Exemplo n.º 7
0
        internal IList <string> GetGroups()
        {
            var list = new List <string>();

            ISiteService site = (ISiteService)_conn.GetService((int)ServiceType.Site);

            list.AddRange(site.EnumerateGroups().Group.Select(g => g.Name));

            return(list);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Extracts the specified symbols to the given folder
        /// </summary>
        /// <param name="targetFolder"></param>
        /// <param name="symbols"></param>
        /// <param name="progressCallback"></param>
        public void ExtractSymbols(string targetFolder, IEnumerable <string> symbols, Action <int, int> progressCallback)
        {
            Check.ArgumentNotEmpty(targetFolder, nameof(targetFolder));
            Check.ThatArgumentIsFolder(targetFolder, nameof(targetFolder));

            if (symbols == null)
            {
                ExtractSymbols(targetFolder);
            }
            else
            {
                IDrawingService drawSvc = (IDrawingService)_conn.GetService((int)ServiceType.Drawing);
                IDrawingSource  ds      = PrepareSymbolDrawingSource(_conn, _symbolLibId);

                //Each section in the symbols.dwf represents a symbol
                var sectionList = drawSvc.EnumerateDrawingSections(ds.ResourceID);
                var symbolNames = new HashSet <string>(symbols);
                int processed   = 0;

                foreach (var sect in sectionList.Section)
                {
                    var sectResources = drawSvc.EnumerateDrawingSectionResources(ds.ResourceID, sect.Name);

                    if (!symbolNames.Contains(sect.Title))
                    {
                        continue;
                    }

                    foreach (var res in sectResources.SectionResource)
                    {
                        if (res.Role.ToUpper() == StringConstants.Thumbnail.ToUpper())
                        {
                            ExtractSymbol(targetFolder, drawSvc, ds, sect, res);
                            processed++;
                            if (progressCallback != null)
                            {
                                progressCallback(processed, symbolNames.Count);
                            }
                        }
                    }
                }
            }
        }
        protected void btnSelect_Click(object sender, EventArgs e)
        {
            string agent = ConfigurationManager.AppSettings["MapAgentUrl"];

            MAPNAME.Value = Request.Params["MAPNAME"];
            SESSION.Value = Request.Params["SESSION"];

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

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

            RuntimeMap rtMap = mpSvc.OpenMap(rtMapId);

            //Get the selected layer
            RuntimeMapLayer rtLayer = rtMap.Layers.GetByObjectId(ddlLayers.SelectedValue);

            //Query using the user filter
            IFeatureReader reader = conn.FeatureService.QueryFeatureSource(
                rtLayer.FeatureSourceID,
                rtLayer.QualifiedClassName,
                txtFilter.Text);

            //Get the selection set
            MapSelection sel = new MapSelection(rtMap);

            MapSelection.LayerSelection layerSel = null;
            if (!sel.Contains(rtLayer))
            {
                sel.Add(rtLayer);
            }
            layerSel = sel[rtLayer];

            //Clear any existing selections
            layerSel.Clear();

            //Populate selection set with query result
            int added = layerSel.AddFeatures(reader, -1);

            //Generate selection string
            string selXml = sel.ToXml();

            //Generate a client-side set selection and execute a "Zoom to Selection" afterwards
            Page.ClientScript.RegisterStartupScript(
                this.GetType(),
                "load",
                "<script type=\"text/javascript\"> window.onload = function() { parent.parent.GetMapFrame().SetSelectionXML('" + selXml + "'); parent.parent.ExecuteMapAction(10); } </script>");


            lblMessage.Text = added + " features in " + rtLayer.Name + " selected";
        }
Exemplo n.º 10
0
        public void TestServiceCapabilities()
        {
            Skip.If(_fixture.Skip, _fixture.SkipReason);

            var conn = CreateHttpConnection("http://tempuri.org", "en", new Version(1, 2, 0));

            //Work through the interface
            IServerConnection isvc = (IServerConnection)conn;

            int[] stypes = isvc.Capabilities.SupportedServices;
            foreach (int st in stypes)
            {
                try
                {
                    IService svc = isvc.GetService(st);
                }
                catch
                {
                    Assert.True(false, "Supported service type mismatch");
                }
            }

            var method = conn.GetType().GetMethod("SetSiteVersion", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

            method.Invoke(conn, new[] { new Version(2, 0, 0) });

            stypes = isvc.Capabilities.SupportedServices;
            foreach (int st in stypes)
            {
                try
                {
                    IService svc = isvc.GetService(st);
                }
                catch
                {
                    Assert.True(false, "Supported service type mismatch");
                }
            }
        }
Exemplo n.º 11
0
        public void TestServiceCapabilities()
        {
            var builder = new RequestBuilder(new Uri("http://tempuri.org"), "en");
            var conn    = new HttpServerConnection(builder);

            conn.SetSiteVersion(new Version(1, 2, 0));

            //Work through the interface
            IServerConnection isvc = (IServerConnection)conn;

            int[] stypes = isvc.Capabilities.SupportedServices;
            foreach (int st in stypes)
            {
                try
                {
                    IService svc = isvc.GetService(st);
                }
                catch
                {
                    Assert.Fail("Supported service type mismatch");
                }
            }

            conn.SetSiteVersion(new Version(2, 0, 0));

            stypes = isvc.Capabilities.SupportedServices;
            foreach (int st in stypes)
            {
                try
                {
                    IService svc = isvc.GetService(st);
                }
                catch
                {
                    Assert.Fail("Supported service type mismatch");
                }
            }
        }
        private void LoadSymbols(string symResId)
        {
            var ds = ImageSymbolConverter.PrepareSymbolDrawingSource(_conn, symResId);
            //Now we should be able to query it via Drawing Service APIs
            var drawSvc = (IDrawingService)_conn.GetService((int)ServiceType.Drawing);

            //Each section in the symbols.dwf represents a symbol
            var sectionList = drawSvc.EnumerateDrawingSections(ds.ResourceID);

            lstSymbols.Items.Clear();

            int idx     = 0;
            var imgList = new ImageList();

            imgList.ImageSize = new Size(32, 32);
            var symbols = new List <ListViewItem>();

            foreach (var sect in sectionList.Section)
            {
                var sectResources = drawSvc.EnumerateDrawingSectionResources(ds.ResourceID, sect.Name);

                foreach (var res in sectResources.SectionResource)
                {
                    if (res.Role.ToUpper() == StringConstants.Thumbnail.ToUpper())
                    {
                        using (var rs = drawSvc.GetSectionResource(ds.ResourceID, res.Href))
                        {
                            Image img = Image.FromStream(rs);
                            imgList.Images.Add(img);

                            var item = new ListViewItem(sect.Title);
                            item.ImageIndex = idx;
                            symbols.Add(item);

                            idx++;
                        }
                    }
                }
            }

            lstSymbols.SmallImageList = imgList;
            lstSymbols.LargeImageList = imgList;
            foreach (var sym in symbols)
            {
                lstSymbols.Items.Add(sym);
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Invokes the render callback method
        /// </summary>
        /// <param name="dummy">Unused parameter</param>
        private void ThreadRender(object dummy)
        {
            try
            {
                //Create a copy of the connection for local usage
                IServerConnection con  = _parent.Connection.Clone();
                var            tileSvc = (ITileService)con.GetService((int)ServiceType.Tile);
                AutoResetEvent ev      = new AutoResetEvent(false);

                while (!_parent.Cancel)
                {
                    KeyValuePair <int, int>?round = null;

                    lock (_syncLock)
                    {
                        if (TileSet.Count == 0 && _fillerComplete)
                        {
                            return; //No more data
                        }
                        if (TileSet.Count > 0)
                        {
                            round = TileSet.Dequeue();
                        }
                    }

                    if (_parent.Cancel)
                    {
                        return;
                    }

                    if (round == null) //No data, but producer is still running
                    {
                        Thread.Sleep(500);
                    }
                    else
                    {
                        RenderTile(ev, tileSvc, round.Value.Key, round.Value.Value, _scale, _group);
                    }
                }
            }
            catch { }
            finally
            {
                _completeFlag--;
                _event.Set();
            }
        }
Exemplo n.º 14
0
        private void lnkViewer_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            TreeNode root = MapTree.SelectedNode;

            while (root.Parent != null)
            {
                root = root.Parent;
            }

            IMapDefinition mdf = root.Tag as IMapDefinition;

            if (mdf != null)
            {
                BusyWaitDelegate worker = () =>
                {
                    IMappingService mapSvc = (IMappingService)m_connection.GetService((int)ServiceType.Mapping);
                    var             rtMap  = mapSvc.CreateMap(mdf);
                    return(rtMap);
                };
                Action <object, Exception> onComplete = (obj, ex) =>
                {
                    if (ex != null)
                    {
                        throw ex;
                    }

                    if (obj != null)
                    {
                        var rtMap = (RuntimeMap)obj;
                        using (var diag = new MapExtentsDialog(rtMap))
                        {
                            if (diag.ShowDialog() == DialogResult.OK)
                            {
                                var env = diag.GetEnvelope();
                                txtLowerX.Text = env.MinX.ToString(CultureInfo.InvariantCulture);
                                txtLowerY.Text = env.MinY.ToString(CultureInfo.InvariantCulture);
                                txtUpperX.Text = env.MaxX.ToString(CultureInfo.InvariantCulture);
                                txtUpperY.Text = env.MaxY.ToString(CultureInfo.InvariantCulture);
                            }
                        }
                    }
                };
                BusyWaitDialog.Run(Strings.PreparingMap, worker, onComplete);
            }
        }
Exemplo n.º 15
0
        private void LoadMap(IServerConnection conn, string mapDefinitionId)
        {
            //To render a map, we need to create a runtime map instance. IMappingService gives us
            //the required services. This is not a standard service, so you need to call GetService()
            //with the correct ServiceType to get the IMappingService reference.
            IMappingService mapSvc = (IMappingService)conn.GetService((int)ServiceType.Mapping);

            //Get an IMapDefinition from the specified resource id. GetResource() returns an instance
            //of IResource, which IMapDefinition extends. As long as you pass in a valid resource id
            //of the right type, you can safely cast the returned object to the expected type.
            IMapDefinition mapDef = (IMapDefinition)conn.ResourceService.GetResource(mapDefinitionId);

            //Create a runtime map
            var rtMap = mapSvc.CreateMap(mapDef);

            //Load it into the viewer
            mapViewer.LoadMap(rtMap);
        }
Exemplo n.º 16
0
        private void LoadMap(IServerConnection conn, string mapDefinitionId)
        {
            //To render a map, we need to create a runtime map instance. IMappingService gives us
            //the required services. This is not a standard service, so you need to call GetService()
            //with the correct ServiceType to get the IMappingService reference.
            IMappingService mapSvc = (IMappingService)conn.GetService((int)ServiceType.Mapping);

            //Get an IMapDefinition from the specified resource id. GetResource() returns an instance
            //of IResource, which IMapDefinition extends. As long as you pass in a valid resource id
            //of the right type, you can safely cast the returned object to the expected type.
            IMapDefinition mapDef = (IMapDefinition)conn.ResourceService.GetResource(mapDefinitionId);

            //Create a runtime map
            var rtMap = mapSvc.CreateMap(mapDef);

            //Load it into the viewer
            mapViewer.LoadMap(rtMap);
        }
        internal static ImagePreviewResult GenerateSymbolDefinitionPreview(IServerConnection conn, IResource previewCopy, int width, int height)
        {
            //For Symbol Definition previews, we make a placeholder Layer Definition with the
            ILayerDefinition        layerDef = Utility.CreateDefaultLayer(conn, LayerType.Vector);
            IVectorLayerDefinition2 vl       = layerDef.SubLayer as IVectorLayerDefinition2;

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

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

                    var mappingSvc = (IMappingService)conn.GetService((int)ServiceType.Mapping);
                    var img        = mappingSvc.GetLegendImage(42, ldfId, 0, 4, width, height, "PNG"); //NOXLATE
                    return(new ImagePreviewResult()
                    {
                        ImagePreview = img
                    });
                }
            }
            return(null);
        }
Exemplo n.º 18
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            var login = new LoginDialog();

            if (login.ShowDialog() == DialogResult.OK)
            {
                _conn = login.Connection;
                if (Array.IndexOf(_conn.Capabilities.SupportedServices, (int)ServiceType.Mapping) < 0)
                {
                    MessageBox.Show(Strings.ErrIncompatibleConnection);
                    Application.Exit();
                }
                _mappingSvc = (IMappingService)_conn.GetService((int)ServiceType.Mapping);
            }
            else
            {
                Application.Exit();
            }
        }
Exemplo n.º 19
0
            /// <summary>
            /// Regenerates the sheet list in this drawing source.
            /// </summary>
            /// <param name="source">The drawing source</param>
            /// <param name="conn">The server connection</param>
            /// <returns>True if sheets were regenerated. False otherwise</returns>
            public static bool RegenerateSheetList(this IDrawingSource source, IServerConnection conn)
            {
                Check.ArgumentNotNull(source, nameof(source));
                Check.ArgumentNotNull(conn, nameof(conn));
                Check.ArgumentNotEmpty(source.ResourceID, $"{nameof(source)}.{nameof(source.ResourceID)}");

                IDrawingService dwSvc  = (IDrawingService)conn.GetService((int)ServiceType.Drawing);
                var             sheets = dwSvc.EnumerateDrawingSections(source.ResourceID);
                bool            bRegen = sheets.Section.Count > 0;

                source.RemoveAllSheets();
                if (bRegen)
                {
                    foreach (var sht in sheets.Section)
                    {
                        source.AddSheet(source.CreateSheet(sht.Name, 0, 0, 0, 0));
                    }
                }
                return(bRegen);
            }
Exemplo n.º 20
0
        private void LoadMap(IServerConnection conn, string mapDefinitionId)
        {
            //To render a map, we need to create a runtime map instance. IMappingService gives us
            //the required services. This is not a standard service, so you need to call GetService()
            //with the correct ServiceType to get the IMappingService reference.
            IMappingService mapSvc = (IMappingService)conn.GetService((int)ServiceType.Mapping);

            //Get an IMapDefinition from the specified resource id. GetResource() returns an instance
            //of IResource, which IMapDefinition extends. As long as you pass in a valid resource id
            //of the right type, you can safely cast the returned object to the expected type.
            IMapDefinition mapDef = (IMapDefinition)conn.ResourceService.GetResource(mapDefinitionId);

            //Create a runtime map
            var rtMap = mapSvc.CreateMap(mapDef);

            //Set map display to match the size of our picture box
            rtMap.InitialiseDisplayParameters(pictureBox1.Width, pictureBox1.Height);

            //Note: Sometimes the meters-per-unit value may be inaccurate. This has ramifications on
            //display and measuring. If you have access to the MgCoordinateSystem API, create an instance
            //using the Map Definition's WKT and use the meters-per-unit value obtained like so:
            //
            // MgCoordinateSystemFactory csFactory = new MgCoordinateSystemFactory();
            // MgCoordinateSystem cs = csFactory.Create(srs);
            // double metersPerUnit = cs.ConvertCoordinateSystemUnitsToMeters(1.0);
            //
            //This result gives a more accurate MPU

            //Before we can do anything with this map, it must first be saved.
            //Anytime you manipulate this map, you need to save it for the changes to be
            //applied back to the MapGuide Server
            rtMap.Save();

            //Render the map with its current display parameters in PNG format. A System.IO.Stream
            //is returned.
            using (var stream = rtMap.Render("PNG"))
            {
                //Create a System.Drawing.Image from the stream and load it into our picture box.
                pictureBox1.Image = Image.FromStream(stream);
            }
        }
        public override IResource CreateItem(string startPoint, IServerConnection conn)
        {
            using (var picker = new ResourcePicker(conn, ResourceTypes.DrawingSource.ToString(), ResourcePickerMode.OpenResource))
            {
                picker.SetStartingPoint(startPoint);
                if (picker.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    var ldf = ObjectFactory.CreateDefaultLayer(OSGeo.MapGuide.ObjectModels.LayerDefinition.LayerType.Drawing, new Version(1, 0, 0));
                    ldf.SubLayer.ResourceId = picker.ResourceID;
                    var dl = ((IDrawingLayerDefinition)ldf.SubLayer);
                    dl.LayerFilter = string.Empty;
                    dl.MinScale    = 0;

                    IDrawingService dwSvc  = (IDrawingService)conn.GetService((int)ServiceType.Drawing);
                    var             sheets = dwSvc.EnumerateDrawingSections(picker.ResourceID);
                    dl.Sheet = sheets.Section[0].Name;

                    return(ldf);
                }
                return(null);
            }
        }
        public override IResource CreateItem(string startPoint, IServerConnection conn)
        {
            using (var picker = new ResourcePicker(conn.ResourceService, ResourceTypes.DrawingSource, ResourcePickerMode.OpenResource))
            {
                picker.SetStartingPoint(startPoint);
                if (picker.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    var ldf = ObjectFactory.CreateDefaultLayer(conn, OSGeo.MapGuide.ObjectModels.LayerDefinition.LayerType.Drawing, new Version(1, 0, 0));
                    ldf.SubLayer.ResourceId = picker.ResourceID;
                    var dl = ((IDrawingLayerDefinition)ldf.SubLayer);
                    dl.LayerFilter = string.Empty;
                    dl.MinScale = 0;

                    IDrawingService dwSvc = (IDrawingService)conn.GetService((int)ServiceType.Drawing);
                    var sheets = dwSvc.EnumerateDrawingSections(picker.ResourceID);
                    dl.Sheet = sheets.Section[0].Name;

                    return ldf;
                }
                return null;
            }
        }
Exemplo n.º 23
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string agent = ConfigurationManager.AppSettings["MapAgentUrl"];
                MAPNAME.Value = Request.Params["MAPNAME"];
                SESSION.Value = Request.Params["SESSION"];

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

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

                RuntimeMap rtMap = mpSvc.OpenMap(rtMapId);
                foreach (RuntimeMapLayer rtLayer in rtMap.Layers)
                {
                    ddlLayers.Items.Add(new ListItem(rtLayer.Name, rtLayer.ObjectId));
                }
            }
        }
Exemplo n.º 24
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string agent   = ConfigurationManager.AppSettings["MapAgentUrl"];
                string mapName = Request.Params["MAPNAME"];
                string session = Request.Params["SESSION"];

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

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

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

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

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

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

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

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

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

                rtMap.Save();

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

                Page.ClientScript.RegisterStartupScript(
                    this.GetType(),
                    "load",
                    "<script type=\"text/javascript\"> window.onload = function() { parent.parent.Refresh(); } </script>");
            }
        }
Exemplo n.º 25
0
            /// <summary>
            /// Updates the extents of all sheets based on their respective AutoCAD Viewport Data in the embedded PIA resource
            /// </summary>
            /// <param name="source">The drawing source</param>
            /// <param name="conn">The server connection</param>
            public static void UpdateExtents(this IDrawingSource source, IServerConnection conn)
            {
                Check.ArgumentNotNull(source, nameof(source));
                Check.ArgumentNotNull(conn, nameof(conn));
                Check.ArgumentNotEmpty(source.ResourceID, $"{nameof(source)}.{nameof(source.ResourceID)}");

                //Need drawing service
                if (Array.IndexOf(conn.Capabilities.SupportedServices, (int)ServiceType.Drawing) < 0)
                {
                    throw new NotSupportedException(string.Format(OSGeo.MapGuide.MaestroAPI.Strings.ERR_SERVICE_NOT_SUPPORTED, ServiceType.Drawing.ToString()));
                }

                var drawSvc = (IDrawingService)conn.GetService((int)ServiceType.Drawing);

                foreach (var sht in source.Sheet)
                {
                    var list = drawSvc.EnumerateDrawingSectionResources(source.ResourceID, sht.Name);
                    foreach (var res in list.SectionResource)
                    {
                        if (res.Role == "AutoCAD Viewport Data") //NOXLATE
                        {
                            using (var stream = drawSvc.GetSectionResource(source.ResourceID, res.Href))
                            {
                                //This is text content
                                using (var sr = new StreamReader(stream))
                                {
                                    try
                                    {
                                        string content = sr.ReadToEnd();

                                        //Viewport parameters are:
                                        //
                                        // llx
                                        // lly
                                        // urx
                                        // ury
                                        //
                                        //A the first space after each number of each parameter marks the end of that value

                                        // 4 - length of "llx="
                                        int    idx  = content.IndexOf("llx") + 4;                              //NOXLATE
                                        string sllx = content.Substring(idx, content.IndexOf(" ", idx) - idx); //NOXLATE
                                        // 4 - length of "lly="
                                        idx = content.IndexOf("lly") + 4;                                      //NOXLATE
                                        string slly = content.Substring(idx, content.IndexOf(" ", idx) - idx); //NOXLATE
                                        // 4 - length of "urx="
                                        idx = content.IndexOf("urx") + 4;                                      //NOXLATE
                                        string surx = content.Substring(idx, content.IndexOf(" ", idx) - idx); //NOXLATE
                                        // 4 - length of "ury="
                                        idx = content.IndexOf("ury") + 4;                                      //NOXLATE
                                        string sury = content.Substring(idx, content.IndexOf(" ", idx) - idx); //NOXLATE

                                        //Update extents
                                        sht.Extent = ObjectFactory.CreateEnvelope(
                                            Convert.ToDouble(sllx),
                                            Convert.ToDouble(slly),
                                            Convert.ToDouble(surx),
                                            Convert.ToDouble(sury));
                                    }
                                    catch { }
                                }
                            }
                        }
                    }
                }
            }
        /// <summary>
        /// Raises the System.Windows.Forms.Form.Load event
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            Dictionary <string, ListViewItem> ul = new Dictionary <string, ListViewItem>();
            Dictionary <string, ListViewItem> gl = new Dictionary <string, ListViewItem>();

            UsersAndGroups.Items.Clear();
            var site = (ISiteService)m_connection.GetService((int)ServiceType.Site);

            foreach (UserListUser u in site.EnumerateUsers().Items)
            {
                ListViewItem lvi = new ListViewItem(new string[] { u.FullName, u.Description, StatusNames[IHUSER] }, IHUSER);
                lvi.Tag = u;
                UsersAndGroups.Items.Add(lvi);
                ul.Add(u.Name, lvi);
            }

            foreach (GroupListGroup g in site.EnumerateGroups().Group)
            {
                ListViewItem lvi = new ListViewItem(new string[] { g.Name, g.Description, StatusNames[IHGROUP] }, IHGROUP);
                lvi.Tag = g;
                UsersAndGroups.Items.Add(lvi);
                gl.Add(g.Name, lvi);
            }

            if (m_resourceId.IsFolder)
            {
                m_folderHeader = m_connection.ResourceService.GetFolderHeader(m_resourceId);
                if (m_folderHeader.Security.Users != null && m_folderHeader.Security.Users.User != null)
                {
                    foreach (ResourceSecurityTypeUsersUser u in m_folderHeader.Security.Users.User)
                    {
                        if (ul.ContainsKey(u.Name))
                        {
                            UpdateListItem(u, ul[u.Name]);
                        }
                    }
                }

                if (m_folderHeader.Security.Groups != null && m_folderHeader.Security.Groups.Group != null)
                {
                    foreach (ResourceSecurityTypeGroupsGroup g in m_folderHeader.Security.Groups.Group)
                    {
                        if (gl.ContainsKey(g.Name))
                        {
                            UpdateListItem(g, gl[g.Name]);
                        }
                    }
                }

                UseInherited.Checked = m_folderHeader.Security.Inherited;
                tabControl1.TabPages.Remove(WMSTab);
                tabControl1.TabPages.Remove(WFSTab);
                tabControl1.TabPages.Remove(CustomTab);
                tabControl1.TabPages.Remove(ReferenceTab);
            }
            else
            {
                m_resourceHeader = m_connection.ResourceService.GetResourceHeader(m_resourceId);
                if (m_resourceHeader.Security.Users != null && m_resourceHeader.Security.Users.User != null)
                {
                    foreach (ResourceSecurityTypeUsersUser u in m_resourceHeader.Security.Users.User)
                    {
                        if (ul.ContainsKey(u.Name))
                        {
                            UpdateListItem(u, ul[u.Name]);
                        }
                    }
                }

                if (m_resourceHeader.Security.Groups != null && m_resourceHeader.Security.Groups.Group != null)
                {
                    foreach (ResourceSecurityTypeGroupsGroup g in m_resourceHeader.Security.Groups.Group)
                    {
                        if (gl.ContainsKey(g.Name))
                        {
                            UpdateListItem(g, gl[g.Name]);
                        }
                    }
                }

                UseInherited.Checked = m_resourceHeader.Security.Inherited;
                if (m_resourceId.Extension != ResourceTypes.LayerDefinition.ToString())
                {
                    tabControl1.TabPages.Remove(WMSTab);
                }
                else
                {
                    UpdateWMSDisplay();
                }

                if (m_resourceId.Extension != ResourceTypes.FeatureSource.ToString())
                {
                    tabControl1.TabPages.Remove(WFSTab);
                }
                else
                {
                    UpdateWFSDisplay();
                }
            }

            //Hide the tabControl if it only has one tab
            if (tabControl1.TabCount == 1)
            {
                foreach (Control c in new System.Collections.ArrayList(tabControl1.TabPages[0].Controls))
                {
                    tabControl1.Controls.Remove(c);
                    c.Top += tabControl1.Top;
                    this.Controls.Add(c);
                }

                this.Controls.Remove(tabControl1);
            }

            this.Text = m_resourceId;
            UseInherited_CheckedChanged(null, null);
        }
Exemplo n.º 27
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string agent   = ConfigurationManager.AppSettings["MapAgentUrl"];
            string mapName = Request.Params["MAPNAME"];
            string layerId = Request.Params["LAYERID"];
            string id      = HttpUtility.UrlDecode(Request.Params["ID"]);

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

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

            RuntimeMap      rtMap = mpSvc.OpenMap(rtMapId);
            RuntimeMapLayer layer = rtMap.Layers.GetByObjectId(layerId);

            //The values returned are in the same order as the array from the IdentityProperties
            object[]       values  = layer.ParseSelectionValues(id);
            PropertyInfo[] idProps = layer.IdentityProperties;

            //Having decoded the identity property values and knowing what names they are from the
            //RuntimeMapLayer, construct the selection filter based on these values.
            //
            //This sample assumes the Sheboygan dataset and so all identity property values are
            //known to be only numeric or strings. If this is not the case for you, use the Type
            //property in PropertyInfo to determine how to construct the filter
            string[] conditions = new string[idProps.Length];
            for (int i = 0; i < idProps.Length; i++)
            {
                conditions[i] = idProps[i].Name + " = " + values[i].ToString();
            }
            //OR all the conditions together to form our final filter
            string selFilter = string.Join(" OR ", conditions);

            //Execute the query
            IFeatureReader reader = conn.FeatureService.QueryFeatureSource(
                layer.FeatureSourceID,
                layer.QualifiedClassName,
                selFilter);

            //Use a StringBuilder because we are doing a lot of concatentation here
            StringBuilder sb = new StringBuilder();

            //Collect the field names
            string[] fieldNames = new string[reader.FieldCount];
            for (int i = 0; i < reader.FieldCount; i++)
            {
                fieldNames[i] = reader.GetName(i);
            }

            int count = 0;

            //Write out the attribute table
            while (reader.ReadNext())
            {
                sb.Append("<table border='1'>");
                for (int i = 0; i < fieldNames.Length; i++)
                {
                    //Just like the MgFeatureReader, you must test for null before
                    //attempting extraction of values, but unlike MgFeatureReader this
                    //offers an indexer property that returns System.Object which allows
                    //a nice and easy way to string coerce all property values.
                    sb.Append("<tr>");
                    sb.Append("<td><strong>" + fieldNames[i] + "</strong></td>");
                    sb.Append("<td>" + (reader.IsNull(i) ? "(null)" : reader[i]) + "</td>");
                    sb.Append("</tr>");
                }
                sb.Append("</table>");
                count++;
            }
            content.InnerHtml = sb.ToString();
            lblMessage.Text   = "Showing attributes of " + count + " features";
            reader.Close();
        }
Exemplo n.º 28
0
        /// <summary>
        /// Previews the given resource
        /// </summary>
        /// <param name="res"></param>
        /// <param name="edSvc"></param>
        /// <param name="locale"></param>
        public void Preview(IResource res, IEditorService edSvc, string locale)
        {
            IServerConnection conn = edSvc.CurrentConnection;

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

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

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

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

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

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

                    if (obj != null)
                    {
                        var rtMap = (RuntimeMap)obj;
                        if (_viewManager != null)
                        {
                            _viewManager.OpenContent(ViewRegion.Document, () => new MapPreviewViewContent(rtMap, _launcher, (edSvc.IsNew) ? null : edSvc.ResourceID));
                        }
                        else
                        {
                            var diag = new MapPreviewDialog(rtMap, _launcher, (edSvc.IsNew) ? null : edSvc.ResourceID);
                            diag.Show(null);
                        }
                    }
                    else //Fallback, shouldn't happen
                    {
                        _inner.Preview(res, edSvc, locale);
                    }
                };
                BusyWaitDialog.Run(Strings.PrgPreparingResourcePreview, worker, onComplete);
            }
            else
            {
                _inner.Preview(res, edSvc, locale);
            }
        }
Exemplo n.º 29
0
 /// <summary>
 /// Gets the service of the specified type
 /// </summary>
 /// <param name="serviceType"></param>
 /// <returns></returns>
 public IService GetService(int serviceType)
 {
     return(_conn.GetService(serviceType));
 }
Exemplo n.º 30
0
        protected override void OnLoad(EventArgs e)
        {
            //This call is a one-time only call that will instantly register all known resource
            //version types and validators. This way you never have to manually reference a
            //ObjectModels assembly of the desired resource type you want to work with
            ModelSetup.Initialize();

            //Anytime we work with the Maestro API, we require an IServerConnection
            //reference. The Maestro.Login.LoginDialog provides a UI to obtain such a
            //reference.

            //If you need to obtain an IServerConnection reference programmatically and
            //without user intervention, use the ConnectionProviderRegistry class
            var login = new Maestro.Login.LoginDialog();
            if (login.ShowDialog() == DialogResult.OK)
            {
                _conn = login.Connection;

                //Connections carry a capability property that tells you what is and isn't supported.
                //Here we need to check if this connection supports the IDrawingService interface. If
                //it doesn't we can't continue.
                if (Array.IndexOf(_conn.Capabilities.SupportedServices, (int)ServiceType.Drawing) < 0)
                {
                    MessageBox.Show("This particular connection does not support the Drawing Service API");
                    Application.Exit();
                    return;
                }

                //For any non-standard service interface, we call GetService() passing in the service type and casting
                //it to the required service interface.
                _dwSvc = (IDrawingService)_conn.GetService((int)ServiceType.Drawing);
            }
            else //This sample does not work without an IServerConnection
            {
                Application.Exit();
            }
        }
Exemplo n.º 31
0
        /// <summary>
        /// Initializes this instance
        /// </summary>
        /// <param name="conn"></param>
        protected internal RuntimeMap(IServerConnection conn)
        {
            this.StrictSelection = true;
            this.IsDirty = false;
            _disableChangeTracking = true;

            this.WatermarkUsage = (int)WatermarkUsageType.Viewer;
            this.SiteVersion = conn.SiteVersion;
            this.SessionId = conn.SessionID;
            this.ObjectId = Guid.NewGuid().ToString();
            m_changeList = new Dictionary<string, ChangeList>();
            _finiteDisplayScales = new double[0];
            this.CurrentConnection = conn;
            if (Array.IndexOf(conn.Capabilities.SupportedServices, (int)ServiceType.Mapping) >= 0)
            {
                _mapSvc = (IMappingService)conn.GetService((int)ServiceType.Mapping);
            }
            if (Array.IndexOf(conn.Capabilities.SupportedCommands, (int)CommandType.GetResourceContents) >= 0)
            {
                _getRes = (IGetResourceContents)conn.CreateCommand((int)CommandType.GetResourceContents);
            }
            this.Layers = new RuntimeMapLayerCollection(this);
            this.Groups = new RuntimeMapGroupCollection(this);
        }
Exemplo n.º 32
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string agent = ConfigurationManager.AppSettings["MapAgentUrl"];

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

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

            RuntimeMap rtMap = mpSvc.OpenMap(rtMapId);

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

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

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

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

                CreateDistrictsLayer(conn, fsId, layerId);

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

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

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

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

                rtMap.Save();

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

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

            rtMap = mpSvc.OpenMap(rtMapId);
            DumpMap(rtMap);
        }
Exemplo n.º 33
0
        /// <summary>
        /// Creates a fusion flexible layout
        /// </summary>
        /// <param name="owner"></param>
        /// <param name="templateName">The name of the template. See <see cref="FusionTemplateNames"/> for the common pre-defined names</param>
        /// <returns></returns>
        public static IApplicationDefinition CreateFlexibleLayout(IServerConnection owner, string templateName)
        {
            Check.NotNull(owner, "owner"); //NOXLATE

            /*
            Check.Precondition(Array.IndexOf(owner.Capabilities.SupportedServices, (int)ServiceType.Fusion) >= 0, "Required Fusion service not supported on this connection");

            var fusionSvc = (IFusionService)owner.GetService((int)ServiceType.Fusion);
            var templates = fusionSvc.GetApplicationTemplates();

            var appDef = DeserializeEmbeddedFlexLayout();
            //Find matching template.
            var tpl = templates.FindTemplate(templateName);
            if (tpl != null)
            {
                appDef.TemplateUrl = tpl.LocationUrl;
                appDef.Title = tpl.Name;
            }
            appDef.CurrentConnection = owner;
            return appDef;
            */

            Check.Precondition(Array.IndexOf(owner.Capabilities.SupportedServices, (int)ServiceType.Fusion) >= 0, "Required Fusion service not supported on this connection");

            IApplicationDefinition appDef = new ApplicationDefinitionType()
            {
                CurrentConnection = owner,
                MapSet = new System.ComponentModel.BindingList<MapGroupType>(),
                WidgetSet = new System.ComponentModel.BindingList<WidgetSetType>()
            };

            var fusionSvc = (IFusionService)owner.GetService((int)ServiceType.Fusion);
            var templates = fusionSvc.GetApplicationTemplates();
            var widgets = fusionSvc.GetApplicationWidgets();
            var containers = fusionSvc.GetApplicationContainers();

            //Find matching template. If it's a known template we should be able to
            //build it programatically, otherwise return a deserialized copy from our
            //embedded resource
            var tpl = templates.FindTemplate(templateName);
            if (tpl != null)
            {
                appDef.TemplateUrl = tpl.LocationUrl;
                appDef.Title = tpl.Name;
            }
            else
            {
                //NOTE: Depending on MapGuide Server version, this document may be
                //invalid (eg. References to widgets not available in that version)
                return DeserializeEmbeddedFlexLayout(owner);
            }

            //Toolbars, every template has them
            var toolbar = appDef.CreateContainer("Toolbar", containers.FindContainer("Toolbar")); //NOXLATE
            var secToolbar = appDef.CreateContainer("ToolbarSecondary", containers.FindContainer("Toolbar")); //NOXLATE
            var vertToolbar = appDef.CreateContainer("ToolbarVertical", containers.FindContainer("Toolbar")); //NOXLATE

            //Context menus, every template has them
            var mapContextMenu = appDef.CreateContainer("MapContextMenu", containers.FindContainer("ContextMenu")); //NOXLATE
            var taskPaneMenu = appDef.CreateContainer("TaskMenu", containers.FindContainer("ContextMenu")); //NOXLATE

            //Menu
            var menu = appDef.CreateContainer("FileMenu", containers.FindContainer("Toolbar")); //NOXLATE

            //Status bar
            var statusbar = appDef.CreateContainer("Statusbar", containers.FindContainer("Splitterbar")); //NOXLATE

            string mapId = "MainMap"; //NOXLATE
            //Set default map group
            appDef.AddMapGroup(mapId, true, string.Empty);

            //Create default widget set
            var widgetSet = appDef.CreateWidgetSet(appDef.CreateMapWidget(mapId, mapContextMenu.Name));
            appDef.AddWidgetSet(widgetSet);

            //Add all known non-parameterized widgets to this widget set
            foreach (var wgt in widgets.WidgetInfo)
            {
                if (Array.IndexOf(parameterizedWidgets, wgt.Type) < 0)
                {
                    var widget = appDef.CreateWidget(wgt.Type, wgt);
                    widgetSet.AddWidget(widget);
                }
            }

            //Add some parameterized ones

            //Zoom In
            var zoomIn = (IUIWidget)appDef.CreateWidget("ZoomIn", widgets.FindWidget(KnownWidgetNames.ZoomOnClick)); //NOXLATE
            zoomIn.SetValue("Factor", "2"); //NOXLATE
            zoomIn.StatusText = zoomIn.Tooltip = Strings.ADF_Widget_ZoomIn_Desc;
            zoomIn.Label = Strings.ADF_Widget_ZoomIn_Label;
            zoomIn.ImageUrl = "images/icons.png"; //NOXLATE
            zoomIn.ImageClass = "zoom-in-fixed"; //NOXLATE
            var vZoomIn = CreateVerticalWidget(zoomIn);

            //Zoom Out
            var zoomOut = (IUIWidget)appDef.CreateWidget("ZoomOut", widgets.FindWidget(KnownWidgetNames.ZoomOnClick)); //NOXLATE
            zoomOut.SetValue("Factor", "0.5"); //NOXLATE
            zoomOut.StatusText = zoomOut.Tooltip = Strings.ADF_Widget_ZoomOut_Desc;
            zoomOut.Label = Strings.ADF_Widget_ZoomOut_Label;
            zoomOut.ImageUrl = "images/icons.png"; //NOXLATE
            zoomOut.ImageClass = "zoom-out-fixed"; //NOXLATE
            var vZoomOut = CreateVerticalWidget(zoomOut);

            //Previous View
            var prevView = (IUIWidget)appDef.CreateWidget("PreviousView", widgets.FindWidget(KnownWidgetNames.ExtentHistory)); //NOXLATE
            prevView.SetValue("Direction", "previous"); //NOXLATE
            prevView.StatusText = prevView.Tooltip = Strings.ADF_Widget_PreviousView_Desc;
            prevView.Label = Strings.ADF_Widget_PreviousView_Label;
            prevView.ImageUrl = "images/icons.png"; //NOXLATE
            prevView.ImageClass = "view-back"; //NOXLATE
            var vPrevView = CreateVerticalWidget(prevView);

            //Next View
            var nextView = (IUIWidget)appDef.CreateWidget("NextView", widgets.FindWidget(KnownWidgetNames.ExtentHistory)); //NOXLATE
            nextView.SetValue("Direction", "next"); //NOXLATE
            nextView.StatusText = nextView.Tooltip = Strings.ADF_Widget_NextView_Desc;
            nextView.Label = Strings.ADF_Widget_NextView_Label;
            nextView.ImageUrl = "images/icons.png"; //NOXLATE
            nextView.ImageClass = "view-forward"; //NOXLATE
            var vNextView = CreateVerticalWidget(nextView);

            //Buffer
            var buffer = (IUIWidget)appDef.CreateWidget("tbBuffer", widgets.FindWidget(KnownWidgetNames.BufferPanel)); //NOXLATE
            //buffer.SetValue("Target", "TaskPane"); //NOXLATE
            buffer.StatusText = buffer.Tooltip = Strings.ADF_Widget_Buffer_Desc;
            buffer.Tooltip = Strings.ADF_Widget_Buffer_Label;

            //Measure
            var measure = (IUIWidget)appDef.CreateWidget("Measure", widgets.FindWidget(KnownWidgetNames.Measure)); //NOXLATE
            var measureParams = new NameValueCollection();
            measureParams["Type"] = "both"; //NOXLATE
            measureParams["MeasureTooltipContainer"] = "MeasureResult"; //NOXLATE
            measureParams["MeasureTooltipType"] = "dynamic"; //NOXLATE
            measureParams["DistancePrecision"] = "0"; //NOXLATE
            measureParams["AreaPrecision"] = "0"; //NOXLATE
            measureParams["Units"] = "meters"; //NOXLATE
            measureParams["Target"] = "TaskPane"; //NOXLATE
            measure.SetAllValues(measureParams);
            measure.StatusText = buffer.Tooltip = Strings.ADF_Widget_Measure_Desc;
            measure.Tooltip = Strings.ADF_Widget_Measure_Label;

            //Show Overview
            var showOverview = (IUIWidget)appDef.CreateWidget("showOverview", widgets.FindWidget(KnownWidgetNames.InvokeScript)); //NOXLATE
            showOverview.Label = "Show Overview"; //NOXLATE
            showOverview.SetValue("Script", "showOverviewMap()"); //NOXLATE

            //Show Task Pane
            var showTaskPane = (IUIWidget)appDef.CreateWidget("showTaskPane", widgets.FindWidget(KnownWidgetNames.InvokeScript)); //NOXLATE
            showTaskPane.Label = "Show Task Pane"; //NOXLATE
            showTaskPane.SetValue("Script", "showTaskPane()"); //NOXLATE

            //Show Legend
            var showLegend = (IUIWidget)appDef.CreateWidget("showLegend", widgets.FindWidget(KnownWidgetNames.InvokeScript)); //NOXLATE
            showLegend.Label = "Show Legend"; //NOXLATE
            showLegend.SetValue("Script", "showLegend()"); //NOXLATE

            //Show Selection Panel
            var showSelectionPanel = (IUIWidget)appDef.CreateWidget("showSelectionPanel", widgets.FindWidget(KnownWidgetNames.InvokeScript)); //NOXLATE
            showSelectionPanel.Label = "Show Selection Panel"; //NOXLATE
            showSelectionPanel.SetValue("Script", "showSelectionPanel()"); //NOXLATE

            //Coordinate Tracker
            var coordTracker = appDef.CreateWidget("statusCoordinates", widgets.FindWidget(KnownWidgetNames.CursorPosition)); //NOXLATE
            coordTracker.SetValue("Template", "X: {x} {units}, Y: {y} {units}"); //NOXLATE
            coordTracker.SetValue("Precision", "4"); //NOXLATE
            coordTracker.SetValue("EmptyText", "&amp;nbsp;"); //NOXLATE

            //Selection Info
            var selInfo = appDef.CreateWidget("statusSelection", widgets.FindWidget(KnownWidgetNames.SelectionInfo)); //NOXLATE
            selInfo.SetValue("EmptyText", "No selection"); //NOXLATE

            //View Size
            var viewSize = appDef.CreateWidget("statusViewSize", widgets.FindWidget(KnownWidgetNames.ViewSize)); //NOXLATE
            viewSize.SetValue("Template", "{w} x {h} ({units})"); //NOXLATE
            viewSize.SetValue("Precision", "2"); //NOXLATE

            widgetSet.AddWidget(zoomIn);
            widgetSet.AddWidget(zoomOut);
            widgetSet.AddWidget(prevView);
            widgetSet.AddWidget(nextView);
            widgetSet.AddWidget(buffer);
            widgetSet.AddWidget(measure);
            widgetSet.AddWidget(showOverview);
            widgetSet.AddWidget(showTaskPane);
            widgetSet.AddWidget(showLegend);
            widgetSet.AddWidget(showSelectionPanel);
            widgetSet.AddWidget(coordTracker);
            widgetSet.AddWidget(selInfo);
            widgetSet.AddWidget(viewSize);

            widgetSet.AddWidget(vZoomIn);
            widgetSet.AddWidget(vZoomOut);
            widgetSet.AddWidget(vPrevView);
            widgetSet.AddWidget(vNextView);

            //Now here's where things may diverge completely between templates
            //So let's try for something that is somewhat consistent

            //Init primary toolbar
            toolbar.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.Print));

            //2.2 specific stuff
            if (owner.SiteVersion >= new Version(2, 2))
            {
                toolbar.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.QuickPlot));
            }

            toolbar.AddItem(appDef.CreateSeparator());
            toolbar.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.RefreshMap));
            //2.4 requires maptips to be a toggle widget
            if (owner.SiteVersion >= VER_240)
            {
                toolbar.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.Maptip));
            }
            toolbar.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.SelectRadius));
            toolbar.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.SelectPolygon));
            toolbar.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.ClearSelection));

            toolbar.AddItem(appDef.CreateWidgetReference(buffer.Name));
            toolbar.AddItem(appDef.CreateWidgetReference(measure.Name));

            //2.2 specific stuff
            if (owner.SiteVersion >= new Version(2, 2))
            {
                toolbar.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.FeatureInfo));
                toolbar.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.Query));
                toolbar.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.Theme));
                toolbar.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.Redline));
            }

            toolbar.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.ViewOptions));
            toolbar.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.About));
            toolbar.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.Help));

            //Init secondary toolbar
            secToolbar.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.Select));
            secToolbar.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.Pan));
            secToolbar.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.Zoom));
            secToolbar.AddItem(appDef.CreateWidgetReference(zoomIn.Name));
            secToolbar.AddItem(appDef.CreateWidgetReference(zoomOut.Name));
            secToolbar.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.InitialMapView));
            secToolbar.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.ZoomToSelection));
            secToolbar.AddItem(appDef.CreateWidgetReference(prevView.Name));
            secToolbar.AddItem(appDef.CreateWidgetReference(nextView.Name));

            //Init vertical toolbar
            widgetSet.AddWidget(CreateVerticalWidget((IUIWidget)appDef.CreateWidget(KnownWidgetNames.Select, widgets.FindWidget(KnownWidgetNames.Select))));
            widgetSet.AddWidget(CreateVerticalWidget((IUIWidget)appDef.CreateWidget(KnownWidgetNames.Pan, widgets.FindWidget(KnownWidgetNames.Pan))));
            widgetSet.AddWidget(CreateVerticalWidget((IUIWidget)appDef.CreateWidget(KnownWidgetNames.Zoom, widgets.FindWidget(KnownWidgetNames.Zoom))));
            widgetSet.AddWidget(CreateVerticalWidget((IUIWidget)appDef.CreateWidget(KnownWidgetNames.InitialMapView, widgets.FindWidget(KnownWidgetNames.InitialMapView))));
            widgetSet.AddWidget(CreateVerticalWidget((IUIWidget)appDef.CreateWidget(KnownWidgetNames.ZoomToSelection, widgets.FindWidget(KnownWidgetNames.ZoomToSelection))));

            vertToolbar.AddItem(appDef.CreateWidgetReference("vert" + KnownWidgetNames.Select)); //NOXLATE
            vertToolbar.AddItem(appDef.CreateWidgetReference("vert" + KnownWidgetNames.Pan)); //NOXLATE
            vertToolbar.AddItem(appDef.CreateWidgetReference("vert" + KnownWidgetNames.Zoom)); //NOXLATE
            vertToolbar.AddItem(appDef.CreateWidgetReference(vZoomIn.Name));
            vertToolbar.AddItem(appDef.CreateWidgetReference(vZoomOut.Name));
            vertToolbar.AddItem(appDef.CreateWidgetReference("vert" + KnownWidgetNames.InitialMapView)); //NOXLATE
            vertToolbar.AddItem(appDef.CreateWidgetReference("vert" + KnownWidgetNames.ZoomToSelection)); //NOXLATE
            vertToolbar.AddItem(appDef.CreateWidgetReference(vPrevView.Name));
            vertToolbar.AddItem(appDef.CreateWidgetReference(vNextView.Name));

            //Main menu
            menu.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.MapMenu));

            //2.2 specific stuff
            if (owner.SiteVersion >= new Version(2, 2))
            {
                menu.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.BasemapSwitcher));
            }
            var viewMenu = appDef.CreateFlyout(Strings.ADF_Flyout_View);
            viewMenu.AddItem(appDef.CreateWidgetReference(showOverview.Name));
            viewMenu.AddItem(appDef.CreateWidgetReference(showTaskPane.Name));
            viewMenu.AddItem(appDef.CreateWidgetReference(showLegend.Name));
            viewMenu.AddItem(appDef.CreateWidgetReference(showSelectionPanel.Name));
            menu.AddItem(viewMenu);

            //status bar
            statusbar.AddItem(appDef.CreateWidgetReference(coordTracker.Name));
            statusbar.AddItem(appDef.CreateWidgetReference(selInfo.Name));
            statusbar.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.EditableScale));
            statusbar.AddItem(appDef.CreateWidgetReference(viewSize.Name));

            //Map Context Menu
            mapContextMenu.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.RefreshMap));
            mapContextMenu.AddItem(appDef.CreateSeparator());
            mapContextMenu.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.Pan));
            mapContextMenu.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.Zoom));
            mapContextMenu.AddItem(appDef.CreateSeparator());
            mapContextMenu.AddItem(appDef.CreateWidgetReference(zoomIn.Name));
            mapContextMenu.AddItem(appDef.CreateWidgetReference(zoomOut.Name));
            mapContextMenu.AddItem(appDef.CreateSeparator());
            var zoomMenu = appDef.CreateFlyout(Strings.ADF_Flyout_Zoom);

            mapContextMenu.AddItem(zoomMenu);
            mapContextMenu.AddItem(appDef.CreateSeparator());
            mapContextMenu.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.Select));
            mapContextMenu.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.ClearSelection));
            var selectMoreMenu = appDef.CreateFlyout(Strings.ADF_Flyout_SelectMore);

            mapContextMenu.AddItem(selectMoreMenu);
            mapContextMenu.AddItem(appDef.CreateSeparator());
            mapContextMenu.AddItem(appDef.CreateWidgetReference(buffer.Name));
            mapContextMenu.AddItem(appDef.CreateWidgetReference(measure.Name));

            if (owner.SiteVersion >= new Version(2, 2))
            {
                mapContextMenu.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.FeatureInfo));
                mapContextMenu.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.Query));
                mapContextMenu.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.Theme));
                mapContextMenu.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.Redline));
            }

            mapContextMenu.AddItem(appDef.CreateSeparator());
            mapContextMenu.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.ViewOptions));
            mapContextMenu.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.Help));
            mapContextMenu.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.About));

            //Tasks Context Menu
            taskPaneMenu.AddItem(appDef.CreateWidgetReference(measure.Name));
            taskPaneMenu.AddItem(appDef.CreateWidgetReference(buffer.Name));

            if (owner.SiteVersion >= new Version(2, 2))
            {
                taskPaneMenu.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.FeatureInfo));
                taskPaneMenu.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.Query));
                taskPaneMenu.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.Theme));
                taskPaneMenu.AddItem(appDef.CreateWidgetReference(KnownWidgetNames.Redline));
            }

            //Now add them all to the main widget set
            widgetSet.AddContainer(toolbar);
            widgetSet.AddContainer(secToolbar);
            widgetSet.AddContainer(vertToolbar);
            widgetSet.AddContainer(menu);
            widgetSet.AddContainer(statusbar);
            widgetSet.AddContainer(mapContextMenu);
            widgetSet.AddContainer(taskPaneMenu);

            //Set positioning
            toolbar.Position = "top"; //NOXLATE
            secToolbar.Position = "top"; //NOXLATE
            menu.Position = "top"; //NOXLATE
            statusbar.Position = "bottom"; //NOXLATE
            mapContextMenu.Position = "top"; //NOXLATE
            taskPaneMenu.Position = "top"; //NOXLATE
            vertToolbar.Position = "left"; //NOXLATE

            return appDef;
        }
Exemplo n.º 34
0
        /// <summary>
        /// Fetches the thumbnail of a symbol in a symbol library
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="symbolLibId"></param>
        /// <param name="symbolName"></param>
        /// <returns></returns>
        internal static Image GetSymbol(IServerConnection conn, string symbolLibId, string symbolName)
        {
            //NOTE: This could be nasty performance-wise if invoked at lot of times in succession
            //But these types of symbols are deprecated anyway, so we can live with it, because people
            //shouldn't be using these anymore (and thus this method by extension)

            var ds = ImageSymbolConverter.PrepareSymbolDrawingSource(conn, symbolLibId);

            //Now we should be able to query it via Drawing Service APIs
            var drawSvc = (IDrawingService)conn.GetService((int)ServiceType.Drawing);

            //Each section in the symbols.dwf represents a symbol
            var sectionList = drawSvc.EnumerateDrawingSections(ds.ResourceID);

            foreach (var sect in sectionList.Section)
            {
                if (sect.Title == symbolName)
                {
                    var sectResources = drawSvc.EnumerateDrawingSectionResources(ds.ResourceID, sect.Name);

                    foreach (var res in sectResources.SectionResource)
                    {
                        if (res.Role.ToUpper() == StringConstants.Thumbnail.ToUpper())
                        {
                            using (var rs = drawSvc.GetSectionResource(ds.ResourceID, res.Href))
                            {
                                return Image.FromStream(rs);
                            }
                        }
                    }
                }
            }
            return null;
        }
Exemplo n.º 35
0
        private void LoadMap(IServerConnection conn, string mapDefinitionId)
        {
            //To render a map, we need to create a runtime map instance. IMappingService gives us
            //the required services. This is not a standard service, so you need to call GetService()
            //with the correct ServiceType to get the IMappingService reference.
            IMappingService mapSvc = (IMappingService)conn.GetService((int)ServiceType.Mapping);

            //Get an IMapDefinition from the specified resource id. GetResource() returns an instance
            //of IResource, which IMapDefinition extends. As long as you pass in a valid resource id
            //of the right type, you can safely cast the returned object to the expected type.
            IMapDefinition mapDef = (IMapDefinition)conn.ResourceService.GetResource(mapDefinitionId);

            //Create a runtime map
            var rtMap = mapSvc.CreateMap(mapDef);

            //Set map display to match the size of our picture box
            rtMap.InitialiseDisplayParameters(pictureBox1.Width, pictureBox1.Height);

            //Note: Sometimes the meters-per-unit value may be inaccurate. This has ramifications on
            //display and measuring. If you have access to the MgCoordinateSystem API, create an instance
            //using the Map Definition's WKT and use the meters-per-unit value obtained like so:
            //
            // MgCoordinateSystemFactory csFactory = new MgCoordinateSystemFactory();
            // MgCoordinateSystem cs = csFactory.Create(srs);
            // double metersPerUnit = cs.ConvertCoordinateSystemUnitsToMeters(1.0);
            //
            //This result gives a more accurate MPU

            //Before we can do anything with this map, it must first be saved.
            //Anytime you manipulate this map, you need to save it for the changes to be
            //applied back to the MapGuide Server
            rtMap.Save();

            //Render the map with its current display parameters in PNG format. A System.IO.Stream
            //is returned.
            using (var stream = rtMap.Render("PNG"))
            {
                //Create a System.Drawing.Image from the stream and load it into our picture box.
                pictureBox1.Image = Image.FromStream(stream);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string agent = ConfigurationManager.AppSettings["MapAgentUrl"];

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

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

            RuntimeMap rtMap = mpSvc.OpenMap(rtMapId);

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

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

                rtMap.Save();

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

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

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

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

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

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

                rtMap.Save();

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

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

            rtMap = mpSvc.OpenMap(rtMapId);
            DumpMap(rtMap);
        }