示例#1
0
        /// <summary> Retruns the background Color object</summary>
        /// <param name="idx">index of the color</param>
        /// <returns> MgColor object that represents the background color</returns>
        internal MgColor getBGColor(int idx)
        {
            MgColor mgColor = null;

            Debug.Assert(idx > 0);

            lock (this)
            {
                if (idx < _bgColors.Count)
                {
                    mgColor = (MgColor)_bgColors[idx];
                }

                if (mgColor == null)
                {
                    bool   isDefaultColor;
                    String colorStr = getBgStr(idx, out isDefaultColor);
                    mgColor = new MgColor(colorStr);

                    //If default color is used then no need to add it in bgColor table.
                    if (!isDefaultColor)
                    {
                        if (idx >= _bgColors.Count)
                        {
                            _bgColors.SetSize(idx + 1);
                        }
                        _bgColors[idx] = mgColor;
                    }
                }
            }

            return(mgColor);
        }
示例#2
0
        /// <summary>
        /// change the values on the color in the specified index
        /// </summary>
        /// <param name="index"></param>
        /// <param name="foreColor"></param>
        /// <param name="backColor"></param>
        /// <returns></returns>
        public bool SetColor(int index, int foreColor, int backColor)
        {
            if (index == 0 || index > Count)
            {
                return(false);
            }

            int alpha = (byte)(foreColor >> 24);
            int red   = (byte)(foreColor >> 16);
            int green = (byte)(foreColor >> 8);
            int blue  = (byte)(foreColor);

            if (index >= _fgColors.Count)
            {
                _fgColors.SetSize(index + 1);
            }
            _fgColors[index] = new MgColor(alpha, red, green, blue, MagicSystemColor.Undefined, false);

            alpha = (byte)(backColor >> 24);
            red   = (byte)(backColor >> 16);
            green = (byte)(backColor >> 8);
            blue  = (byte)(backColor);

            if (index >= _bgColors.Count)
            {
                _bgColors.SetSize(index + 1);
            }
            _bgColors[index] = new MgColor(alpha, red, green, blue, MagicSystemColor.Undefined, false);

            return(true);
        }
示例#3
0
        /// <summary>
        /// Colors
        /// </summary>
        /// <param name="control"></param>
        /// <param name="properties"></param>
        static void BuildColorsProperties(MgControlBase control, Dictionary <string, DesignerPropertyInfo> properties)
        {
            bool isDefaultvalue = false;
            int  value          = GetRuntimeValueAsInt(control, PropInterface.PROP_TYPE_COLOR, ref isDefaultvalue);

            if (value > 0)
            {
                MgColor color = isDefaultvalue ? null : Manager.GetColorsTable().getBGColor(value);
                properties.Add(Constants.WinPropBackColor, new DesignerPropertyInfo()
                {
                    VisibleInPropertyGrid = true, Value = color, IsDefaultValue = isDefaultvalue
                });

                if (control.Type == MgControlType.CTRL_TYPE_TEXT || control.Type == MgControlType.CTRL_TYPE_TABLE)
                {
                    properties.Add(Constants.WinPropIsTransparent, new DesignerPropertyInfo()
                    {
                        VisibleInPropertyGrid = false, Value = color, IsDefaultValue = isDefaultvalue
                    });
                }

                color = isDefaultvalue ? null : Manager.GetColorsTable().getFGColor(value);
                properties.Add(Constants.WinPropForeColor, new DesignerPropertyInfo()
                {
                    VisibleInPropertyGrid = true, Value = color, IsDefaultValue = isDefaultvalue
                });
            }
            else
            {
                // fixed defect #:132036, 132037
                // for button control set default color that we set on MgButton.cs , BtnFace\WindowText convert from ControlUtils.cs method MgColor2Color()
                if (control.Type == MgControlType.CTRL_TYPE_BUTTON)
                {
                    MgColor colorBG = new MgColor()
                    {
                        IsSystemColor = true, SystemColor = MagicSystemColor.BtnFace
                    };
                    properties.Add(Constants.WinPropBackColor, new DesignerPropertyInfo()
                    {
                        VisibleInPropertyGrid = true, Value = colorBG, IsDefaultValue = isDefaultvalue
                    });

                    MgColor colorFG = new MgColor()
                    {
                        IsSystemColor = true, SystemColor = MagicSystemColor.WindowText
                    };
                    properties.Add(Constants.WinPropForeColor, new DesignerPropertyInfo()
                    {
                        VisibleInPropertyGrid = true, Value = colorFG, IsDefaultValue = isDefaultvalue
                    });
                }
            }
        }
示例#4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        object ConvertBackColorProp(object obj, object value)
        {
            Color   backgroundColor = Color.Empty;
            MgColor mgColor         = (MgColor)value;

            // if the color is transparent then set the background color to null
            if (mgColor != null)
            {
                //For logical text, we support alpha values.
                bool supportsAlpha = obj is LgText || GuiUtils.supportTransparency(obj);
                backgroundColor = ControlUtils.MgColor2Color(mgColor, GuiUtils.supportTransparency(obj), supportsAlpha);
            }
            return(backgroundColor);
        }
示例#5
0
        public void Execute(IPlatformFactory factory, ITestLogger logger)
        {
            short   nRed   = 22;
            short   nGreen = 33;
            short   nBlue  = 44;
            short   nAlpha = 55;
            MgColor color  = new MgColor(nRed, nGreen, nBlue, nAlpha);

            Assert.AreEqual(nRed, color.Red);
            Assert.AreEqual(nGreen, color.Green);
            Assert.AreEqual(nBlue, color.Blue);
            Assert.AreEqual(nAlpha, color.Alpha);
            String scolor = nRed.ToString("x") + nGreen.ToString("x") + nBlue.ToString("x") + nAlpha.ToString("x");

            Assert.AreEqual(scolor, color.Color);
        }
示例#6
0
        public void Execute(IPlatformFactory factory, ITestLogger logger)
        {
            var resSvc    = (MgResourceService)factory.CreateService(MgServiceType.ResourceService);
            var renderSvc = (MgRenderingService)factory.CreateService(MgServiceType.RenderingService);
            var root      = "../../TestData/TileService/";

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

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

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

            Utils.LoadResource(resSvc, "Library://UnitTests/Maps/BaseMap.MapDefinition", root + "UT_BaseMap.mdf");

            var mdfId = new MgResourceIdentifier("Library://UnitTests/Maps/BaseMap.MapDefinition");

            //This is a sample request from the AJAX viewer. It selected 7 features. It should do the same here.
            var dpi    = 96;
            var width  = 773;
            var height = 696;
            var scale  = 4345.697945713148;
            var x      = -87.72117757411266;
            var y      = 43.7527161153258;
            var wkt    = "POLYGON((-87.72250482778884 43.75497812742761, -87.72134799968197 43.75497812742761, -87.72134799968197 43.75358373640595, -87.72250482778884 43.75358373640595, -87.72250482778884 43.75497812742761))";
            var map    = (MgMap)factory.CreateMap(mdfId, mdfId.Name, width, height, x, y, scale, dpi);

            var selColor   = new MgColor(0, 0, 255);
            var renderOpts = new MgRenderingOptions(MgImageFormats.Png, 1 | 2 | 4 | 8, selColor);
            var result     = renderSvc.RenderDynamicOverlay(map, null, renderOpts);

            Utils.CheckValidImage(result, width, height, MgImageFormats.Png);
        }
示例#7
0
        public void Execute(IPlatformFactory factory, ITestLogger logger)
        {
            var resSvc    = (MgResourceService)factory.CreateService(MgServiceType.ResourceService);
            var renderSvc = (MgRenderingService)factory.CreateService(MgServiceType.RenderingService);
            var root      = "../../TestData/TileService/";

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

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

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

            Utils.LoadResource(resSvc, "Library://UnitTests/Maps/BaseMap.MapDefinition", root + "UT_BaseMap.mdf");

            var mdfId = new MgResourceIdentifier("Library://UnitTests/Maps/BaseMap.MapDefinition");

            var dpi    = 96;
            var width  = 773;
            var height = 696;
            var scale  = 4345.697945713148;
            var x      = -87.72117757411266;
            var y      = 43.7527161153258;
            var wkt    = "POLYGON((-87.72250482778884 43.75497812742761, -87.72134799968197 43.75497812742761, -87.72134799968197 43.75358373640595, -87.72250482778884 43.75358373640595, -87.72250482778884 43.75497812742761))";
            var map    = (MgMap)factory.CreateMap(mdfId, mdfId.Name, width, height, x, y, scale, dpi);

            var bgColor = new MgColor(255, 255, 255);
            var result  = renderSvc.RenderMapLegend(map, 200, 600, bgColor, MgImageFormats.Png);

            Utils.CheckValidImage(result, 200, 600, MgImageFormats.Png);
        }
示例#8
0
 public Stream RenderMapLegend(Mapping.RuntimeMap map, int width, int height, System.Drawing.Color backgroundColor, string format)
 {
     var impl = map as LocalRuntimeMap;
     if (impl == null)
         throw new ArgumentException("Instance is not a LocalRuntimeMap", "map"); //LOCALIZEME
     var renderSvc = GetRenderingService();
     GetByteReaderMethod fetch = () =>
     {
         MgColor bgColor = new MgColor(backgroundColor);
         return renderSvc.RenderMapLegend(impl.GetWrappedInstance(), width, height, bgColor, format);
     };
     return new MgReadOnlyStream(fetch);
 }
示例#9
0
        public override System.IO.Stream RenderRuntimeMap(RuntimeMap rtmap, double x1, double y1, double x2, double y2, int width, int height, int dpi, string format, bool clip)
        {
            var resourceId = rtmap.ResourceID;
            MgRenderingService rnd = this.Connection.CreateService(MgServiceType.RenderingService) as MgRenderingService;
            MgResourceService res = this.Connection.CreateService(MgServiceType.ResourceService) as MgResourceService;
            MgGeometryFactory gf = new MgGeometryFactory();

            string mapname = new ResourceIdentifier(resourceId).Path;

            //TODO: The render is missing the clip param for the extent override method

            GetByteReaderMethod fetch = () =>
            {
                MgMap map = new MgMap();
                map.Open(res, mapname);
                MgSelection sel = new MgSelection(map);
                //The color accepted by MgColor has alpha as the last value, but the returned has alpha first
                MgColor color = new MgColor(Utility.ParseHTMLColor(map.GetBackgroundColor()));
                MgEnvelope env = new MgEnvelope(gf.CreateCoordinateXY(x1, y1), gf.CreateCoordinateXY(x2, y2));

                return rnd.RenderMap(map, sel, env, width, height, color, format);
            };
            LogMethodCall("MgRenderingService::RenderMap", true, "MgMap", "MgSelection", "MgEnvelope", width.ToString(), height.ToString(), "MgColor", format);
            return new MgReadOnlyStream(fetch);
        }
示例#10
0
        public override System.IO.Stream RenderRuntimeMap(RuntimeMap rtmap, double x, double y, double scale, int width, int height, int dpi, string format, bool clip)
        {
            var resourceId = rtmap.ResourceID;
            MgRenderingService rnd = this.Connection.CreateService(MgServiceType.RenderingService) as MgRenderingService;
            MgResourceService res = this.Connection.CreateService(MgServiceType.ResourceService) as MgResourceService;
            MgGeometryFactory gf = new MgGeometryFactory();

            string mapname = new ResourceIdentifier(resourceId).Path;

            GetByteReaderMethod fetch = () =>
            {
                MgMap map = new MgMap();
                map.Open(res, mapname);
                MgSelection sel = new MgSelection(map);
                //The color accepted by MgColor has alpha as the last value, but the returned has alpha first
                MgColor color = new MgColor(Utility.ParseHTMLColor(map.GetBackgroundColor()));
                MgCoordinate coord = gf.CreateCoordinateXY(x, y);
                return rnd.RenderMap(map, sel, coord, scale, width, height, color, format, true);
            };
            LogMethodCall("MgRenderingService::RenderMap", true, "MgMap", "MgSelection", "MgPoint("+ x + "," + y + ")", scale.ToString(), width.ToString(), height.ToString(), "MgColor", format, true.ToString());
            return new MgReadOnlyStream(fetch);
        }
示例#11
0
        public Stream RenderMapLegend(RuntimeMap map, int width, int height, System.Drawing.Color backgroundColor, string format)
        {
            MgRenderingService rnd = this.Connection.CreateService(MgServiceType.RenderingService) as MgRenderingService;
            MgResourceService res = this.Connection.CreateService(MgServiceType.ResourceService) as MgResourceService;

            GetByteReaderMethod fetch = () =>
            {
                MgMap mmap = new MgMap();
                mmap.Open(res, map.Name);
                MgSelection sel = new MgSelection(mmap);
                MgColor color = new MgColor(backgroundColor);
                return rnd.RenderMapLegend(mmap, width, height, color, format);
            };
            LogMethodCall("MgRenderingService::RenderMapLegend", true, "MgMap", width.ToString(CultureInfo.InvariantCulture), height.ToString(CultureInfo.InvariantCulture), "#" + ColorTranslator.ToHtml(backgroundColor), format);
            return new MgReadOnlyStream(fetch);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                var fact = new MgdServiceFactory();
                MgdRenderingService  renSvc = (MgdRenderingService)fact.CreateService(MgServiceType.RenderingService);
                MgResourceIdentifier resId  = new MgResourceIdentifier(textBox1.Text);

                var sw = new Stopwatch();
                sw.Start();
                MgdMap map = new MgdMap(resId);
                sw.Stop();
                Trace.TraceInformation("Runtime map created in {0}ms", sw.ElapsedMilliseconds);
                MgdSelection selection = null;

                if (!string.IsNullOrEmpty(txtSelectLayer.Text) &&
                    !string.IsNullOrEmpty(txtSelectFilter.Text))
                {
                    selection = new MgdSelection(map);

                    var layers = map.GetLayers();
                    if (layers.IndexOf(txtSelectLayer.Text) >= 0)
                    {
                        var layer = layers.GetItem(txtSelectLayer.Text);

                        var query = new MgFeatureQueryOptions();
                        query.SetFilter(txtSelectFilter.Text);

                        var reader = layer.SelectFeatures(query);

                        selection.AddFeatures(layer, reader, 0);

                        Trace.TraceInformation("{0} features in selection set", selection.GetSelectedFeaturesCount(layer, layer.GetFeatureClassName()));
                    }
                }

                double x;
                double y;
                if (double.TryParse(textBox2.Text, out x) &&
                    double.TryParse(textBox3.Text, out y))
                {
                    map.SetViewCenterXY(x, y);
                }

                int w;
                int h;
                if (int.TryParse(txtWidth.Text, out w) &&
                    int.TryParse(txtHeight.Text, out h))
                {
                    map.SetDisplaySize(w, h);
                }

                double scale;
                if (double.TryParse(textBox4.Text, out scale))
                {
                    map.SetViewScale(scale);
                }
                int mode;
                if (int.TryParse(textBox6.Text, out mode))
                {
                }

                MgColor             selColor   = new MgColor("0x0000FFFF");
                MgdRenderingOptions renderOpts = new MgdRenderingOptions(textBox5.Text, mode, selColor);

                sw.Start();
                MgByteReader response = renSvc.RenderDynamicOverlay(map, selection, renderOpts);
                sw.Stop();
                Trace.TraceInformation("RenderDynamicOverlay executed in {0}ms", sw.ElapsedMilliseconds);

                new ImageResponseDialog(response).ShowDialog();
            }
            catch (MgException ex)
            {
                MessageBox.Show(ex.ToString(), "Error from MapGuide");
            }
        }
示例#13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="colorIndex"></param>
        /// <param name="isBackGround"></param>
        /// <returns></returns>
        protected Color ColorIndexToColor(int colorIndex, bool isBackGround)
        {
            MgColor mgColor = isBackGround ? Manager.GetColorsTable().getBGColor(colorIndex) : Manager.GetColorsTable().getFGColor(colorIndex);

            return(ControlUtils.MgColor2Color(mgColor, isBackGround, isBackGround));
        }
示例#14
0
 public MgViewerRenderingOptions(string format, int behavior, MgColor color)
 {
     this.Format = format;
     this.Behavior = behavior;
     this.Color = color;
 }
示例#15
0
 public void Color()
 {
     short nRed = 22;
     short nGreen = 33;
     short nBlue = 44;
     short nAlpha = 55;
     MgColor color = new MgColor(nRed, nGreen, nBlue, nAlpha);
     Assert.AreEqual(nRed, color.Red);
     Assert.AreEqual(nGreen, color.Green);
     Assert.AreEqual(nBlue, color.Blue);
     Assert.AreEqual(nAlpha, color.Alpha);
     String scolor = nRed.ToString("x") + nGreen.ToString("x") + nBlue.ToString("x") + nAlpha.ToString("x");
     Assert.AreEqual(scolor, color.Color);
 }
示例#16
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;
            }
        }
示例#17
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                var fact = new MgdServiceFactory();
                MgdRenderingService renSvc = (MgdRenderingService)fact.CreateService(MgServiceType.RenderingService);
                MgResourceIdentifier resId = new MgResourceIdentifier(textBox1.Text);

                var sw = new Stopwatch();
                sw.Start();
                MgdMap map = new MgdMap(resId);
                sw.Stop();
                Trace.TraceInformation("Runtime map created in {0}ms", sw.ElapsedMilliseconds);
                MgdSelection selection = null;

                if (!string.IsNullOrEmpty(txtSelectLayer.Text) &&
                    !string.IsNullOrEmpty(txtSelectFilter.Text))
                {
                    selection = new MgdSelection(map);

                    var layers = map.GetLayers();
                    if (layers.IndexOf(txtSelectLayer.Text) >= 0)
                    {
                        var layer = layers.GetItem(txtSelectLayer.Text);

                        var query = new MgFeatureQueryOptions();
                        query.SetFilter(txtSelectFilter.Text);

                        var reader = layer.SelectFeatures(query);

                        selection.AddFeatures(layer, reader, 0);

                        Trace.TraceInformation("{0} features in selection set", selection.GetSelectedFeaturesCount(layer, layer.GetFeatureClassName()));
                    }
                }

                double x;
                double y;
                if (double.TryParse(textBox2.Text, out x) &&
                    double.TryParse(textBox3.Text, out y))
                {
                    map.SetViewCenterXY(x, y);
                }

                int w;
                int h;
                if (int.TryParse(txtWidth.Text, out w) &&
                    int.TryParse(txtHeight.Text, out h))
                {
                    map.SetDisplaySize(w, h);
                }

                double scale;
                if (double.TryParse(textBox4.Text, out scale))
                {
                    map.SetViewScale(scale);
                }
                int mode;
                if (int.TryParse(textBox6.Text, out mode))
                { 
                    
                }

                MgColor selColor = new MgColor("0x0000FFFF");
                MgdRenderingOptions renderOpts = new MgdRenderingOptions(textBox5.Text, mode, selColor);

                sw.Start();
                MgByteReader response = renSvc.RenderDynamicOverlay(map, selection, renderOpts);
                sw.Stop();
                Trace.TraceInformation("RenderDynamicOverlay executed in {0}ms", sw.ElapsedMilliseconds);

                new ImageResponseDialog(response).ShowDialog();
            }
            catch (MgException ex)
            {
                MessageBox.Show(ex.ToString(), "Error from MapGuide");
            }
        }
示例#18
0
        /// <summary>Converts MgColor to an System color</summary>
        /// <param name="mgColor"></param>
        /// <param name="checkTransparent">if true, returns null for transparent colors, if false - return real bgcolor</param>
        /// <param name="useAlpha">if true, use alpha(opacity) value of the color</param>
        /// <returns></returns>
        public static Color MgColor2Color(MgColor mgColor, bool checkTransparent, bool useAlpha)
        {
            Color color = Color.Empty;

            if (mgColor.IsTransparent && checkTransparent)
            {
                color = Color.Transparent;
            }
            else if (mgColor.IsSystemColor)
            {
                switch (mgColor.SystemColor)
                {
                case MagicSystemColor.ScrollBar:
                    color = SystemColors.ScrollBar;
                    break;

                case MagicSystemColor.Background:
                    color = SystemColors.Desktop;
                    break;

                case MagicSystemColor.ActiveCaption:
                    color = SystemColors.ActiveCaption;
                    break;

                case MagicSystemColor.InactiveCaption:
                    color = SystemColors.InactiveCaption;
                    break;

                case MagicSystemColor.Menu:
                    color = SystemColors.Menu;
                    break;

                case MagicSystemColor.Window:
                    color = SystemColors.Window;
                    break;

                case MagicSystemColor.WindowFrame:
                    color = SystemColors.WindowFrame;
                    break;

                case MagicSystemColor.MenuText:
                    color = SystemColors.MenuText;
                    break;

                case MagicSystemColor.WindowText:
                    color = SystemColors.WindowText;
                    break;

                case MagicSystemColor.CaptionText:
                    color = SystemColors.ActiveCaptionText;
                    break;

                case MagicSystemColor.ActiveBorder:
                    color = SystemColors.ActiveBorder;
                    break;

                case MagicSystemColor.InActiveBorder:
                    color = SystemColors.InactiveBorder;
                    break;

                case MagicSystemColor.AppWorkSpace:
                    color = SystemColors.AppWorkspace;
                    break;

                case MagicSystemColor.Highlight:
                    color = SystemColors.Highlight;
                    break;

                case MagicSystemColor.HighlightText:
                    color = SystemColors.HighlightText;
                    break;

                case MagicSystemColor.BtnFace:
                    color = SystemColors.Control;           //SystemColors.ButtonFace -> in CF we don't have it, use its equivalent.
                    break;

                case MagicSystemColor.BtnShadow:
                    color = SystemColors.ControlDark;       //SystemColors.ButtonShadow
                    break;

                case MagicSystemColor.BtnHighlight:
                    color = SystemColors.ControlLightLight; //SystemColors.ButtonHighlight
                    break;

                case MagicSystemColor.GrayText:
                    color = SystemColors.GrayText;
                    break;

                case MagicSystemColor.BtnText:
                    color = SystemColors.ControlText;
                    break;

                case MagicSystemColor.InActiveCaptionText:
                    color = SystemColors.InactiveCaptionText;
                    break;

                case MagicSystemColor.ThreeDDarkShadow:
                    color = SystemColors.ControlDarkDark;
                    break;

                case MagicSystemColor.ThreeDLight:
                    color = SystemColors.ControlLight;
                    break;

                case MagicSystemColor.InfoText:
                    color = SystemColors.InfoText;
                    break;

                case MagicSystemColor.Info:
                    color = SystemColors.Info;
                    break;

                default:
                    color = Color.Black;
                    break;
                }
            }
#if !PocketPC
            else if (useAlpha)
            {
                color = Color.FromArgb(mgColor.Alpha, mgColor.Red, mgColor.Green, mgColor.Blue);
            }
#endif
            else
            {
                color = Color.FromArgb(mgColor.Red, mgColor.Green, mgColor.Blue);
            }

            return(color);
        }
示例#19
0
    //----------------------------------------------------------------------------------------
    // �� �ܣ� ����ͼ���Ϊͼ���ļ�
    //
    // �� �ߣ�
    //
    //
    // �� �ڣ�2007.05.#
    //
    //-----------------------------------------------------------------------------------------
    public bool GenerateMapImage()
    {
        // ��ȡ��Դ�������Ⱦ�������
        MgResourceService resourceService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService);
        MgRenderingService renderingService = (MgRenderingService)siteConnection.CreateService(MgServiceType.RenderingService);
        //  �򿪵�ͼ
        MgMap map = new MgMap();
        map.Open(resourceService, "Sheboygan");

        //  ����ѡ��
        MgSelection selection = new MgSelection(map);
        selection.Open(resourceService, "Sheboygan");
        // ָ����Χ
        MgEnvelope extent = map.GetMapExtent();
        double x = 0.5*extent.GetLowerLeftCoordinate().GetX();
        double y = 0.5*extent.GetLowerLeftCoordinate().GetY() ;

        MgColor color = new MgColor("FFFFBF20");
        // ���ɲ�����ͼ���ļ�
        MgByteReader byteReader = renderingService.RenderMap(map, selection, extent, 450, 613, color, "PNG");
        MgByteSink byteSink = new MgByteSink(byteReader);
        string filePath = "C:\\Temp\\Map.PNG";
        byteSink.ToFile(filePath);
        return true;
    }
示例#20
0
 public MgViewerRenderingOptions(string format, int behavior, MgColor color)
 {
     this.Format   = format;
     this.Behavior = behavior;
     this.Color    = color;
 }