Exemple #1
0
        protected string GetFixedUrl(IContextRequest request)
        {
            Uri    uri         = request.Url;
            string absoluteUri = uri.AbsoluteUri;

            return(uri.Query.Length <= 0 ? absoluteUri : absoluteUri.Replace(uri.Query, String.Empty));
        }
Exemple #2
0
        public void request_generates_transparent_image()
        {
            MockRepository  mocks = new MockRepository();
            IContextRequest req   = mocks.StrictMock <IContextRequest>();

            With.Mocks(mocks)
            .Expecting(() =>
            {
                Expect.Call(req.GetParam("VERSION")).Return("1.3.0");
                Expect.Call(req.GetParam("LAYERS")).Return("poly_landmarks,tiger_roads,poi");
                Expect.Call(req.GetParam("STYLES")).Return("");
                Expect.Call(req.GetParam("CRS")).Return("EPSG:4326");
                Expect.Call(req.GetParam("BBOX")).Return("40.68,-74.02,40.69,-74.01");
                Expect.Call(req.GetParam("WIDTH")).Return("256");
                Expect.Call(req.GetParam("HEIGHT")).Return("256");
                Expect.Call(req.GetParam("FORMAT")).Return("image/png");
                Expect.Call(req.GetParam("CQL_FILTER")).Return(null);
                Expect.Call(req.GetParam("TRANSPARENT")).Return("TRUE");
                DoNotExpect.Call(req.GetParam("BGCOLOR"));
            })
            .Verify(() =>
            {
                IHandler handler      = new GetMap(Desc);
                IHandlerResponse resp = handler.Handle(Map, req);
                Assert.That(resp, Is.Not.Null);
                Assert.IsInstanceOf <GetMapResponse>(resp);
                GetMapResponse img   = (GetMapResponse)resp;
                ImageCodecInfo codec = img.CodecInfo;
                Assert.That(codec, Is.Not.Null);
                Assert.That(codec.MimeType, Is.EqualTo("image/png"));
                Assert.That(img.Image, Is.Not.Null);
            });
        }
        protected Map GetMap(IContextRequest request)
        {
            string type = request.GetParam("MAP_TYPE");

            if (String.IsNullOrEmpty(type))
            {
                throw new WmsParameterNotSpecifiedException("MAP_TYPE");
            }
            if (String.Equals(type, "DEF", StringComparison.InvariantCultureIgnoreCase))
            {
                return(ShapefileHelper.Default());
            }
            if (String.Equals(type, "SPH", StringComparison.InvariantCultureIgnoreCase))
            {
                return(ShapefileHelper.Spherical());
            }
            if (String.Equals(type, "SQL", StringComparison.InvariantCultureIgnoreCase))
            {
                return(DatabaseHelper.SqlServer());
            }
            if (String.Equals(type, "BRU", StringComparison.InvariantCultureIgnoreCase))
            {
                return(BruTileHelper.Osm());
            }
            string format = String.Format("unsupported map type: '{0}'", type);

            throw new NotSupportedException(format);
        }
Exemple #4
0
        protected override WmsParams ValidateParams(IContextRequest request, int targetSrid)
        {
            WmsParams @params = ValidateCommons(request, targetSrid);

            // code specific for GetMap
            Color backColor;
            bool transparent = String.Equals(request.GetParam("TRANSPARENT"), "TRUE", Case);
            if (!transparent)
            {
                string bgcolor = request.GetParam("BGCOLOR");
                if (bgcolor != null)
                {
                    try { backColor = ColorTranslator.FromHtml(bgcolor); }
                    catch
                    {
                        string s = String.Format("Invalid parameter BGCOLOR: {0}", bgcolor);
                        throw new WmsInvalidParameterException(s);
                    }
                }
                else backColor = Color.White;
            }
            else backColor = Color.Transparent;
            @params.BackColor = backColor;
            return @params;
        }
Exemple #5
0
        protected override WmsParams ValidateParams(IContextRequest request, int targetSrid)
        {
            WmsParams @params = ValidateCommons(request, targetSrid);

            // code specific for GetMap
            Color backColor;
            bool  transparent = String.Equals(request.GetParam("TRANSPARENT"), "TRUE", Case);

            if (!transparent)
            {
                string bgcolor = request.GetParam("BGCOLOR");
                if (bgcolor != null)
                {
                    try { backColor = ColorTranslator.FromHtml(bgcolor); }
                    catch
                    {
                        string s = String.Format("Invalid parameter BGCOLOR: {0}", bgcolor);
                        throw new WmsInvalidParameterException(s);
                    }
                }
                else
                {
                    backColor = Color.White;
                }
            }
            else
            {
                backColor = Color.Transparent;
            }
            @params.BackColor = backColor;
            return(@params);
        }
Exemple #6
0
        protected override WmsParams ValidateParams(IContextRequest request, int targetSrid)
        {
            // version is mandatory only if REQUEST != GetCapabilities
            string version = request.GetParam("VERSION");

            if (version != null)
            {
                if (!String.Equals(version, "1.3.0", Case))
                {
                    throw new WmsOperationNotSupportedException("Only version 1.3.0 supported");
                }
            }
            // service parameter is mandatory for GetCapabilities request
            string service = request.GetParam("SERVICE");

            if (service == null)
            {
                throw new WmsParameterNotSpecifiedException("SERVICE");
            }

            if (!String.Equals(service, "WMS", StringComparison.InvariantCulture))
            {
                throw new WmsInvalidParameterException("Invalid service for GetCapabilities Request. Service parameter must be 'WMS'");
            }

            return(new WmsParams {
                Service = service, Version = version
            });
        }
        /// <summary>
        /// Generates a capabilities file from a map object for use in WMS services
        /// </summary>
        /// <remarks>The capabilities document uses the v1.3.0 OpenGIS WMS specification</remarks>
        /// <param name="map">The map to create capabilities for</param>
        /// <param name="description">Additional description of WMS</param>
        /// <param name="request">An abstraction of the <see cref="HttpContext"/> request</param>
        /// <returns>Returns XmlDocument describing capabilities</returns>
        public static XmlDocument GetCapabilities(Map map, WmsServiceDescription description, IContextRequest request)
        {
            XmlDocument capabilities = new XmlDocument();

            // Insert XML tag
            capabilities.InsertBefore(capabilities.CreateXmlDeclaration("1.0", "UTF-8", String.Empty), capabilities.DocumentElement);
            string format = String.Format("Capabilities generated by SharpMap v. {0}", Assembly.GetExecutingAssembly().GetName().Version);
            capabilities.AppendChild(capabilities.CreateComment(format));

            // Create root node
            XmlNode rootNode = capabilities.CreateNode(XmlNodeType.Element, "WMS_Capabilities", WmsNamespaceUri);
            rootNode.Attributes.Append(CreateAttribute("version", "1.3.0", capabilities));

            XmlAttribute attr = capabilities.CreateAttribute("xmlns", "xsi", "http://www.w3.org/2000/xmlns/");
            attr.InnerText = "http://www.w3.org/2001/XMLSchema-instance";
            rootNode.Attributes.Append(attr);

            rootNode.Attributes.Append(CreateAttribute("xmlns:xlink", XlinkNamespaceUri, capabilities));
            XmlAttribute attr2 = capabilities.CreateAttribute("xsi", "schemaLocation",
                                                              "http://www.w3.org/2001/XMLSchema-instance");
            attr2.InnerText = "http://schemas.opengis.net/wms/1.3.0/capabilities_1_3_0.xsd";
            rootNode.Attributes.Append(attr2);

            // Build Service node
            rootNode.AppendChild(GenerateServiceNode(ref description, capabilities));

            // Build Capability node
            XmlNode capabilityNode = GenerateCapabilityNode(map, capabilities, description.PublicAccessURL, request);
            rootNode.AppendChild(capabilityNode);

            capabilities.AppendChild(rootNode);

            //TODO: Validate output against schema
            return capabilities;
        }
Exemple #8
0
        public void bbox_must_be_valid()
        {
            MockRepository  mocks = new MockRepository();
            IContextRequest req   = mocks.StrictMock <IContextRequest>();

            With.Mocks(mocks)
            .Expecting(() =>
            {
                Expect.Call(req.GetParam("VERSION")).Return("1.3.0");
                Expect.Call(req.GetParam("LAYERS")).Return("poly_landmarks");
                Expect.Call(req.GetParam("STYLES")).Return("");
                Expect.Call(req.GetParam("CRS")).Return("EPSG:4326");
                Expect.Call(req.GetParam("BBOX")).Return("45,75,35,65");     // min-max flipped!
                Expect.Call(req.GetParam("WIDTH")).Return("256");
                Expect.Call(req.GetParam("HEIGHT")).Return("256");
                Expect.Call(req.GetParam("FORMAT")).Return("image/png");
                Expect.Call(req.GetParam("CQL_FILTER")).Return(null);
                Expect.Call(req.GetParam("TRANSPARENT")).Return("TRUE");
            })
            .Verify(() =>
            {
                IHandler handler      = new GetMap(Desc);
                IHandlerResponse resp = handler.Handle(Map, req);
                Assert.That(resp, Is.Not.Null);
            });
        }
        public override IHandlerResponse Handle(Map map, IContextRequest request)
        {
            ValidateParams(request, 0);

            XmlDocument doc = ServerCapabilities.GetCapabilities(map, Description, request);
            return new GetCapabilitiesResponse(doc);
        }
Exemple #10
0
        public void bgcolor_html_known_name()
        {
            MockRepository  mocks = new MockRepository();
            IContextRequest req   = mocks.StrictMock <IContextRequest>();

            With.Mocks(mocks)
            .Expecting(() =>
            {
                Expect.Call(req.GetParam("VERSION")).Return("1.3.0");
                Expect.Call(req.GetParam("LAYERS")).Return("poly_landmarks,tiger_roads,poi");
                Expect.Call(req.GetParam("STYLES")).Return("");
                Expect.Call(req.GetParam("CRS")).Return("EPSG:4326");
                Expect.Call(req.GetParam("BBOX")).Return("40.68,-74.02,40.69,-74.01");
                Expect.Call(req.GetParam("WIDTH")).Return("256");
                Expect.Call(req.GetParam("HEIGHT")).Return("256");
                Expect.Call(req.GetParam("FORMAT")).Return("image/png");
                Expect.Call(req.GetParam("CQL_FILTER")).Return(null);
                Expect.Call(req.GetParam("TRANSPARENT")).Return("FALSE");
                Expect.Call(req.GetParam("BGCOLOR")).Return("lightgrey");
            })
            .Verify(() =>
            {
                IHandler handler      = new GetMap(Desc);
                IHandlerResponse resp = handler.Handle(Map, req);
                Assert.That(resp, Is.Not.Null);
                Assert.IsInstanceOf <GetMapResponse>(resp);
            });
        }
Exemple #11
0
        public Context(HttpContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context", "An attempt was made to access the WMS server outside a valid HttpContext");

            _request = new ContextRequest(context);
            _response = new ContextResponse(context);
        }
Exemple #12
0
        public override IHandlerResponse Handle(Map map, IContextRequest request)
        {
            ValidateParams(request, 0);

            XmlDocument doc = ServerCapabilities.GetCapabilities(map, Description, request);

            return(new GetCapabilitiesResponse(doc));
        }
Exemple #13
0
        public Context(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context", "An attempt was made to access the WMS server outside a valid HttpContext");
            }

            _request  = new ContextRequest(context);
            _response = new ContextResponse(context);
        }
        public void request_generates_valid_json()
        {
            MockRepository  mocks = new MockRepository();
            IContextRequest req   = mocks.StrictMock <IContextRequest>();

            With.Mocks(mocks)
            .Expecting(() =>
            {
                Expect.Call(req.GetParam("VERSION")).Return("1.3.0");
                Expect.Call(req.GetParam("LAYERS")).Return("poly_landmarks,tiger_roads,poi");
                Expect.Call(req.GetParam("STYLES")).Return("");
                Expect.Call(req.GetParam("CRS")).Return("EPSG:4326");
                Expect.Call(req.GetParam("BBOX")).Return("40.68,-74.02,40.69,-74.01");
                Expect.Call(req.GetParam("WIDTH")).Return("256");
                Expect.Call(req.GetParam("HEIGHT")).Return("256");
                Expect.Call(req.GetParam("FORMAT")).Return("image/png");
                Expect.Call(req.GetParam("CQL_FILTER")).Return(null);
                Expect.Call(req.GetParam("QUERY_LAYERS")).Return("poly_landmarks");
                Expect.Call(req.GetParam("INFO_FORMAT")).Return("text/json");
                Expect.Call(req.GetParam("X")).Return(null);
                Expect.Call(req.GetParam("I")).Return("128");
                Expect.Call(req.GetParam("Y")).Return(null);
                Expect.Call(req.GetParam("J")).Return("128");
                Expect.Call(req.GetParam("FEATURE_COUNT")).Return("10");
            })
            .Verify(() =>
            {
                IHandler handler      = new GetFeatureInfoJson(Desc);
                IHandlerResponse resp = handler.Handle(Map, req);
                Assert.That(resp, Is.Not.Null);
                Assert.IsInstanceOf <GetFeatureInfoResponseJson>(resp);
                GetFeatureInfoResponseJson json = (GetFeatureInfoResponseJson)resp;
                string contentType = json.ContentType;
                Assert.That(contentType, Is.Not.Null);
                Assert.That(contentType, Is.EqualTo("text/json"));
                string charset = json.Charset;
                Assert.That(charset, Is.Not.Null);
                Assert.That(charset, Is.EqualTo("utf-8"));

                JContainer c = (JContainer)JsonConvert.DeserializeObject(json.Response);
                JToken token = c.First;
                Assert.That(token, Is.InstanceOf <JProperty>());
                JProperty type = (JProperty)token;
                Assert.That(type.Name, Is.EqualTo("type"));
                Assert.That(type.Value.Value <string>(), Is.EqualTo("FeatureCollection"));
                token = token.Next;
                Assert.That(token, Is.InstanceOf <JProperty>());
                JProperty features = (JProperty)token;
                Assert.That(features.Name, Is.EqualTo("features"));
                Assert.That(features.Value, Is.InstanceOf <JArray>());
            });
        }
Exemple #15
0
        public override void ProcessRequest(IContext context)
        {
            IContextRequest  request  = context.Request;
            IContextResponse response = context.Response;

            try
            {
                string s = request.GetParam("BBOX");
                if (String.IsNullOrEmpty(s))
                {
                    throw new WmsInvalidParameterException("BBOX");
                }


                Map             map    = GetMap(request);
                LayerCollection layers = map.Layers;
                ILayer          first  = layers.First();
                bool            flip   = first.TargetSRID == 4326;
                BoundingBox     bbox   = AbstractHandler.ParseBBOX(s, flip);
                if (bbox == null)
                {
                    throw new WmsInvalidBboxException(s);
                }

                string ls = request.GetParam("LAYERS");
                if (!String.IsNullOrEmpty(ls))
                {
                    string[] strings = ls.Split(',');
                    foreach (ILayer layer in layers)
                    {
                        if (!strings.Contains(layer.LayerName))
                        {
                            layer.Enabled = false;
                        }
                    }
                }

                IEnumerable <GeoJSON> items  = GetData(map, bbox);
                StringWriter          writer = new StringWriter();
                GeoJSONWriter.Write(items, writer);
                string buffer = writer.ToString();

                IHandlerResponse result = new GetFeatureInfoResponseJson(buffer);
                result.WriteToContextAndFlush(response);
            }
            catch (WmsExceptionBase ex)
            {
                ex.WriteToContextAndFlush(response);
            }
        }
Exemple #16
0
        /// <summary>
        /// Validate common arguments for GetFeatureInfo and GetMap requests
        /// </summary>
        protected WmsParams ValidateCommons(IContextRequest request, int targetSrid)
        {
            string version = request.GetParam("VERSION");
            if (version == null)
                throw new WmsParameterNotSpecifiedException("VERSION");
            if (!String.Equals(version, "1.3.0", Case))
                throw new WmsInvalidParameterException("Only version 1.3.0 supported");
            string layers = request.GetParam("LAYERS");
            if (layers == null)
                throw new WmsParameterNotSpecifiedException("LAYERS");
            string styles = request.GetParam("STYLES");
            if (styles == null)
                throw new WmsParameterNotSpecifiedException("STYLES");
            string crs = request.GetParam("CRS");
            if (crs == null)
                throw new WmsParameterNotSpecifiedException("CRS");
            if (crs != "EPSG:" + targetSrid)
                throw new WmsInvalidCRSException("CRS not supported");
            string bbox = request.GetParam("BBOX");
            if (bbox == null)
                throw new WmsParameterNotSpecifiedException("BBOX");
            string width = request.GetParam("WIDTH");
            if (width == null)
                throw new WmsParameterNotSpecifiedException("WIDTH");
            string height = request.GetParam("HEIGHT");
            if (height == null)
                throw new WmsParameterNotSpecifiedException("HEIGHT");
            string format = request.GetParam("FORMAT");
            if (format == null)
                throw new WmsParameterNotSpecifiedException("FORMAT");
            string cqlFilter = request.GetParam("CQL_FILTER");
            short w, h;
            if (!Int16.TryParse(width, out w) || !Int16.TryParse(height, out h))
                throw new WmsInvalidParameterException("Invalid parameters for HEIGHT or WITDH");
            Envelope env = ParseBBOX(bbox, targetSrid == 4326);
            if (env == null)
                throw new WmsInvalidBboxException(bbox);

            return new WmsParams
            {
                Layers = layers,
                Styles = styles,
                CRS = crs,
                BBOX = env,
                Width = w,
                Height = h,
                Format = format,
                CqlFilter = cqlFilter
            };
        }
 protected Map GetMap(IContextRequest request)
 {
     string type = request.GetParam("MAP_TYPE");
     if (String.IsNullOrEmpty(type))
         throw new WmsParameterNotSpecifiedException("MAP_TYPE");
     if (String.Equals(type, "DEF", StringComparison.InvariantCultureIgnoreCase))
         return ShapefileHelper.Default();
     if (String.Equals(type, "SPH", StringComparison.InvariantCultureIgnoreCase))
         return ShapefileHelper.Spherical();
     if (String.Equals(type, "SQL", StringComparison.InvariantCultureIgnoreCase))
         return DatabaseHelper.SqlServer();
     string format = String.Format("unsupported map type: '{0}'", type);
     throw new NotSupportedException(format);
 }
Exemple #18
0
        public void only_wms_130_is_supported()
        {
            MockRepository  mocks = new MockRepository();
            IContextRequest req   = mocks.StrictMock <IContextRequest>();

            With.Mocks(mocks)
            .Expecting(() => Expect.Call(req.GetParam("VERSION")).Return("1.1.1"))
            .Verify(() =>
            {
                IHandler handler      = new GetMap(Desc);
                IHandlerResponse resp = handler.Handle(Map, req);
                Assert.That(resp, Is.Not.Null);
                Assert.IsInstanceOf <GetMapResponse>(resp);
            });
        }
Exemple #19
0
        public void no_queryable_layer()
        {
            const string expectedPlain = "GetFeatureInfo results:\nSearch returned no results on layer: poly_landmarks\n";

            MockRepository  mocks = new MockRepository();
            IContextRequest req   = mocks.StrictMock <IContextRequest>();

            With.Mocks(mocks)
            .Expecting(() =>
            {
                Expect.Call(req.GetParam("VERSION")).Return("1.3.0");
                Expect.Call(req.GetParam("LAYERS")).Return("poly_landmarks,tiger_roads,poi");
                Expect.Call(req.GetParam("STYLES")).Return("");
                Expect.Call(req.GetParam("CRS")).Return("EPSG:4326");
                Expect.Call(req.GetParam("BBOX")).Return("40.689903,-74.02474,40.724235,-73.98955");
                Expect.Call(req.GetParam("WIDTH")).Return("800");
                Expect.Call(req.GetParam("HEIGHT")).Return("820");
                Expect.Call(req.GetParam("FORMAT")).Return("image/png");
                Expect.Call(req.GetParam("CQL_FILTER")).Return(null);
                Expect.Call(req.GetParam("QUERY_LAYERS")).Return("poly_landmarks");
                Expect.Call(req.GetParam("INFO_FORMAT")).Return("text/plain");
                Expect.Call(req.GetParam("X")).Return(null);
                Expect.Call(req.GetParam("I")).Return("378");
                Expect.Call(req.GetParam("Y")).Return(null);
                Expect.Call(req.GetParam("J")).Return("288");
                Expect.Call(req.GetParam("FEATURE_COUNT")).Return("10");
            })
            .Verify(() =>
            {
                foreach (ILayer layer in Map.Layers)
                {
                    ((VectorLayer)layer).IsQueryEnabled = false;
                }

                IHandler handler      = new GetFeatureInfoPlain(Desc);
                IHandlerResponse resp = handler.Handle(Map, req);
                Assert.That(resp, Is.Not.Null);
                Assert.IsInstanceOf <GetFeatureInfoResponsePlain>(resp);
                GetFeatureInfoResponsePlain plain = (GetFeatureInfoResponsePlain)resp;
                string contentType = plain.ContentType;
                Assert.That(contentType, Is.Not.Null);
                Assert.That(contentType, Is.EqualTo("text/plain"));
                string charset = plain.Charset;
                Assert.That(charset, Is.Not.Null);
                Assert.That(charset, Is.EqualTo("utf-8"));
                Assert.That(plain.Response, Is.EqualTo(expectedPlain));
            });
        }
Exemple #20
0
 public override IHandlerResponse Handle(Map map, IContextRequest request)
 {
     WmsParams @params = ValidateParams(request, TargetSrid(map));
     map.Size = new Size(@params.Width, @params.Height);
     map.ZoomToBox(@params.BBOX);
     string[] requestLayers = @params.QueryLayers.Split(new[] { ',' });
     AbstractGetFeatureInfoResponse info = CreateFeatureInfo(map,
         requestLayers,
         @params.X, @params.Y,
         @params.FeatureCount,
         @params.CqlFilter,
         _params.PixelSensitivity,
         _params.IntersectDelegate);
     if (_params.Encoding != null)
         info.Charset = _params.Encoding.WebName;
     return info;
 }
        public void no_queryable_layer()
        {
            MockRepository  mocks = new MockRepository();
            IContextRequest req   = mocks.StrictMock <IContextRequest>();

            With.Mocks(mocks)
            .Expecting(() =>
            {
                Expect.Call(req.GetParam("VERSION")).Return("1.3.0");
                Expect.Call(req.GetParam("LAYERS")).Return("poly_landmarks,tiger_roads,poi");
                Expect.Call(req.GetParam("STYLES")).Return("");
                Expect.Call(req.GetParam("CRS")).Return("EPSG:4326");
                Expect.Call(req.GetParam("BBOX")).Return("40.68,-74.02,40.69,-74.01");
                Expect.Call(req.GetParam("WIDTH")).Return("256");
                Expect.Call(req.GetParam("HEIGHT")).Return("256");
                Expect.Call(req.GetParam("FORMAT")).Return("image/png");
                Expect.Call(req.GetParam("CQL_FILTER")).Return(null);
                Expect.Call(req.GetParam("QUERY_LAYERS")).Return("poly_landmarks");
                Expect.Call(req.GetParam("INFO_FORMAT")).Return("text/json");
                Expect.Call(req.GetParam("X")).Return(null);
                Expect.Call(req.GetParam("I")).Return("128");
                Expect.Call(req.GetParam("Y")).Return(null);
                Expect.Call(req.GetParam("J")).Return("128");
                Expect.Call(req.GetParam("FEATURE_COUNT")).Return("10");
            })
            .Verify(() =>
            {
                foreach (ILayer layer in Map.Layers)
                {
                    ((VectorLayer)layer).IsQueryEnabled = false;
                }

                IHandler handler      = new GetFeatureInfoJson(Desc);
                IHandlerResponse resp = handler.Handle(Map, req);
                Assert.That(resp, Is.Not.Null);
                Assert.IsInstanceOf <GetFeatureInfoResponseJson>(resp);
                GetFeatureInfoResponseJson json = (GetFeatureInfoResponseJson)resp;
                string contentType = json.ContentType;
                Assert.That(contentType, Is.Not.Null);
                Assert.That(contentType, Is.EqualTo("text/json"));
                string charset = json.Charset;
                Assert.That(charset, Is.Not.Null);
                Assert.That(charset, Is.EqualTo("utf-8"));
                Assert.That(json.Response, Is.EqualTo("{\"type\":\"FeatureCollection\",\"features\":[]}"));
            });
        }
Exemple #22
0
 public override IHandlerResponse Handle(Map map, IContextRequest request)
 {
     WmsParams @params = ValidateParams(request, TargetSrid(map));
     map.Size = new Size(@params.Width, @params.Height);
     map.ZoomToBox(@params.BBOX);
     string[] requestLayers = @params.QueryLayers.Split(new[] { ',' });
     AbstractGetFeatureInfoResponse info = CreateFeatureInfo(map,
         requestLayers,
         @params.X, @params.Y,
         @params.FeatureCount,
         @params.CqlFilter,
         _params.PixelSensitivity,
         _params.IntersectDelegate);
     if (_params.Encoding != null)
         info.Charset = _params.Encoding.WebName;
     return info;
 }
        /// <summary>
        /// Generates a capabilities file from a map object for use in WMS services
        /// </summary>
        /// <remarks>The capabilities document uses the v1.3.0 OpenGIS WMS specification</remarks>
        /// <param name="map">The map to create capabilities for</param>
        /// <param name="serviceDescription">Additional description of WMS</param>
        /// <param name="request">An abstraction of the <see cref="HttpContext"/> request</param>
        /// <returns>Returns XmlDocument describing capabilities</returns>
        public static XmlDocument GetCapabilities(Map map, WmsServiceDescription serviceDescription, IContextRequest request)
        {
            XmlDocument capabilities = new XmlDocument();


            //Set XMLSchema
            //capabilities.Schemas.Add(GetCapabilitiesSchema());

            //Instantiate an XmlNamespaceManager object.
            //System.Xml.XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager(capabilities.NameTable);
            //xmlnsManager.AddNamespace(xlinkNamespaceURI, "urn:Books");

            //Insert XML tag
            capabilities.InsertBefore(capabilities.CreateXmlDeclaration("1.0", "UTF-8", string.Empty),
                                      capabilities.DocumentElement);
            capabilities.AppendChild(
                capabilities.CreateComment("Capabilities generated by SharpMap v. " +
                                           Assembly.GetExecutingAssembly().GetName().Version));
            //Create root node
            XmlNode RootNode = capabilities.CreateNode(XmlNodeType.Element, "WMS_Capabilities", wmsNamespaceURI);
            RootNode.Attributes.Append(CreateAttribute("version", "1.3.0", capabilities));

            XmlAttribute attr = capabilities.CreateAttribute("xmlns", "xsi", "http://www.w3.org/2000/xmlns/");
            attr.InnerText = "http://www.w3.org/2001/XMLSchema-instance";
            RootNode.Attributes.Append(attr);

            RootNode.Attributes.Append(CreateAttribute("xmlns:xlink", xlinkNamespaceURI, capabilities));
            XmlAttribute attr2 = capabilities.CreateAttribute("xsi", "schemaLocation",
                                                              "http://www.w3.org/2001/XMLSchema-instance");
            attr2.InnerText = "http://schemas.opengis.net/wms/1.3.0/capabilities_1_3_0.xsd";
            RootNode.Attributes.Append(attr2);

            //Build Service node
            RootNode.AppendChild(GenerateServiceNode(ref serviceDescription, capabilities));

            //Build Capability node
            XmlNode capabilityNode = GenerateCapabilityNode(map, capabilities, serviceDescription.PublicAccessURL, request);
            RootNode.AppendChild(capabilityNode);

            capabilities.AppendChild(RootNode);

            //TODO: Validate output against schema

            return capabilities;
        }
        public void service_param_is_mandatory()
        {
            MockRepository  mocks = new MockRepository();
            IContextRequest req   = mocks.StrictMock <IContextRequest>();

            With.Mocks(mocks)
            .Expecting(() =>
            {
                Expect.Call(req.GetParam("VERSION")).Return("1.3.0");
                Expect.Call(req.GetParam("SERVICE")).Return(null);
            })
            .Verify(() =>
            {
                IHandler handler      = new GetCapabilities(Desc);
                IHandlerResponse resp = handler.Handle(Map, req);
                Assert.That(resp, Is.Not.Null);
            });
        }
        protected override WmsParams ValidateParams(IContextRequest request, int targetSrid)
        {
            // version is mandatory only if REQUEST != GetCapabilities
            string version = request.GetParam("VERSION");
            if (version != null)
            {
                if (!String.Equals(version, "1.3.0", Case))
                    throw new WmsOperationNotSupportedException("Only version 1.3.0 supported");
            }
            // service parameter is mandatory for GetCapabilities request
            string service = request.GetParam("SERVICE");
            if (service == null)
                throw new WmsParameterNotSpecifiedException("SERVICE");

            if (!String.Equals(service, "WMS", StringComparison.InvariantCulture))
                throw new WmsInvalidParameterException("Invalid service for GetCapabilities Request. Service parameter must be 'WMS'");

            return new WmsParams { Service = service, Version = version };
        }
Exemple #26
0
        public void request_generates_valid_plain()
        {
            const string expectedPlain = "GetFeatureInfo results:\nLayer: \'poly_landmarks\'\nFeatureinfo:\n\'52\' \'76\' \'D65\' \'City Hall\',\n\'47\' \'69\' \'H11\' \'Hudson River\'\n";

            MockRepository  mocks = new MockRepository();
            IContextRequest req   = mocks.StrictMock <IContextRequest>();

            With.Mocks(mocks)
            .Expecting(() =>
            {
                Expect.Call(req.GetParam("VERSION")).Return("1.3.0");
                Expect.Call(req.GetParam("LAYERS")).Return("poly_landmarks,tiger_roads,poi");
                Expect.Call(req.GetParam("STYLES")).Return("");
                Expect.Call(req.GetParam("CRS")).Return("EPSG:4326");
                Expect.Call(req.GetParam("BBOX")).Return("40.689903,-74.02474,40.724235,-73.98955");
                Expect.Call(req.GetParam("WIDTH")).Return("800");
                Expect.Call(req.GetParam("HEIGHT")).Return("820");
                Expect.Call(req.GetParam("FORMAT")).Return("image/png");
                Expect.Call(req.GetParam("CQL_FILTER")).Return(null);
                Expect.Call(req.GetParam("QUERY_LAYERS")).Return("poly_landmarks");
                Expect.Call(req.GetParam("INFO_FORMAT")).Return("text/plain");
                Expect.Call(req.GetParam("X")).Return(null);
                Expect.Call(req.GetParam("I")).Return("378");
                Expect.Call(req.GetParam("Y")).Return(null);
                Expect.Call(req.GetParam("J")).Return("288");
                Expect.Call(req.GetParam("FEATURE_COUNT")).Return("10");
            })
            .Verify(() =>
            {
                IHandler handler      = new GetFeatureInfoPlain(Desc);
                IHandlerResponse resp = handler.Handle(Map, req);
                Assert.That(resp, Is.Not.Null);
                Assert.IsInstanceOf <GetFeatureInfoResponsePlain>(resp);
                GetFeatureInfoResponsePlain plain = (GetFeatureInfoResponsePlain)resp;
                string contentType = plain.ContentType;
                Assert.That(contentType, Is.Not.Null);
                Assert.That(contentType, Is.EqualTo("text/plain"));
                string charset = plain.Charset;
                Assert.That(charset, Is.Not.Null);
                Assert.That(charset, Is.EqualTo("utf-8"));
                Assert.That(plain.Response, Is.EqualTo(expectedPlain));
            });
        }
Exemple #27
0
        protected override WmsParams ValidateParams(IContextRequest request, int targetSrid)
        {
            WmsParams @params = ValidateCommons(request, targetSrid);

            // code specific for GetFeatureInfo
            string queryLayers = request.GetParam("QUERY_LAYERS");
            if (queryLayers == null)
                throw new WmsParameterNotSpecifiedException("QUERY_LAYERS");
            @params.QueryLayers = queryLayers;

            string infoFormat = request.GetParam("INFO_FORMAT");
            if (infoFormat == null)
                throw new WmsParameterNotSpecifiedException("INFO_FORMAT");

            @params.InfoFormat = infoFormat;

            // parameters X&Y are not part of the 1.3.0 specification, 
            // but are included for backwards compatability with 1.1.1 
            // (OpenLayers likes it when used together with wms1.1.1 services)
            // we will assume that Openlayers is used by default 
            // so check X&Y first
            string x = request.GetParam("X") ?? request.GetParam("I");
            if (x == null)
                throw new WmsParameterNotSpecifiedException("I");
            string y = request.GetParam("Y") ?? request.GetParam("J");
            if (y == null)
                throw new WmsParameterNotSpecifiedException("J");

            float cx;
            if (!Single.TryParse(x, out cx))
                throw new WmsInvalidParameterException("Invalid parameters for X / I");
            @params.X = cx;
            float cy;
            if (!Single.TryParse(y, out cy))
                throw new WmsInvalidParameterException("Invalid parameters for Y / J");
            @params.Y = cy;

            string featureCount = request.GetParam("FEATURE_COUNT");
            int fc = Int32.TryParse(featureCount, out fc) ? Math.Max(fc, 1) : 1;
            @params.FeatureCount = fc;
            return @params;
        }
Exemple #28
0
        protected override WmsParams ValidateParams(IContextRequest request, int targetSrid)
        {
            WmsParams @params = ValidateCommons(request, targetSrid);

            // code specific for GetFeatureInfo
            string queryLayers = request.GetParam("QUERY_LAYERS");
            if (queryLayers == null)
                throw new WmsParameterNotSpecifiedException("QUERY_LAYERS");
            @params.QueryLayers = queryLayers;

            string infoFormat = request.GetParam("INFO_FORMAT");
            if (infoFormat == null)
                throw new WmsParameterNotSpecifiedException("INFO_FORMAT");

            @params.InfoFormat = infoFormat;

            // parameters X&Y are not part of the 1.3.0 specification, 
            // but are included for backwards compatability with 1.1.1 
            // (OpenLayers likes it when used together with wms1.1.1 services)
            // we will assume that Openlayers is used by default 
            // so check X&Y first
            string x = request.GetParam("X") ?? request.GetParam("I");
            if (x == null)
                throw new WmsParameterNotSpecifiedException("I");
            string y = request.GetParam("Y") ?? request.GetParam("J");
            if (y == null)
                throw new WmsParameterNotSpecifiedException("J");

            float cx;
            if (!Single.TryParse(x, out cx))
                throw new WmsInvalidParameterException("Invalid parameters for X / I");
            @params.X = cx;
            float cy;
            if (!Single.TryParse(y, out cy))
                throw new WmsInvalidParameterException("Invalid parameters for Y / J");
            @params.Y = cy;

            string featureCount = request.GetParam("FEATURE_COUNT");
            int fc = Int32.TryParse(featureCount, out fc) ? Math.Max(fc, 1) : 1;
            @params.FeatureCount = fc;
            return @params;
        }
Exemple #29
0
        public void crs_support_is_checked()
        {
            MockRepository  mocks = new MockRepository();
            IContextRequest req   = mocks.StrictMock <IContextRequest>();

            With.Mocks(mocks)
            .Expecting(() =>
            {
                Expect.Call(req.GetParam("VERSION")).Return("1.3.0");
                Expect.Call(req.GetParam("LAYERS")).Return("poly_landmarks");
                Expect.Call(req.GetParam("STYLES")).Return("WMS");
                Expect.Call(req.GetParam("CRS")).Return("EPSG:900913");
            })
            .Verify(() =>
            {
                IHandler handler      = new GetMap(Desc);
                IHandlerResponse resp = handler.Handle(Map, req);
                Assert.That(resp, Is.Not.Null);
                Assert.IsInstanceOf <GetMapResponse>(resp);
            });
        }
        public void version_param_is_optional()
        {
            MockRepository  mocks = new MockRepository();
            IContextRequest req   = mocks.StrictMock <IContextRequest>();

            With.Mocks(mocks)
            .Expecting(() =>
            {
                Expect.Call(req.GetParam("VERSION")).Return(null);
                Expect.Call(req.GetParam("SERVICE")).Return("WMS");
                Expect.Call(req.Url).Return(new Uri(Desc.OnlineResource)).Repeat.AtLeastOnce();
                Expect.Call(req.Encode(Desc.OnlineResource)).Return(Desc.OnlineResource);
            })
            .Verify(() =>
            {
                IHandler handler      = new GetCapabilities(Desc);
                IHandlerResponse resp = handler.Handle(Map, req);
                Assert.That(resp, Is.Not.Null);
                Assert.IsInstanceOf <GetCapabilitiesResponse>(resp);
                Validate((GetCapabilitiesResponse)resp);
            });
        }
Exemple #31
0
 protected abstract WmsParams ValidateParams(IContextRequest request, int targetSrid);
Exemple #32
0
 public abstract IHandlerResponse Handle(Map map, IContextRequest request);
Exemple #33
0
        public override IHandlerResponse Handle(Map map, IContextRequest request)
        {
            WmsParams @params = ValidateParams(request, TargetSrid(map));

            map.BackColor = @params.BackColor;

            // get the image format requested
            ImageCodecInfo imageEncoder = GetEncoderInfo(@params.Format);

            Size size = GetSize(@params);

            map.Size = size;
            Envelope bbox      = @params.BBOX;
            double   sizeRatio = size.Width / (double)size.Height;
            double   bboxRatio = bbox.Width / bbox.Height;

            map.PixelAspectRatio = sizeRatio / bboxRatio;
            map.Center           = bbox.Centre;
            map.Zoom             = bbox.Width;

            // set Styles for layerNames
            // first, if the request ==  STYLES=, set all the vectorlayers with Themes not null the Theme to the first theme from Themes
            string ptheme    = @params.Styles;
            string players   = @params.Layers;
            string cqlFilter = @params.CqlFilter;

            if (!String.IsNullOrEmpty(players))
            {
                string[] layerNames = GetLayerNames(map, players);

                // we have a known set of layerNames in request
                // so we will set each layer to its default theme
                // and disable the layer, layers will be enabled
                // later as per the request
                foreach (ILayer layer in map.Layers)
                {
                    VectorLayer vectorLayer = layer as VectorLayer;
                    SetDefaultThemeForLayer(vectorLayer);
                    layer.Enabled = false;
                }

                Dictionary <string, string> themeTable = new Dictionary <string, string>();
                BuildThemeLookup(ptheme, layerNames, themeTable);

                // since we have layerNames specified
                // enable only those layerNames
                for (int j = 0; j < layerNames.Length; j++)
                {
                    string layerName = layerNames[j];
                    ILayer layer     = GetMapLayerByName(map, layerName);

                    // set layer on/off
                    layer.Enabled = true;

                    // check if a styles have been specified for layers
                    if (themeTable.Count > 0)
                    {
                        string themeName = themeTable[layerName];
                        // do nothing if themeName is empty
                        if (!string.IsNullOrEmpty(themeName))
                        {
                            // is this a vector layer at all
                            VectorLayer vectorLayer = layer as VectorLayer;

                            // does it have several themes to choose from
                            // TODO -> Refactor VectorLayer.Themes to Rendering.Thematics.ThemeList : ITheme
                            if (vectorLayer != null && vectorLayer.Themes != null && vectorLayer.Themes.Count > 0)
                            {
                                // we need to a case invariant comparison for themeName
                                Dictionary <string, ITheme> themeDict = new Dictionary <string, ITheme>(vectorLayer.Themes, new StringComparerIgnoreCase());

                                if (!themeDict.ContainsKey(themeName))
                                {
                                    throw new WmsStyleNotDefinedException("Style not advertised for this layer");
                                }
                                vectorLayer.Theme = themeDict[themeName];
                            }
                        }
                    }

                    if (!String.IsNullOrEmpty(cqlFilter))
                    {
                        ApplyCqlFilter(cqlFilter, layer);
                    }
                }
            }
            // render map
            Image img = map.GetMap();

            return(new GetMapResponse(img, imageEncoder));
        }
        public void request_generates_valid_html()
        {
            const string    expectedHtml = @"<html>
<head>
<title>GetFeatureInfo output</title>
</head>
<style type='text/css'>
  table.featureInfo, table.featureInfo td, table.featureInfo th {
  border:1px solid #ddd;
  border-collapse:collapse;
  margin:0;
  padding:0;
  font-size: 90%;
  padding:.2em .1em;
}
table.featureInfo th {
  padding:.2em .2em;
  font-weight:bold;
  background:#eee;
}
table.featureInfo td {
  background:#fff;
}
table.featureInfo tr.odd td {
  background:#eee;
}
table.featureInfo caption {
  text-align:left;
  font-size:100%;
  font-weight:bold;
  padding:.2em .2em;
}
</style>
<body>
<table class='featureInfo'>
<caption class='featureInfo'>poly_landmarks</caption>
<tr>
<th>Oid</th>
<th>LAND</th>
<th>CFCC</th>
<th>LANAME</th>
</tr>
<tr class='even'>
<td>52</td>
<td>76</td>
<td>D65</td>
<td>City Hall</td>
</tr>
<tr class='odd'>
<td>47</td>
<td>69</td>
<td>H11</td>
<td>Hudson River</td>
</tr>
</table>
<br />
<table class='featureInfo'>
<caption class='featureInfo'>tiger_roads</caption>
<tr>
<th>Oid</th>
<th>CFCC</th>
<th>NAME</th>
</tr>
<tr class='even'>
<td>7664</td>
<td>A41</td>
<td>Broadway</td>
</tr>
<tr class='odd'>
<td>7667</td>
<td>A41</td>
<td>Broadway</td>
</tr>
<tr class='even'>
<td>6016</td>
<td>A41</td>
<td>Barclay St</td>
</tr>
</table>
<br />

</body>
</html>";
            MockRepository  mocks        = new MockRepository();
            IContextRequest req          = mocks.StrictMock <IContextRequest>();

            With.Mocks(mocks)
            .Expecting(() =>
            {
                Expect.Call(req.GetParam("VERSION")).Return("1.3.0");
                Expect.Call(req.GetParam("LAYERS")).Return("poly_landmarks,tiger_roads,poi");
                Expect.Call(req.GetParam("STYLES")).Return("");
                Expect.Call(req.GetParam("CRS")).Return("EPSG:4326");
                Expect.Call(req.GetParam("BBOX")).Return("40.689903,-74.02474,40.724235,-73.98955");
                Expect.Call(req.GetParam("WIDTH")).Return("800");
                Expect.Call(req.GetParam("HEIGHT")).Return("820");
                Expect.Call(req.GetParam("FORMAT")).Return("image/png");
                Expect.Call(req.GetParam("CQL_FILTER")).Return(null);
                Expect.Call(req.GetParam("QUERY_LAYERS")).Return("poly_landmarks,tiger_roads,poi");
                Expect.Call(req.GetParam("INFO_FORMAT")).Return("text/html");
                Expect.Call(req.GetParam("X")).Return(null);
                Expect.Call(req.GetParam("I")).Return("378");
                Expect.Call(req.GetParam("Y")).Return(null);
                Expect.Call(req.GetParam("J")).Return("288");
                Expect.Call(req.GetParam("FEATURE_COUNT")).Return("10");
            })
            .Verify(() =>
            {
                IHandler handler      = new GetFeatureInfoHtml(Desc);
                IHandlerResponse resp = handler.Handle(Map, req);
                Assert.That(resp, Is.Not.Null);
                Assert.IsInstanceOf <GetFeatureInfoResponseHtml>(resp);
                GetFeatureInfoResponseHtml html = (GetFeatureInfoResponseHtml)resp;
                string contentType = html.ContentType;
                Assert.That(contentType, Is.Not.Null);
                Assert.That(contentType, Is.EqualTo("text/html"));
                string charset = html.Charset;
                Assert.That(charset, Is.Not.Null);
                Assert.That(charset, Is.EqualTo("utf-8"));
                string actual   = html.Response;
                string expected = expectedHtml.Replace(Environment.NewLine, new String('\n', 1));
                Assert.That(actual, Is.EqualTo(expected));
            });
        }
Exemple #35
0
        public override IHandlerResponse Handle(Map map, IContextRequest request)
        {
            WmsParams @params = ValidateParams(request, TargetSrid(map));
            map.BackColor = @params.BackColor;

            // get the image format requested
            ImageCodecInfo imageEncoder = GetEncoderInfo(@params.Format);

            Size size = GetSize(@params);
            map.Size = size;
            Envelope bbox = @params.BBOX;
            double sizeRatio = size.Width / (double)size.Height;
            double bboxRatio = bbox.Width / bbox.Height;
            map.PixelAspectRatio = sizeRatio / bboxRatio;
            map.Center = bbox.Centre;
            map.Zoom = bbox.Width;

            // set Styles for layerNames
            // first, if the request ==  STYLES=, set all the vectorlayers with Themes not null the Theme to the first theme from Themes
            string ptheme = @params.Styles;
            string players = @params.Layers;
            string cqlFilter = @params.CqlFilter;

            if (!String.IsNullOrEmpty(players))
            {
                string[] layerNames = GetLayerNames(map, players);

                // we have a known set of layerNames in request 
                // so we will set each layer to its default theme
                // and disable the layer, layers will be enabled 
                // later as per the request
                foreach (ILayer layer in map.Layers)
                {
                    VectorLayer vectorLayer = layer as VectorLayer;
                    SetDefaultThemeForLayer(vectorLayer);
                    layer.Enabled = false;
                }

                Dictionary<string, string> themeTable = new Dictionary<string, string>();
                BuildThemeLookup(ptheme, layerNames, themeTable);

                // since we have layerNames specified
                // enable only those layerNames
                for (int j = 0; j < layerNames.Length; j++)
                {
                    string layerName = layerNames[j];
                    ILayer layer = GetMapLayerByName(map, layerName);

                    // set layer on/off
                    layer.Enabled = true;

                    // check if a styles have been specified for layers
                    if (themeTable.Count > 0)
                    {
                        string themeName = themeTable[layerName];
                        // do nothing if themeName is empty
                        if (!string.IsNullOrEmpty(themeName))
                        {
                            // is this a vector layer at all
                            VectorLayer vectorLayer = layer as VectorLayer;

                            // does it have several themes to choose from
                            // TODO -> Refactor VectorLayer.Themes to Rendering.Thematics.ThemeList : ITheme
                            if (vectorLayer != null && vectorLayer.Themes != null && vectorLayer.Themes.Count > 0)
                            {
                                // we need to a case invariant comparison for themeName
                                Dictionary<string, ITheme> themeDict = new Dictionary<string, ITheme>(vectorLayer.Themes, new StringComparerIgnoreCase());

                                if (!themeDict.ContainsKey(themeName))
                                    throw new WmsStyleNotDefinedException("Style not advertised for this layer");
                                vectorLayer.Theme = themeDict[themeName];
                            }
                        }
                    }

                    if (!String.IsNullOrEmpty(cqlFilter))
                        ApplyCqlFilter(cqlFilter, layer);
                }

            }
            // render map
            Image img = map.GetMap();
            return new GetMapResponse(img, imageEncoder);
        }
Exemple #36
0
        private static XmlNode GenerateCapabilityNode(Map map, XmlDocument capabilities, string publicWMSUrl, IContextRequest request)
        {
            string onlineResource;

            if (String.IsNullOrEmpty(publicWMSUrl))
            {
                string port = request.Url.IsDefaultPort ? "" : ":" + request.Url.Port;
                string s    = String.Format("http://{0}{1}{2}", request.Url.Host, port,
                                            request.Url.AbsolutePath);
                onlineResource = request.Encode(s);
            }
            else
            {
                onlineResource = publicWMSUrl;
            }

            XmlNode capabilityNode      = capabilities.CreateNode(XmlNodeType.Element, "Capability", WmsNamespaceUri);
            XmlNode requestNode         = capabilities.CreateNode(XmlNodeType.Element, "Request", WmsNamespaceUri);
            XmlNode getCapabilitiesNode = capabilities.CreateNode(XmlNodeType.Element, "GetCapabilities",
                                                                  WmsNamespaceUri);

            // Set format of supported capabilities mime types (only text/xml supported)
            getCapabilitiesNode.AppendChild(CreateElement("Format", "text/xml", capabilities, WmsNamespaceUri));
            getCapabilitiesNode.AppendChild(GenerateDCPTypeNode(capabilities, onlineResource));
            requestNode.AppendChild(getCapabilitiesNode);
            XmlNode getFeatureInfoNode = capabilities.CreateNode(XmlNodeType.Element, "GetFeatureInfo", WmsNamespaceUri);

            getFeatureInfoNode.AppendChild(CreateElement("Format", "text/plain", capabilities, WmsNamespaceUri));
            getFeatureInfoNode.AppendChild(CreateElement("Format", "text/json", capabilities, WmsNamespaceUri));
            getFeatureInfoNode.AppendChild(GenerateDCPTypeNode(capabilities, onlineResource));
            requestNode.AppendChild(getFeatureInfoNode);
            XmlNode getMapNode = capabilities.CreateNode(XmlNodeType.Element, "GetMap", WmsNamespaceUri);

            // Add supported fileformats. Return the ones that GDI+ supports
            foreach (ImageCodecInfo encoder in ImageCodecInfo.GetImageEncoders())
            {
                getMapNode.AppendChild(CreateElement("Format", encoder.MimeType, capabilities, WmsNamespaceUri));
            }

            getMapNode.AppendChild(GenerateDCPTypeNode(capabilities, onlineResource));

            requestNode.AppendChild(getMapNode);
            capabilityNode.AppendChild(requestNode);
            XmlElement exceptionNode = capabilities.CreateElement("Exception", WmsNamespaceUri);

            exceptionNode.AppendChild(CreateElement("Format", "text/xml", capabilities, WmsNamespaceUri));
            capabilityNode.AppendChild(exceptionNode); // Add supported exception types

            // Build layerlist
            XmlNode layerRootNode = capabilities.CreateNode(XmlNodeType.Element, "Layer", WmsNamespaceUri);

            layerRootNode.AppendChild(CreateElement("Title", "SharpMap", capabilities, WmsNamespaceUri));
            layerRootNode.AppendChild(CreateElement("CRS", "EPSG:" + map.Layers[0].SRID, capabilities, WmsNamespaceUri)); //TODO
            layerRootNode.AppendChild(GenerateBoundingBoxElement(map.GetExtents(), map.Layers[0].SRID, capabilities));

            XmlElement geoBox = capabilities.CreateElement("EX_GeographicBoundingBox", WmsNamespaceUri);
            // Using default values here. TODO: this should be changed when projection library is complete
            const string minX = "-180";
            const string minY = "-90";
            const string maxX = "180";
            const string maxY = "90";

            geoBox.AppendChild(CreateElement("westBoundLongitude", minX, capabilities, WmsNamespaceUri));
            geoBox.AppendChild(CreateElement("southBoundLatitude", minY, capabilities, WmsNamespaceUri));
            geoBox.AppendChild(CreateElement("eastBoundLongitude", maxX, capabilities, WmsNamespaceUri));
            geoBox.AppendChild(CreateElement("northBoundLatitude", maxY, capabilities, WmsNamespaceUri));

            // The above way to respresent the boundingbox is correct and replace the incorrect way below.
            // For downward compatibility I will keep the old code.
            geoBox.Attributes.Append(CreateAttribute("minx", minX, capabilities));
            geoBox.Attributes.Append(CreateAttribute("miny", minY, capabilities));
            geoBox.Attributes.Append(CreateAttribute("maxx", maxX, capabilities));
            geoBox.Attributes.Append(CreateAttribute("maxy", maxY, capabilities));
            layerRootNode.AppendChild(geoBox);

            foreach (ILayer layer in map.Layers)
            {
                XmlNode wmsLayerNode = GetWmsLayerNode(layer, capabilities);
                layerRootNode.AppendChild(wmsLayerNode);
            }

            capabilityNode.AppendChild(layerRootNode);
            return(capabilityNode);
        }
        private static XmlNode GenerateCapabilityNode(Map map, XmlDocument capabilities, string publicWMSUrl, IContextRequest request)
        {
            string OnlineResource = "";

            if (String.IsNullOrEmpty(publicWMSUrl))
            {
                string port = request.Url.IsDefaultPort ? "" : ":" + request.Url.Port;
                string s = String.Format("http://{0}{1}{2}", request.Url.Host, port,
                    request.Url.AbsolutePath);
                OnlineResource = request.Encode(s);
            }
            else OnlineResource = publicWMSUrl;

            XmlNode CapabilityNode = capabilities.CreateNode(XmlNodeType.Element, "Capability", wmsNamespaceURI);
            XmlNode RequestNode = capabilities.CreateNode(XmlNodeType.Element, "Request", wmsNamespaceURI);
            XmlNode GetCapabilitiesNode = capabilities.CreateNode(XmlNodeType.Element, "GetCapabilities",
                                                                  wmsNamespaceURI);
            //Set format of supported capabilities mime types (only text/xml supported)
            GetCapabilitiesNode.AppendChild(CreateElement("Format", "text/xml", capabilities, false, wmsNamespaceURI));
            GetCapabilitiesNode.AppendChild(GenerateDCPTypeNode(capabilities, OnlineResource));
            RequestNode.AppendChild(GetCapabilitiesNode);
            XmlNode GetFeatureInfoNode = capabilities.CreateNode(XmlNodeType.Element, "GetFeatureInfo", wmsNamespaceURI);
            GetFeatureInfoNode.AppendChild(CreateElement("Format", "text/plain", capabilities, false, wmsNamespaceURI));
            GetFeatureInfoNode.AppendChild(CreateElement("Format", "text/json", capabilities, false, wmsNamespaceURI));
            GetFeatureInfoNode.AppendChild(GenerateDCPTypeNode(capabilities, OnlineResource));
            RequestNode.AppendChild(GetFeatureInfoNode);
            XmlNode GetMapNode = capabilities.CreateNode(XmlNodeType.Element, "GetMap", wmsNamespaceURI);
            //Add supported fileformats. Return the ones that GDI+ supports
            foreach (ImageCodecInfo encoder in ImageCodecInfo.GetImageEncoders())
                GetMapNode.AppendChild(CreateElement("Format", encoder.MimeType, capabilities, false, wmsNamespaceURI));

            GetMapNode.AppendChild(GenerateDCPTypeNode(capabilities, OnlineResource));

            RequestNode.AppendChild(GetMapNode);
            CapabilityNode.AppendChild(RequestNode);
            XmlElement exceptionNode = capabilities.CreateElement("Exception", wmsNamespaceURI);
            exceptionNode.AppendChild(CreateElement("Format", "text/xml", capabilities, false, wmsNamespaceURI));
            CapabilityNode.AppendChild(exceptionNode); //Add supported exception types

            //Build layerlist

            XmlNode LayerRootNode = capabilities.CreateNode(XmlNodeType.Element, "Layer", wmsNamespaceURI);
            LayerRootNode.AppendChild(CreateElement("Title", "SharpMap", capabilities, false, wmsNamespaceURI));
            LayerRootNode.AppendChild(CreateElement("CRS", "EPSG:" + map.Layers[0].SRID, capabilities, false,
                                                    wmsNamespaceURI)); //TODO
            LayerRootNode.AppendChild(GenerateBoundingBoxElement(map.GetExtents(), map.Layers[0].SRID, capabilities));
                        
            XmlElement geoBox = capabilities.CreateElement("EX_GeographicBoundingBox", wmsNamespaceURI);

            //Using default values here. This should be changed when projection library is complete
            string minX = "-180";
            string minY = "-90";
            string maxX = "180";
            string maxY = "90";

            geoBox.AppendChild(CreateElement("westBoundLongitude", minX, capabilities, false, wmsNamespaceURI));
            geoBox.AppendChild(CreateElement("southBoundLatitude", minY, capabilities, false, wmsNamespaceURI));
            geoBox.AppendChild(CreateElement("eastBoundLongitude", maxX, capabilities, false, wmsNamespaceURI));
            geoBox.AppendChild(CreateElement("northBoundLatitude", maxY, capabilities, false, wmsNamespaceURI));

            //The above way to respresent the boundingbox is correct and replace the incorrect way below. 
            //For downward compatibility I will keep the old code.
            geoBox.Attributes.Append(CreateAttribute("minx", minX, capabilities));
            geoBox.Attributes.Append(CreateAttribute("miny", minY, capabilities));
            geoBox.Attributes.Append(CreateAttribute("maxx", maxX, capabilities));
            geoBox.Attributes.Append(CreateAttribute("maxy", maxY, capabilities));
            LayerRootNode.AppendChild(geoBox);

            foreach (ILayer layer in map.Layers)
                LayerRootNode.AppendChild(GetWmsLayerNode(layer, capabilities));

            CapabilityNode.AppendChild(LayerRootNode);

            return CapabilityNode;
        }
 protected string GetFixedUrl(IContextRequest request)
 {
     Uri uri = request.Url;
     string absoluteUri = uri.AbsoluteUri;
     return uri.Query.Length <= 0 ? absoluteUri : absoluteUri.Replace(uri.Query, String.Empty);
 }
Exemple #39
0
        /// <summary>
        /// Validate common arguments for GetFeatureInfo and GetMap requests
        /// </summary>
        protected WmsParams ValidateCommons(IContextRequest request, int targetSrid)
        {
            string version = request.GetParam("VERSION");

            if (version == null)
            {
                throw new WmsParameterNotSpecifiedException("VERSION");
            }
            if (!String.Equals(version, "1.3.0", Case))
            {
                throw new WmsInvalidParameterException("Only version 1.3.0 supported");
            }
            string layers = request.GetParam("LAYERS");

            if (layers == null)
            {
                throw new WmsParameterNotSpecifiedException("LAYERS");
            }
            string styles = request.GetParam("STYLES");

            if (styles == null)
            {
                throw new WmsParameterNotSpecifiedException("STYLES");
            }
            string crs = request.GetParam("CRS");

            if (crs == null)
            {
                throw new WmsParameterNotSpecifiedException("CRS");
            }
            if (crs != "EPSG:" + targetSrid)
            {
                throw new WmsInvalidCRSException("CRS not supported");
            }
            string bbox = request.GetParam("BBOX");

            if (bbox == null)
            {
                throw new WmsParameterNotSpecifiedException("BBOX");
            }
            string width = request.GetParam("WIDTH");

            if (width == null)
            {
                throw new WmsParameterNotSpecifiedException("WIDTH");
            }
            string height = request.GetParam("HEIGHT");

            if (height == null)
            {
                throw new WmsParameterNotSpecifiedException("HEIGHT");
            }
            string format = request.GetParam("FORMAT");

            if (format == null)
            {
                throw new WmsParameterNotSpecifiedException("FORMAT");
            }
            string cqlFilter = request.GetParam("CQL_FILTER");
            short  w, h;

            if (!Int16.TryParse(width, out w) || !Int16.TryParse(height, out h))
            {
                throw new WmsInvalidParameterException("Invalid parameters for HEIGHT or WITDH");
            }
            Envelope env = ParseBBOX(bbox, targetSrid == 4326);

            if (env == null)
            {
                throw new WmsInvalidBboxException(bbox);
            }

            return(new WmsParams
            {
                Layers = layers,
                Styles = styles,
                CRS = crs,
                BBOX = env,
                Width = w,
                Height = h,
                Format = format,
                CqlFilter = cqlFilter
            });
        }
Exemple #40
0
 protected abstract WmsParams ValidateParams(IContextRequest request, int targetSrid);
Exemple #41
0
 public abstract IHandlerResponse Handle(Map map, IContextRequest request);
Exemple #42
0
        /// <summary>
        /// Generates a capabilities file from a map object for use in WMS services
        /// </summary>
        /// <remarks>The capabilities document uses the v1.3.0 OpenGIS WMS specification</remarks>
        /// <param name="map">The map to create capabilities for</param>
        /// <param name="serviceDescription">Additional description of WMS</param>
        /// <param name="request">An abstraction of the <see cref="HttpContext"/> request</param>
        /// <returns>Returns XmlDocument describing capabilities</returns>
        public static XmlDocument GetCapabilities(Map map, WmsServiceDescription serviceDescription, IContextRequest request)
        {
            XmlDocument capabilities = new XmlDocument();


            //Set XMLSchema
            //capabilities.Schemas.Add(GetCapabilitiesSchema());

            //Instantiate an XmlNamespaceManager object.
            //System.Xml.XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager(capabilities.NameTable);
            //xmlnsManager.AddNamespace(xlinkNamespaceURI, "urn:Books");

            //Insert XML tag
            capabilities.InsertBefore(capabilities.CreateXmlDeclaration("1.0", "UTF-8", string.Empty),
                                      capabilities.DocumentElement);
            capabilities.AppendChild(
                capabilities.CreateComment("Capabilities generated by SharpMap v. " +
                                           Assembly.GetExecutingAssembly().GetName().Version));
            //Create root node
            XmlNode RootNode = capabilities.CreateNode(XmlNodeType.Element, "WMS_Capabilities", wmsNamespaceURI);

            RootNode.Attributes.Append(CreateAttribute("version", "1.3.0", capabilities));

            XmlAttribute attr = capabilities.CreateAttribute("xmlns", "xsi", "http://www.w3.org/2000/xmlns/");

            attr.InnerText = "http://www.w3.org/2001/XMLSchema-instance";
            RootNode.Attributes.Append(attr);

            RootNode.Attributes.Append(CreateAttribute("xmlns:xlink", xlinkNamespaceURI, capabilities));
            XmlAttribute attr2 = capabilities.CreateAttribute("xsi", "schemaLocation",
                                                              "http://www.w3.org/2001/XMLSchema-instance");

            attr2.InnerText = "http://schemas.opengis.net/wms/1.3.0/capabilities_1_3_0.xsd";
            RootNode.Attributes.Append(attr2);

            //Build Service node
            RootNode.AppendChild(GenerateServiceNode(ref serviceDescription, capabilities));

            //Build Capability node
            XmlNode capabilityNode = GenerateCapabilityNode(map, capabilities, serviceDescription.PublicAccessURL, request);

            RootNode.AppendChild(capabilityNode);

            capabilities.AppendChild(RootNode);

            //TODO: Validate output against schema

            return(capabilities);
        }
Exemple #43
0
        /// <summary>
        /// Generates a capabilities file from a map object for use in WMS services
        /// </summary>
        /// <remarks>The capabilities document uses the v1.3.0 OpenGIS WMS specification</remarks>
        /// <param name="map">The map to create capabilities for</param>
        /// <param name="description">Additional description of WMS</param>
        /// <param name="request">An abstraction of the <see cref="HttpContext"/> request</param>
        /// <returns>Returns XmlDocument describing capabilities</returns>
        public static XmlDocument GetCapabilities(Map map, WmsServiceDescription description, IContextRequest request)
        {
            XmlDocument capabilities = new XmlDocument();

            // Insert XML tag
            capabilities.InsertBefore(capabilities.CreateXmlDeclaration("1.0", "UTF-8", String.Empty), capabilities.DocumentElement);
            string format = String.Format("Capabilities generated by SharpMap v. {0}", Assembly.GetExecutingAssembly().GetName().Version);

            capabilities.AppendChild(capabilities.CreateComment(format));

            // Create root node
            XmlNode rootNode = capabilities.CreateNode(XmlNodeType.Element, "WMS_Capabilities", WmsNamespaceUri);

            rootNode.Attributes.Append(CreateAttribute("version", "1.3.0", capabilities));

            XmlAttribute attr = capabilities.CreateAttribute("xmlns", "xsi", "http://www.w3.org/2000/xmlns/");

            attr.InnerText = "http://www.w3.org/2001/XMLSchema-instance";
            rootNode.Attributes.Append(attr);

            rootNode.Attributes.Append(CreateAttribute("xmlns:xlink", XlinkNamespaceUri, capabilities));
            XmlAttribute attr2 = capabilities.CreateAttribute("xsi", "schemaLocation",
                                                              "http://www.w3.org/2001/XMLSchema-instance");

            attr2.InnerText = "http://schemas.opengis.net/wms/1.3.0/capabilities_1_3_0.xsd";
            rootNode.Attributes.Append(attr2);

            // Build Service node
            rootNode.AppendChild(GenerateServiceNode(ref description, capabilities));

            // Build Capability node
            XmlNode capabilityNode = GenerateCapabilityNode(map, capabilities, description.PublicAccessURL, request);

            rootNode.AppendChild(capabilityNode);

            capabilities.AppendChild(rootNode);

            //TODO: Validate output against schema
            return(capabilities);
        }
Exemple #44
0
        /// <summary>
        /// Generates a WMS 1.3.0 compliant response based on a <see cref="SharpMap.Map"/> and the current HttpRequest.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The Web Map Server implementation in SharpMap requires v1.3.0 compatible clients,
        /// and support the basic operations "GetCapabilities" and "GetMap"
        /// as required by the WMS v1.3.0 specification. SharpMap does not support the optional
        /// GetFeatureInfo operation for querying.
        /// </para>
        /// <example>
        /// Creating a WMS server in ASP.NET is very simple using the classes in the SharpMap.Web.Wms namespace.
        /// <code lang="C#">
        /// void page_load(object o, EventArgs e)
        /// {
        ///		//Get the path of this page
        ///		string url = (Request.Url.Query.Length>0?Request.Url.AbsoluteUri.Replace(Request.Url.Query,""):Request.Url.AbsoluteUri);
        ///		SharpMap.Web.Wms.Capabilities.WmsServiceDescription description =
        ///			new SharpMap.Web.Wms.Capabilities.WmsServiceDescription("Acme Corp. Map Server", url);
        ///
        ///		// The following service descriptions below are not strictly required by the WMS specification.
        ///
        ///		// Narrative description and keywords providing additional information
        ///		description.Abstract = "Map Server maintained by Acme Corporation. Contact: [email protected]. High-quality maps showing roadrunner nests and possible ambush locations.";
        ///		description.Keywords.Add("bird");
        ///		description.Keywords.Add("roadrunner");
        ///		description.Keywords.Add("ambush");
        ///
        ///		//Contact information
        ///		description.ContactInformation.PersonPrimary.Person = "John Doe";
        ///		description.ContactInformation.PersonPrimary.Organisation = "Acme Inc";
        ///		description.ContactInformation.Address.AddressType = "postal";
        ///		description.ContactInformation.Address.Country = "Neverland";
        ///		description.ContactInformation.VoiceTelephone = "1-800-WE DO MAPS";
        ///		//Impose WMS constraints
        ///		description.MaxWidth = 1000; //Set image request size width
        ///		description.MaxHeight = 500; //Set image request size height
        ///
        ///		//Call method that sets up the map
        ///		//We just add a dummy-size, since the wms requests will set the image-size
        ///		SharpMap.Map myMap = MapHelper.InitializeMap(new System.Drawing.Size(1,1));
        ///
        ///		//Parse the request and create a response
        ///		SharpMap.Web.Wms.WmsServer.ParseQueryString(myMap,description);
        /// }
        /// </code>
        /// </example>
        /// </remarks>
        /// <param name="map">Map to serve on WMS</param>
        /// <param name="description">Description of map service</param>
        /// <param name="context">The context the <see cref="WmsServer"/> is running in.</param>
        public static void ParseQueryString(Map map, Capabilities.WmsServiceDescription description, IContext context)
        {
            const StringComparison @case    = StringComparison.InvariantCultureIgnoreCase;
            IContextRequest        request  = context.Request;
            IContextResponse       response = context.Response;

            try
            {
                if (PixelSensitivity < 0)
                {
                    PixelSensitivity = 1;
                }
                if (map == null)
                {
                    throw new WmsArgumentException("Map for WMS is null");
                }
                if (map.Layers.Count == 0)
                {
                    throw new WmsArgumentException("Map doesn't contain any layers for WMS service");
                }

                string req = request.GetParam("REQUEST");
                if (req == null)
                {
                    throw new WmsParameterNotSpecifiedException("REQUEST");
                }

                IHandler handler;
                if (String.Equals(req, "GetCapabilities", @case))
                {
                    handler = new GetCapabilities(description);
                }
                else if (String.Equals(req, "GetFeatureInfo", @case))
                {
                    // use text/plain as default handler
                    // let the default handler validate params
                    string format = request.GetParam("INFO_FORMAT") ?? String.Empty;
                    GetFeatureInfoParams @params = new GetFeatureInfoParams(PixelSensitivity,
                                                                            IntersectDelegate, FeatureInfoResponseEncoding);
                    if (String.Equals(format, "text/json", @case))
                    {
                        handler = new GetFeatureInfoJson(description, @params);
                    }
                    else if (String.Equals(format, "text/html", @case))
                    {
                        handler = new GetFeatureInfoHtml(description, @params);
                    }
                    else
                    {
                        handler = new GetFeatureInfoPlain(description, @params);
                    }
                }
                else if (String.Equals(req, "GetMap", @case))
                {
                    handler = new GetMap(description);
                }
                else
                {
                    string s = String.Format("Invalid request: {0}", req);
                    throw new WmsOperationNotSupportedException(s);
                }

                IHandlerResponse result = handler.Handle(map, request);
                result.WriteToContextAndFlush(response);
            }
            catch (WmsExceptionBase ex)
            {
                ex.WriteToContextAndFlush(response);
            }
        }