示例#1
0
        /// <summary>
        /// Deserializes X-Road message response or throws <see>XRoadFaultException</see> when
        /// X-Road fault is parsed from the message instead of expected result value.
        /// </summary>
        public static object DeserializeMessageContent(this XRoadMessage message, IServiceMap serviceMap, IMessageFormatter messageFormatter)
        {
            if (serviceMap.ResponseDefinition.ContainsNonTechnicalFault)
            {
                ThrowIfXRoadFault(message, serviceMap, messageFormatter);
            }

            message.ContentStream.Position = 0;
            using (var reader = XmlReader.Create(message.ContentStream))
            {
                messageFormatter.MoveToBody(reader);

                if (!reader.MoveToElement(2))
                {
                    throw new InvalidQueryException("No payload element in SOAP message.");
                }

                messageFormatter.ThrowSoapFaultIfPresent(reader);

                var result = serviceMap.DeserializeResponse(reader, message);

                return(result is XRoadFault fault ? throw new XRoadFaultException(fault) : result);
            }
        }
示例#2
0
        public static int GetClassID(IServiceMap map, IClass Class)
        {
            List <IDatasetElement> elements = map.MapElements;

            foreach (IDatasetElement element in map.MapElements)
            {
                if (element != null && element.Class == Class)
                {
                    return(element.ID);
                }
                if (element is IWebServiceLayer && ((IWebServiceLayer)element).WebServiceClass != null)
                {
                    foreach (IWebServiceTheme theme in ((IWebServiceLayer)element).WebServiceClass.Themes)
                    {
                        if (theme != null && theme.Class == Class)
                        {
                            return(theme.ID);
                        }
                    }
                }
            }

            return(-1);
        }
示例#3
0
        public static Layers FindMapLayers(IServiceMap map, bool useTOC, string id, List <ILayer> clonedLayers)
        {
            if (useTOC)
            {
                return(FindMapLayersFromTOC(map, id, clonedLayers));
            }

            foreach (IDatasetElement element in map.MapElements)
            {
                if (!(element is ILayer))
                {
                    continue;
                }
                ILayer layer = element as ILayer;

                if (layer.SID == id)
                {
                    return(new Layers(GetLayerByID(clonedLayers, layer.ID)));
                }
                if (element.Class is IWebServiceClass)
                {
                    foreach (IWebServiceTheme theme in ((IWebServiceClass)element.Class).Themes)
                    {
                        if (!(theme is ILayer))
                        {
                            continue;
                        }
                        if (theme.SID == id)
                        {
                            return(new Layers(GetLayerByID(clonedLayers, theme.ID)));
                        }
                    }
                }
            }
            return(new Layers());
        }
示例#4
0
        private void GetCompactTile(IServiceRequestContext context, TileServiceMetadata metadata, int epsg, double scale, int row, int col, string format, GridOrientation orientation, BoundingTiles boundingTiles, bool renderOnTheFly)
        {
            if (!metadata.EPSGCodes.Contains(epsg))
            {
                throw new ArgumentException("Wrong epsg argument");
            }

            if (orientation != GridOrientation.UpperLeft)
            {
                throw new ArgumentException("Compact Tiles Orientation must bei Upper Left!");
            }

            scale = metadata.Scales.GetScale(scale);
            if (scale <= 0.0)
            {
                throw new ArgumentException("Wrong scale argument");
            }

            //IEnvelope bounds = metadata.GetEGPSEnvelope(epsg);
            //if (bounds == null || bounds.Width == 0.0 || bounds.Height == 0.0)
            //    throw new Exception("No bounds defined for EPSG:" + epsg);
            IPoint origin = metadata.GetOriginUpperLeft(epsg);

            if (origin == null)
            {
                throw new Exception("No origin defined for EPSG:" + epsg);
            }

            format = format.ToLower();
            if (format != ".png" && format != ".jpg")
            {
                throw new Exception("Unsupported image format");
            }
            if (format == ".png" && metadata.FormatPng == false)
            {
                throw new Exception("Format image/png not supported");
            }
            if (format == ".jpg" && metadata.FormatJpg == false)
            {
                throw new Exception("Format image/jpeg no supported");
            }

            string path = _mapServer.TileCachePath + @"\" + context.ServiceMap.Name + @"\_alllayers\compact\" +
                          TileServiceMetadata.ScalePath(orientation, epsg, scale);

            string compactTileName = CompactTileName(row, col);

            string bundleFilename     = path + @"\" + compactTileName + ".tilebundle";
            string bundleDoneFilename = path + @"\" + compactTileName + ".tilebundle.done";
            string bundleCalcFilename = path + @"\" + compactTileName + ".tilebundle.calc";

            if (new FileInfo(bundleFilename).Exists)
            {
                GetCompactTileBytes(context, path, row, col);
                return;
            }
            else if (!renderOnTheFly || new FileInfo(bundleDoneFilename).Exists || new FileInfo(bundleCalcFilename).Exists /* && !metadata.RenderTilesOnTheFly*/)
            {
                return; // Empty
            }

            DirectoryInfo di = new DirectoryInfo(path);

            if (!di.Exists)
            {
                di.Create();
            }

            try { File.Delete(bundleFilename); }
            catch { }

            //temp
            //string pathTemp = path + @"\temp";
            //DirectoryInfo diTemp = new DirectoryInfo(pathTemp);
            //if (!diTemp.Exists)
            //    diTemp.Create();

            File.WriteAllText(bundleCalcFilename, "calc...");
            CompactTilesIndexBuilder indexBuilder = new CompactTilesIndexBuilder();

            int startRow = CompactTileStart(row), startCol = CompactTileStart(col);

            ISpatialReference sRef = SpatialReference.FromID("epsg:" + epsg);

            using (IServiceMap map = context.ServiceMap)
            {
                map.Display.SpatialReference = sRef;
                map.Display.dpi = metadata.Dpi;

                double res = (double)scale / (metadata.Dpi / 0.0254);
                if (map.Display.MapUnits != GeoUnits.Meters)
                {
                    GeoUnitConverter converter = new GeoUnitConverter();
                    res = converter.Convert(res, GeoUnits.Meters, map.Display.MapUnits);
                }


                string bundleTempFilename  = path + @"\" + compactTileName + "." + Guid.NewGuid().ToString("N").ToLower() + ".tilebundle";
                string bundleIndexFilename = path + @"\" + compactTileName + ".tilebundlx";

                File.WriteAllBytes(bundleTempFilename, new byte[0]);
                int bundlePos = 0;

                int tileMatrixWidth = 8, tileMatrixHeight = 8;

                map.Display.iWidth  = metadata.TileWidth * tileMatrixWidth;
                map.Display.iHeight = metadata.TileHeight * tileMatrixHeight;

                for (int r = 0; r < 128; r += 8)
                {
                    File.WriteAllText(bundleCalcFilename, "calc...row" + r);
                    for (int c = 0; c < 128; c += 8)
                    {
                        int currentRow = r + startRow, currentCol = c + startCol;

                        if (boundingTiles != null)
                        {
                            if (!boundingTiles.Check(currentRow, currentCol, 8, 8))
                            {
                                continue;
                            }
                        }

                        double H = metadata.TileHeight * res;
                        double y = origin.Y - H * (currentRow + tileMatrixHeight);

                        double W = metadata.TileWidth * res;
                        double x = origin.X + W * currentCol;

                        map.Display.ZoomTo(new Envelope(x, y, x + W * tileMatrixWidth, y + H * tileMatrixHeight));
                        if (format != ".jpg") // Make PNG Transparent
                        {
                            map.Display.BackgroundColor = System.Drawing.Color.Transparent;
                        }

                        map.ReleaseImage();  // Delete old Image !!! Because there is no map.SaveImage()!!!!
                        map.Render();

                        if (IsEmptyBitmap(map.MapImage, map.Display.BackgroundColor))
                        {
                            continue;
                        }

                        // Temp
                        //map.MapImage.Save(pathTemp + @"\matrix_" + (startRow + r) + "_" + (startCol + c) + ".png", ImageFormat.Png);

                        for (int j = 0; j < tileMatrixHeight; j++)
                        {
                            for (int i = 0; i < tileMatrixWidth; i++)
                            {
                                int tileRow = currentRow + j, tileCol = currentCol + i;

                                if (boundingTiles != null)
                                {
                                    if (!boundingTiles.Check(tileRow, tileCol, 8, 8))
                                    {
                                        continue;
                                    }
                                }

                                using (Bitmap bm = new Bitmap(metadata.TileWidth, metadata.TileHeight, map.MapImage.PixelFormat))
                                    using (Graphics gr = Graphics.FromImage(bm))
                                    {
                                        gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
                                        gr.DrawImage(map.MapImage,
                                                     new RectangleF(0f, 0f, (float)bm.Width, (float)bm.Height),
                                                     new RectangleF(-0.5f + (float)(i * metadata.TileWidth), -0.5f + (float)(j * metadata.TileHeight), (float)metadata.TileWidth, (float)metadata.TileHeight), GraphicsUnit.Pixel);

                                        //for (int py = 0, to_py = bm.Height; py < to_py; py++)
                                        //{
                                        //    for (int px = 0, to_px = bm.Width; px < to_px; px++)
                                        //    {
                                        //        var pCol = map.MapImage.GetPixel(px + i * metadata.TileHeight, py + j * metadata.TileHeight);
                                        //        bm.SetPixel(px, py, pCol);
                                        //    }
                                        //}

                                        if (IsEmptyBitmap(bm, map.Display.BackgroundColor))
                                        {
                                            continue;
                                        }

                                        // Temp
                                        //bm.Save(pathTemp + @"\tile_" + tileRow + "_" + tileCol + ".png", ImageFormat.Png);

                                        //try
                                        //{
                                        //    if (format != ".jpg" && map.Display.BackgroundColor.A > 0)   // Make PNG Transparent
                                        //        bm.MakeTransparent(map.Display.BackgroundColor);
                                        //}
                                        //catch { }

                                        MemoryStream ms = new MemoryStream();
                                        bm.Save(ms, format == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png);


                                        byte[] imageBytes = ms.ToArray();
                                        using (var stream = new FileStream(bundleTempFilename, FileMode.Append))
                                        {
                                            stream.Write(imageBytes, 0, imageBytes.Length);
                                        }

                                        indexBuilder.SetValue(r + j, c + i, bundlePos, imageBytes.Length);

                                        bundlePos += imageBytes.Length;
                                    }
                            }
                        }
                    }

                    map.ReleaseImage();
                    GC.Collect();
                }

                try { File.Delete(bundleFilename); }
                catch { }
                if (bundlePos == 0)
                {
                    File.Delete(bundleTempFilename);
                    File.WriteAllText(bundleDoneFilename, "");
                }
                else
                {
                    File.Move(bundleTempFilename, bundleFilename);
                    indexBuilder.Save(bundleIndexFilename);
                }
                try { File.Delete(bundleCalcFilename); }
                catch { }
            }
            GC.Collect();
        }
示例#5
0
        private void GetTile(IServiceRequestContext context, TileServiceMetadata metadata, int epsg, double scale, int row, int col, string format, GridOrientation orientation, bool renderOnTheFly)
        {
            if (!metadata.EPSGCodes.Contains(epsg))
            {
                throw new ArgumentException("Wrong epsg argument");
            }

            //if (!metadata.Scales.Contains(scale))
            //    throw new ArgumentException("Wrong scale argument");
            scale = metadata.Scales.GetScale(scale);
            if (scale <= 0.0)
            {
                throw new ArgumentException("Wrong scale argument");
            }

            //IEnvelope bounds = metadata.GetEPSGEnvelope(epsg);
            //if (bounds == null || bounds.Width == 0.0 || bounds.Height == 0.0)
            //    throw new Exception("No bounds defined for EPSG:" + epsg);

            format = format.ToLower();
            if (format != ".png" && format != ".jpg")
            {
                throw new Exception("Unsupported image format");
            }
            if (format == ".png" && metadata.FormatPng == false)
            {
                throw new Exception("Format image/png not supported");
            }
            if (format == ".jpg" && metadata.FormatJpg == false)
            {
                throw new Exception("Format image/jpeg no supported");
            }

            string path = _mapServer.TileCachePath + @"\" + context.ServiceMap.Name + @"\_alllayers\" +
                          TileServiceMetadata.TilePath(orientation, epsg, scale, row, col) + format;

            if ((orientation == GridOrientation.UpperLeft && metadata.UpperLeftCacheTiles) ||
                (orientation == GridOrientation.LowerLeft && metadata.LowerLeftCacheTiles))
            {
                FileInfo fi = new FileInfo(path);
                if (fi.Exists)
                {
                    context.ServiceRequest.Response = fi.FullName;
                    return;
                }
                else if (!renderOnTheFly && !metadata.RenderTilesOnTheFly)
                {
                    return;  // Empty
                }
                if (!fi.Directory.Exists)
                {
                    fi.Directory.Create();
                }
            }
            else
            {
                path = _mapServer.OutputPath + @"\tile_" + Guid.NewGuid().ToString("N").ToLower() + format;
            }

            ISpatialReference sRef = SpatialReference.FromID("epsg:" + epsg);

            using (IServiceMap map = context.ServiceMap)
            {
                map.Display.SpatialReference = sRef;
                map.Display.dpi = metadata.Dpi;

                map.Display.iWidth  = metadata.TileWidth;
                map.Display.iHeight = metadata.TileHeight;

                double res = (double)scale / (metadata.Dpi / 0.0254);
                if (map.Display.MapUnits != GeoUnits.Meters)
                {
                    GeoUnitConverter converter = new GeoUnitConverter();
                    res = converter.Convert(res, GeoUnits.Meters, map.Display.MapUnits);
                }

                var origin = orientation == GridOrientation.UpperLeft ? metadata.GetOriginUpperLeft(epsg) : metadata.GetOriginLowerLeft(epsg);

                double H = metadata.TileHeight * res;
                double y = (orientation == GridOrientation.UpperLeft ?
                            origin.Y - H * (row + 1) :
                            origin.Y + H * row);

                double W = metadata.TileWidth * res;
                //if (map.Display.MapUnits == GeoUnits.DecimalDegrees)
                //{
                //    double phi = (2 * y + H) / 2.0;
                //    W /= Math.Cos(phi / 180.0 * Math.PI);
                //}
                double x = origin.X + W * col;

                map.Display.ZoomTo(new Envelope(x, y, x + W, y + H));
                map.Render();

                bool maketrans = map.Display.MakeTransparent;
                map.Display.MakeTransparent = true;
                map.SaveImage(path, format == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png);
                map.Display.MakeTransparent = maketrans;

                context.ServiceRequest.Response = path;
                _mapServer.Log("CreateTile:", loggingMethod.request_detail, path);
            }
        }
示例#6
0
        private byte[] GetCompactTile(IServiceRequestContext context, TileServiceMetadata metadata, int epsg, double scale, int row, int col, string format, GridOrientation orientation)
        {
            if (!metadata.EPSGCodes.Contains(epsg))
            {
                throw new ArgumentException("Wrong epsg argument");
            }

            if (orientation != GridOrientation.UpperLeft)
            {
                throw new ArgumentException("Compact Tiles Orientation must bei Upper Left!");
            }

            scale = metadata.Scales.GetScale(scale);
            if (scale <= 0.0)
            {
                throw new ArgumentException("Wrong scale argument");
            }

            //IEnvelope bounds = metadata.GetEGPSEnvelope(epsg);
            //if (bounds == null || bounds.Width == 0.0 || bounds.Height == 0.0)
            //    throw new Exception("No bounds defined for EPSG:" + epsg);
            IPoint origin = metadata.GetOriginUpperLeft(epsg);

            if (origin == null)
            {
                throw new Exception("No origin defined for EPSG:" + epsg);
            }

            format = format.ToLower();
            if (format != ".png" && format != ".jpg")
            {
                throw new Exception("Unsupported image format");
            }
            if (format == ".png" && metadata.FormatPng == false)
            {
                throw new Exception("Format image/png not supported");
            }
            if (format == ".jpg" && metadata.FormatJpg == false)
            {
                throw new Exception("Format image/jpeg no supported");
            }

            string path = _mapServer.TileCachePath + @"\" + context.ServiceMap.Name + @"\_alllayers\compact\" +
                          TileServiceMetadata.ScalePath(orientation, epsg, scale);

            string compactTileName = CompactTileName(row, col);

            string bundleFilename     = path + @"\" + compactTileName + ".tilebundle";
            string bundleDoneFilename = path + @"\" + compactTileName + ".tilebundle.done";
            string bundleCalcFilename = path + @"\" + compactTileName + ".tilebundle.calc";

            if (new FileInfo(bundleFilename).Exists)
            {
                return(GetCompactTileBytes(context, path, row, col, format));
            }



            if (IsDirectoryEmpty(path))
            {
                #region On The Fly

                using (IServiceMap map = context.ServiceMap)
                {
                    ISpatialReference sRef = SpatialReference.FromID("epsg:" + epsg);

                    map.Display.SpatialReference = sRef;
                    map.Display.dpi = metadata.Dpi;

                    map.Display.iWidth  = metadata.TileWidth;
                    map.Display.iHeight = metadata.TileHeight;

                    double res = (double)scale / (metadata.Dpi / 0.0254);
                    if (map.Display.MapUnits != GeoUnits.Meters)
                    {
                        GeoUnitConverter converter = new GeoUnitConverter();
                        res = converter.Convert(res, GeoUnits.Meters, map.Display.MapUnits);
                    }

                    origin = orientation == GridOrientation.UpperLeft ? metadata.GetOriginUpperLeft(epsg) : metadata.GetOriginLowerLeft(epsg);

                    double H = metadata.TileHeight * res;
                    double y = (orientation == GridOrientation.UpperLeft ?
                                origin.Y - H * (row + 1) :
                                origin.Y + H * row);

                    double W = metadata.TileWidth * res;
                    double x = origin.X + W * col;

                    map.Display.ZoomTo(new Envelope(x, y, x + W, y + H));
                    map.Render();

                    bool maketrans = map.Display.MakeTransparent;
                    map.Display.MakeTransparent = true;
                    MemoryStream ms = new MemoryStream();
                    map.SaveImage(ms, format == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png);
                    map.Display.MakeTransparent = maketrans;

                    return(ms.ToArray());
                }

                #endregion

                #region Tile from Existing UpLevel Tiles (Vorteil Resampling wird nicht von Browser erledigt, ist meistens Fast -> hier Nearstneigbor)

                int level2 = metadata.Scales.IndexOf(scale);
                if (level2 <= 0)
                {
                    return(null);
                }

                using (IServiceMap map = context.ServiceMap)
                {
                    double res = (double)scale / (metadata.Dpi / 0.0254);
                    if (map.Display.MapUnits != GeoUnits.Meters)
                    {
                        GeoUnitConverter converter = new GeoUnitConverter();
                        res = converter.Convert(res, GeoUnits.Meters, map.Display.MapUnits);
                    }

                    double H = metadata.TileHeight * res;
                    double y = origin.Y - H * (row + 1);

                    double W = metadata.TileWidth * res;
                    double x = origin.X + W * col;

                    while (true)
                    {
                        if (level2 <= 0)
                        {
                            break;
                        }

                        double scale2 = metadata.Scales[level2 - 1];

                        string path2 = _mapServer.TileCachePath + @"\" + context.ServiceMap.Name + @"\_alllayers\compact\" +
                                       TileServiceMetadata.ScalePath(orientation, epsg, scale2);
                        if (IsDirectoryEmpty(path2))
                        {
                            level2--;
                            continue;
                        }


                        double res2 = scale2 / (metadata.Dpi / 0.0254);

                        double W2 = metadata.TileWidth * res2;
                        double H2 = metadata.TileHeight * res2;

                        int col2_0 = (int)Math.Floor((x - origin.X) / W2);
                        int row2_0 = (int)Math.Floor((origin.Y - (y + H)) / H2);

                        int col2_1 = (int)Math.Floor((x + W - origin.X) / W2);
                        int row2_1 = (int)Math.Floor((origin.Y - y) / H2);

                        double x2_0 = origin.X + W2 * col2_0,
                               y2_0 = origin.Y - H2 * (row2_1 + 1);

                        double W20 = Math.Abs(col2_1 - col2_0 + 1) * W2,
                               H20 = Math.Abs(row2_1 - row2_0 + 1) * H2;

                        using (Bitmap bm = new Bitmap(Math.Abs(col2_1 - col2_0 + 1) * metadata.TileWidth, Math.Abs(row2_1 - row2_0 + 1) * metadata.TileHeight))
                            using (Graphics gr = Graphics.FromImage(bm))
                            {
                                for (int r2 = row2_0; r2 <= row2_1; r2++)
                                {
                                    for (int c2 = col2_0; c2 <= col2_1; c2++)
                                    {
                                        byte[] buffer = GetCompactTileBytes(context, path2, r2, c2, format);
                                        if (buffer != null && buffer.Length > 0)
                                        {
                                            MemoryStream ms        = new MemoryStream(buffer);
                                            var          tileImage = Image.FromStream(ms);
                                            gr.DrawImage(tileImage, new PointF((c2 - col2_0) * metadata.TileWidth, (r2 - row2_0) * metadata.TileHeight));
                                        }
                                    }
                                }

                                float imageX = (float)((x - x2_0) / W20 * (double)bm.Width);
                                float imageY = bm.Height - (float)((y - y2_0) / H20 * (double)bm.Height);

                                float imageW = (float)((double)metadata.TileWidth * res / res2);
                                float imageH = (float)((double)metadata.TileHeight * res / res2);

                                using (Bitmap outputBm = new Bitmap(metadata.TileWidth, metadata.TileHeight))
                                    using (Graphics outputGr = Graphics.FromImage(outputBm))
                                    {
                                        outputGr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;

                                        outputGr.DrawImage(bm,
                                                           new RectangleF(-.5f, -.5f, (float)outputBm.Width + 1f, (float)outputBm.Height + 1f),
                                                           new RectangleF(imageX, imageY - imageH, imageW, imageH),
                                                           GraphicsUnit.Pixel);


                                        MemoryStream output = new MemoryStream();
                                        outputBm.Save(output, format == ".png" ? ImageFormat.Png : ImageFormat.Jpeg);

                                        return(output.ToArray());
                                    }
                            }
                    }
                }

                #endregion
            }


            return(null);
        }
示例#7
0
        internal static void LoadConfig()
        {
            try
            {
                if (mapDocument == null)
                {
                    return;
                }

                DirectoryInfo di = new DirectoryInfo(ServicesPath);
                if (!di.Exists)
                {
                    di.Create();
                }

                acl = new Acl(new FileInfo(ServicesPath + @"\acl.xml"));

                foreach (FileInfo fi in di.GetFiles("*.mxl"))
                {
                    try
                    {
                        if (mapServices.Count < mapServer.MaxServices)
                        {
                            MapService service = new MapService(fi.FullName, MapServiceType.MXL);
                            mapServices.Add(service);
                            Console.WriteLine("service " + service.Name + " added");
                        }
                    }
                    catch (Exception ex)
                    {
                        if (Functions.log_errors)
                        {
                            Logger.Log(loggingMethod.error, "LoadConfig - " + fi.Name + ": " + ex.Message);
                        }
                    }
                }
                foreach (FileInfo fi in di.GetFiles("*.svc"))
                {
                    try
                    {
                        if (mapServices.Count < mapServer.MaxServices)
                        {
                            MapService service = new MapService(fi.FullName, MapServiceType.SVC);
                            mapServices.Add(service);
                            Console.WriteLine("service " + service.Name + " added");
                        }
                    }
                    catch (Exception ex)
                    {
                        if (Functions.log_errors)
                        {
                            Logger.Log(loggingMethod.error, "LoadConfig - " + fi.Name + ": " + ex.Message);
                        }
                    }
                }

                try
                {
                    // Config Datei laden...
                    FileInfo fi = new FileInfo(ServicesPath + @"\config.xml");
                    if (fi.Exists)
                    {
                        XmlDocument doc = new XmlDocument();
                        doc.Load(fi.FullName);

                        #region onstart - alias
                        foreach (XmlNode serviceNode in doc.SelectNodes("MapServer/onstart/alias/services/service[@alias]"))
                        {
                            string     serviceName = serviceNode.InnerText;
                            MapService ms          = new MapServiceAlias(
                                serviceNode.Attributes["alias"].Value,
                                serviceName.Contains(",") ? MapServiceType.GDI : MapServiceType.SVC,
                                serviceName);
                            mapServices.Add(ms);
                        }
                        #endregion

                        #region onstart - load

                        foreach (XmlNode serviceNode in doc.SelectNodes("MapServer/onstart/load/services/service"))
                        {
                            ServiceRequest serviceRequest = new ServiceRequest(
                                serviceNode.InnerText, String.Empty);

                            ServiceRequestContext context = new ServiceRequestContext(
                                mapServer,
                                null,
                                serviceRequest);

                            IServiceMap sm = mapServer[context];

                            /*
                             * // Initalisierung...?!
                             * sm.Display.iWidth = sm.Display.iHeight = 50;
                             * IEnvelope env = null;
                             * foreach (IDatasetElement dsElement in sm.MapElements)
                             * {
                             *  if (dsElement != null && dsElement.Class is IFeatureClass)
                             *  {
                             *      if (env == null)
                             *          env = new Envelope(((IFeatureClass)dsElement.Class).Envelope);
                             *      else
                             *          env.Union(((IFeatureClass)dsElement.Class).Envelope);
                             *  }
                             * }
                             * sm.Display.ZoomTo(env);
                             * sm.Render();
                             * */
                        }
                        #endregion

                        Console.WriteLine("config.xml loaded...");
                    }
                }
                catch (Exception ex)
                {
                    if (Functions.log_errors)
                    {
                        Logger.Log(loggingMethod.error, "LoadConfig - config.xml: " + ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                if (Functions.log_errors)
                {
                    Logger.Log(loggingMethod.error, "LoadConfig: " + ex.Message);
                }
            }
        }
示例#8
0
        public void Request(IServiceRequestContext context)
        {
            if (context == null || context.ServiceRequest == null)
            {
                return;
            }

            if (_mapServer == null)
            {
                return;
            }

            MiscParameterDescriptor parameters = new MiscParameterDescriptor();

            if (!parameters.ParseParameters(context.ServiceRequest.Request.Split('&')))
            {
                _mapServer.Log("Invalid Parameters", loggingMethod.error, context.ServiceRequest.Request);
                return;
            }

            using (IServiceMap map = context.ServiceMap) // _mapServer[context];
            {
                if (map == null)
                {
                    _mapServer.Log("Invalid Map", loggingMethod.error, context.ServiceRequest.Request);
                    return;
                }

                QueryFilter filter = parameters.BBOX != null ? new SpatialFilter() : new QueryFilter();
                filter.SubFields = "*";
                if (parameters.BBOX != null)
                {
                    ((SpatialFilter)filter).Geometry = parameters.BBOX;
                }
                ISpatialReference sRef = SpatialReference.FromID("epsg:4326");
                filter.FeatureSpatialReference = sRef;
                if (filter is SpatialFilter)
                {
                    ((SpatialFilter)filter).FilterSpatialReference = sRef;
                }

                // Get Layers
                List <ILayer> queryLayers = new List <ILayer>();
                foreach (string l in parameters.LAYERS)
                {
                    if (l == String.Empty || l[0] != 'c')
                    {
                        continue;
                    }

                    MapServerHelper.Layers layers = MapServerHelper.FindMapLayers(map, _useTOC, l.Substring(1, l.Length - 1));
                    if (layers == null)
                    {
                        continue;
                    }

                    foreach (ILayer layer in layers)
                    {
                        queryLayers.Add(layer);
                    }
                }

                StringBuilder sb = new StringBuilder();
                foreach (ILayer layer in queryLayers)
                {
                    if (layer is IFeatureLayer && ((IFeatureLayer)layer).FeatureClass != null)
                    {
                        using (IFeatureCursor cursor = ((IFeatureLayer)layer).FeatureClass.Search(filter) as IFeatureCursor)
                        {
                            Stream stream = gView.Framework.OGC.KML.KML.ToKml(cursor, 1000);
                            stream.Position = 0;
                            byte[] bytes = new byte[(int)stream.Length];
                            stream.Read(bytes, 0, bytes.Length);
                            sb.Append(Encoding.UTF8.GetString(bytes));
                        }
                    }
                }

                context.ServiceRequest.Response = sb.ToString();
            }
        }
示例#9
0
        public static bool ModifyFilter(IServiceMap map, ITableClass tClass, IQueryFilter filter)
        {
            if (filter == null || tClass == null)
            {
                return(false);
            }
            string subFields = filter.SubFields;

            if (subFields != "*")
            {
                filter.SubFields = String.Empty;
                foreach (string subField in subFields.Split(' '))
                {
                    string fname = subField;
                    if (subFields.StartsWith(filter.fieldPrefix) &&
                        subFields.EndsWith(filter.fieldPostfix))
                    {
                        fname = fname.Substring(filter.fieldPrefix.Length, fname.Length - filter.fieldPrefix.Length - filter.fieldPostfix.Length);
                    }

                    if (tClass.Fields != null)
                    {
                        if (tClass.FindField(fname) != null ||
                            (tClass is IFeatureClass && ((IFeatureClass)tClass).ShapeFieldName == fname))
                        {
                            filter.AddField(fname);
                        }
                    }
                }
            }

            try
            {
                XmlDocument xmlFilter = new XmlDocument();
                string      xml       = Xml.ToXml(tClass, filter);
                xmlFilter.LoadXml(xml);

                XmlNodeList propertyNames = xmlFilter.SelectNodes("//PropertyName");

                foreach (XmlNode propertyName in propertyNames)
                {
                    if (propertyName.InnerText == MergedObjectIDName)
                    {
                        XmlNode literal = propertyName.ParentNode.SelectSingleNode("Literal");
                        if (literal == null)
                        {
                            return(false);
                        }

                        long mergedID;
                        if (!long.TryParse(literal.InnerText, out mergedID))
                        {
                            return(false);
                        }
                        int classID = GetClassID(map, tClass), propertyClassID = GetClassID(mergedID);

                        if (classID != propertyClassID)
                        {
                            propertyName.ParentNode.ParentNode.RemoveChild(propertyName.ParentNode);
                            continue;
                        }
                        propertyName.InnerText = tClass.IDFieldName;
                        literal.InnerText      = GetObjectID(mergedID).ToString();
                    }
                    else if (tClass.Fields.FindField(propertyName.InnerText) == null)
                    {
                        propertyName.ParentNode.ParentNode.RemoveChild(
                            propertyName.ParentNode);
                    }
                }

                // keine Properties übgrig geblieben sind -> nicht abfraten...
                if (propertyNames.Count > 0 && xmlFilter.SelectNodes("//PropertyName").Count == 0)
                {
                    return(false);
                }
                IQueryFilter f = Xml.FromXml(tClass, xmlFilter.SelectSingleNode("Filter"));

                // Prüfen, ob vom Filter noch was übrig bleibt...
                if (!String.IsNullOrEmpty(filter.WhereClause) &&
                    String.IsNullOrEmpty(f.WhereClause))
                {
                    return(false);
                }

                filter.WhereClause = f.WhereClause;
            }
            catch { return(false); }
            return(true);
        }
示例#10
0
        public static List <Layers> MapLayers(IServiceMap map, bool useTOC)
        {
            if (useTOC)
            {
                return(MapLayersFromTOC(map));
            }

            List <Layers> layersList = new List <Layers>();

            foreach (IDatasetElement element in map.MapElements)
            {
                if (!(element is ILayer))
                {
                    continue;
                }
                ILayer layer = element as ILayer;

                if (layer.Class is IWebServiceClass)
                {
                    foreach (IWebServiceTheme theme in ((IWebServiceClass)layer.Class).Themes)
                    {
                        if (!(theme is ILayer))
                        {
                            continue;
                        }

                        string title = layer.Title;
                        string group = String.Empty;
                        if (map.TOC != null)
                        {
                            //ITOCElement tocElement = map.TOC.GetTOCElement(theme.Class);
                            // Besser layer als layer.Class verwendenden, weil Class von mehrerenen Layern
                            // verwendet werden kann zB bei gesplitteten Layern...
                            ITOCElement tocElement = map.TOC.GetTOCElement((ILayer)theme);
                            if (tocElement != null)
                            {
                                title = tocElement.Name;
                                group = ParentGroupName(tocElement);
                            }
                        }
                        if (!String.IsNullOrEmpty(layer.Namespace))
                        {
                            title = layer.Namespace + ":" + title;
                        }

                        layersList.Add(new Layers(theme));
                        layersList[layersList.Count - 1].Title     = title;
                        layersList[layersList.Count - 1].GroupName = group;
                    }
                }
                else
                {
                    string title = layer.Title;
                    string group = String.Empty;
                    if (map.TOC != null)
                    {
                        //ITOCElement tocElement = map.TOC.GetTOCElement(layer.Class);
                        // Besser layer als layer.Class verwendenden, weil Class von mehrerenen Layern
                        // verwendet werden kann zB bei gesplitteten Layern...
                        ITOCElement tocElement = map.TOC.GetTOCElement(layer);
                        if (tocElement != null)
                        {
                            title = tocElement.Name;
                            group = ParentGroupName(tocElement);
                        }
                    }
                    if (!String.IsNullOrEmpty(layer.Namespace))
                    {
                        title = layer.Namespace + ":" + title;
                    }

                    layersList.Add(new Layers(layer));
                    layersList[layersList.Count - 1].Title     = title;
                    layersList[layersList.Count - 1].GroupName = group;
                }
            }
            return(layersList);
        }
示例#11
0
        private void GetCompactTileBytes(IServiceRequestContext context, IServiceMap serviceMap, string path, int row, int col)
        {
            string compactTileName = CompactTileName(row, col);

            string bundleFilename      = path + @"\" + compactTileName + ".tilebundle";
            string bundleIndexFilename = path + @"\" + compactTileName + ".tilebundlx";

            FileInfo fi = new FileInfo(bundleIndexFilename);

            if (!fi.Exists)
            {
                return;
            }

            CompactTileIndex bundleIndex = new CompactTileIndex(bundleIndexFilename);

            int bundleStartRow = CompactTileStart(row);
            int bundleStartCol = CompactTileStart(col);

            try
            {
                int tileLength, tilePosition = bundleIndex.TilePosition(row - bundleStartRow, col - bundleStartCol, out tileLength);

                if (tilePosition < 0)
                {
                    return;
                }

                using (FileStream fs = File.Open(bundleFilename, FileMode.Open, FileAccess.Read, FileShare.Read)) //new FileStream(bundleFilename, FileMode.Open, FileAccess.Read))
                {
                    fs.Position = tilePosition;

                    byte[] data = new byte[tileLength];
                    fs.Read(data, 0, tileLength);

                    context.ServiceRequest.Response = new MapServerResponse()
                    {
                        Data        = data,
                        ContentType = "image/jpg",
                        Expires     = DateTime.UtcNow.AddDays(7)
                    }.ToString();
                }
            }
            catch (Exception ex)
            {
                TileServiceMetadata metadata = serviceMap.MetadataProvider(_metaprovider) as TileServiceMetadata;
                using (var bitmap = Current.Engine.CreateBitmap(metadata.TileWidth, metadata.TileHeight))
                    using (var canvas = bitmap.CreateCanvas())
                        using (var font = Current.Engine.CreateFont("Arial", 9f))
                            using (var redBrush = Current.Engine.CreateSolidBrush(ArgbColor.Red))
                            {
                                canvas.DrawText(ex.Message, font, redBrush, new CanvasRectangleF(0f, 0f, (float)bitmap.Width, (float)bitmap.Height));
                                canvas.Flush();

                                MemoryStream ms = new MemoryStream();
                                bitmap.Save(ms, ImageFormat.Png);

                                context.ServiceRequest.Response = new MapServerResponse()
                                {
                                    Data        = ms.ToArray(),
                                    ContentType = "image/jpg"
                                }.ToString();
                            }
            }
        }
        private void PerformQueryTilesRequest(IServiceRequestContext context, XmlNode rType)
        {
            if (context == null || context.ServiceRequest == null)
            {
                _mapServer.Log("PerformQueryTilesRequest", loggingMethod.error, "no context or servicerequest");
                return;
            }

            ServiceRequest serviceRequest = context.ServiceRequest;

            _mapServer.Log("Service:" + serviceRequest.Service, loggingMethod.request, "TileService Request: QueryTiles");

            try
            {
                int level = 0;
                if (rType.Attributes["level"] != null)
                {
                    level = int.Parse(rType.Attributes["level"].Value);
                }

                IServiceMap map = _mapServer[context];
                if (map == null)
                {
                    serviceRequest.Response = CreateException("Service not found");
                    return;
                }

                #region QueryGeometry
                IGeometry queryGeometry = null;

                #region Envelope
                XmlNode envelopeNode = rType.SelectSingleNode("Envelope[@minx and @miny and @maxx and @maxy]");
                if (envelopeNode != null)
                {
                    Envelope queryEnvelope = new Envelope(
                        double.Parse(envelopeNode.Attributes["minx"].Value, _nhi),
                        double.Parse(envelopeNode.Attributes["miny"].Value, _nhi),
                        double.Parse(envelopeNode.Attributes["maxx"].Value, _nhi),
                        double.Parse(envelopeNode.Attributes["maxy"].Value, _nhi));
                    queryGeometry = queryEnvelope;
                }
                #endregion

                #region Polygon
                XmlNode polygonNode = rType.SelectSingleNode("Polygon");
                if (polygonNode != null)
                {
                    Polygon polygon = new Polygon();
                    foreach (XmlNode ringNode in polygonNode.SelectNodes("Ring"))
                    {
                        Ring ring = new Ring();
                        foreach (XmlNode pointNode in ringNode.SelectNodes("Point[@x and @y]"))
                        {
                            ring.AddPoint(new Point(double.Parse(pointNode.Attributes["x"].Value, _nhi),
                                                    double.Parse(pointNode.Attributes["y"].Value, _nhi)));
                        }
                        if (ring.PointCount > 2)
                        {
                            polygon.AddRing(ring);
                        }
                    }
                    if (polygon.RingCount == 0)
                    {
                        serviceRequest.Response = CreateException("Invalid Polygon definition node");
                        return;
                    }
                    queryGeometry = polygon;
                }
                #endregion

                if (queryGeometry == null)
                {
                    serviceRequest.Response = CreateException("No geometry (Envelope,Polygon) definition node");
                    return;
                }
                #endregion

                #region Layer/Featureclass
                XmlNode layerNode = rType.SelectSingleNode("Layer[@id]");
                if (layerNode == null)
                {
                    serviceRequest.Response = CreateException("No layer definition node");
                    return;
                }
                string id = layerNode.Attributes["id"].Value;
                MapServerHelper.Layers layers = MapServerHelper.FindMapLayers(map, true, id);
                if (layers.Count != 1)
                {
                    serviceRequest.Response = CreateException("Can't find layer with id='" + id + "'");
                    return;
                }
                IFeatureClass fc = layers[0].Class as IFeatureClass;
                if (fc == null || fc.FindField("GRID_LEVEL") == null ||
                    fc.FindField("GRID_ROW") == null ||
                    fc.FindField("GRID_COLUMN") == null ||
                    fc.FindField("FILE") == null)
                {
                    serviceRequest.Response = CreateException("Featureclass is not a tilegrid");
                    return;
                }
                #endregion

                #region Query
                SpatialFilter filter = new SpatialFilter();
                filter.AddField(fc.IDFieldName);
                filter.AddField(fc.ShapeFieldName);
                filter.AddField("GRID_LEVEL");
                filter.AddField("GRID_ROW");
                filter.AddField("GRID_COLUMN");
                filter.AddField("FILE");
                filter.Geometry    = queryGeometry;
                filter.WhereClause = "GRID_LEVEL=" + level;

                StringBuilder sb = new StringBuilder();
                sb.Append("<TileRequest><Tiles>");
                using (IFeatureCursor cursor = fc.GetFeatures(filter))
                {
                    IFeature feature;
                    while ((feature = cursor.NextFeature) != null)
                    {
                        sb.Append("<Tile");

                        #region Envelope
                        IEnvelope env = feature.Shape.Envelope;
                        sb.Append(" id='" + feature.OID + "'");
                        sb.Append(" minx='" + env.minx.ToString(_nhi) + "'");
                        sb.Append(" miny='" + env.miny.ToString(_nhi) + "'");
                        sb.Append(" maxx='" + env.maxx.ToString(_nhi) + "'");
                        sb.Append(" maxy='" + env.maxy.ToString(_nhi) + "'");
                        #endregion

                        #region File
                        FileInfo fi = new FileInfo(feature["FILE"].ToString());
                        sb.Append(" path='/" + feature["GRID_LEVEL"].ToString() + "/" + feature["GRID_ROW"].ToString() + "/" + feature["GRID_COLUMN"].ToString() + fi.Extension + "'");
                        #endregion
                        sb.Append(" />");
                    }
                }
                sb.Append("</Tiles></TileRequest>");
                #endregion

                serviceRequest.Response = sb.ToString();
            }
            catch (Exception ex)
            {
                _mapServer.Log("Service:" + serviceRequest.Service, loggingMethod.error, ex.Message + "\r\n" + ex.StackTrace);
                serviceRequest.Response = CreateException(ex.Message);
                return;
            }
        }
示例#13
0
        private byte[] GetCompactTile(IServiceRequestContext context, TileServiceMetadata metadata, int epsg, double scale, int row, int col, string format, GridOrientation orientation)
        {
            if (!metadata.EPSGCodes.Contains(epsg))
            {
                throw new ArgumentException("Wrong epsg argument");
            }

            if (orientation != GridOrientation.UpperLeft)
            {
                throw new ArgumentException("Compact Tiles Orientation must bei Upper Left!");
            }

            scale = metadata.Scales.GetScale(scale);
            if (scale <= 0.0)
            {
                throw new ArgumentException("Wrong scale argument");
            }

            //IEnvelope bounds = metadata.GetEGPSEnvelope(epsg);
            //if (bounds == null || bounds.Width == 0.0 || bounds.Height == 0.0)
            //    throw new Exception("No bounds defined for EPSG:" + epsg);
            IPoint origin = metadata.GetOriginUpperLeft(epsg);

            if (origin == null)
            {
                throw new Exception("No origin defined for EPSG:" + epsg);
            }

            format = format.ToLower();
            if (format != ".png" && format != ".jpg")
            {
                throw new Exception("Unsupported image format");
            }
            if (format == ".png" && metadata.FormatPng == false)
            {
                throw new Exception("Format image/png not supported");
            }
            if (format == ".jpg" && metadata.FormatJpg == false)
            {
                throw new Exception("Format image/jpeg no supported");
            }

            string path = _mapServer.TileCachePath + @"\" + MapName(context) + @"\_alllayers\compact\" +
                          TileServiceMetadata.ScalePath(orientation, epsg, scale);

            string compactTileName = CompactTileName(row, col);

            string bundleFilename     = path + @"\" + compactTileName + ".tilebundle";
            string bundleDoneFilename = path + @"\" + compactTileName + ".tilebundle.done";
            string bundleCalcFilename = path + @"\" + compactTileName + ".tilebundle.calc";

            if (new FileInfo(bundleFilename).Exists)
            {
                return(GetCompactTileBytes(context, path, row, col, format));
            }



            if (IsDirectoryEmpty(path))
            {
                #region On The Fly

                using (IServiceMap map = context.CreateServiceMapInstance())
                {
                    ISpatialReference sRef = SpatialReference.FromID("epsg:" + epsg);

                    map.Display.SpatialReference = sRef;
                    map.Display.dpi = metadata.Dpi;

                    map.Display.iWidth  = metadata.TileWidth;
                    map.Display.iHeight = metadata.TileHeight;

                    double res = (double)scale / (metadata.Dpi / 0.0254);
                    if (map.Display.MapUnits != GeoUnits.Meters)
                    {
                        GeoUnitConverter converter = new GeoUnitConverter();
                        res = converter.Convert(res, GeoUnits.Meters, map.Display.MapUnits);
                    }

                    origin = orientation == GridOrientation.UpperLeft ? metadata.GetOriginUpperLeft(epsg) : metadata.GetOriginLowerLeft(epsg);

                    double H = metadata.TileHeight * res;
                    double y = (orientation == GridOrientation.UpperLeft ?
                                origin.Y - H * (row + 1) :
                                origin.Y + H * row);

                    double W = metadata.TileWidth * res;
                    double x = origin.X + W * col;

                    map.Display.ZoomTo(new Envelope(x, y, x + W, y + H));
                    map.Render();

                    bool maketrans = map.Display.MakeTransparent;
                    map.Display.MakeTransparent = true;
                    MemoryStream ms = new MemoryStream();
                    map.SaveImage(ms, format == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png);
                    map.Display.MakeTransparent = maketrans;

                    return(ms.ToArray());
                }

                #endregion
            }


            return(null);
        }
示例#14
0
        private static object DeserializeRequest31(string templateXml, string contentXml, IServiceMap serviceMap = null, string serviceName = "Service1")
        {
            serviceMap = serviceMap ?? serviceMap31;
            var template = string.IsNullOrEmpty(templateXml) ? null : new XRoadXmlTemplate(templateXml, typeof(IService).GetTypeInfo().GetMethod(serviceName));

            return(DeserializeRequest(templateXml, contentXml, Globals.ServiceManager31, serviceName, (msgr, xmlr) =>
            {
                var message = Globals.ServiceManager31.CreateMessage();
                message.XmlTemplate = template;

                using (message)
                {
                    msgr.Read(message);
                    messageFormatter.MoveToPayload(xmlr, XName.Get(serviceName, Globals.ServiceManager31.ProducerNamespace));
                    return serviceMap.DeserializeRequest(xmlr, message);
                }
            }));
        }
示例#15
0
        public void Request(IServiceRequestContext context)
        {
            if (context == null || context.ServiceRequest == null)
            {
                return;
            }

            if (_mapServer == null)
            {
                return;
            }

            MiscParameterDescriptor parameters = new MiscParameterDescriptor();

            if (!parameters.ParseParameters(context.ServiceRequest.Request.Split('&')))
            {
                _mapServer.Log("Invalid Parameters", loggingMethod.error, context.ServiceRequest.Request);
                return;
            }

            using (IServiceMap map = context.ServiceMap) // _mapServer[context];
            {
                if (map == null)
                {
                    _mapServer.Log("Invalid Map", loggingMethod.error, context.ServiceRequest.Request);
                    return;
                }

                QueryFilter filter = parameters.BBOX != null ? new SpatialFilter() : new QueryFilter();
                filter.SubFields = "*";
                if (parameters.BBOX != null)
                {
                    ((SpatialFilter)filter).Geometry = parameters.BBOX;
                }
                if (!String.IsNullOrEmpty(parameters.SRS))
                {
                    ISpatialReference sRef = SpatialReference.FromID(parameters.SRS);
                    filter.FeatureSpatialReference = sRef;
                    if (filter is SpatialFilter)
                    {
                        ((SpatialFilter)filter).FilterSpatialReference = sRef;
                    }
                }
                // Get Layers
                List <ILayer> queryLayers = new List <ILayer>();
                foreach (string l in parameters.LAYERS)
                {
                    if (l == String.Empty || l[0] != 'c')
                    {
                        continue;
                    }

                    MapServerHelper.Layers layers = MapServerHelper.FindMapLayers(map, _useTOC, l.Substring(1, l.Length - 1));
                    if (layers == null)
                    {
                        continue;
                    }

                    foreach (ILayer layer in layers)
                    {
                        queryLayers.Add(layer);
                    }
                }

                StringBuilder sb = new StringBuilder();
                sb.Append("{'type':'FeatureCollection','features':[");
                foreach (ILayer layer in queryLayers)
                {
                    if (layer is IFeatureLayer && ((IFeatureLayer)layer).FeatureClass != null)
                    {
                        using (IFeatureCursor cursor = ((IFeatureLayer)layer).FeatureClass.Search(filter) as IFeatureCursor)
                        {
                            string json = gView.Framework.OGC.GeoJson.GeoJson.ToGeoJsonFeatures(cursor, parameters.MaxFeatures);
                            sb.Append(json);
                        }
                    }
                }
                sb.Append("]}");

                context.ServiceRequest.Response = sb.ToString();
            }
        }