private static void Run(IReadOnlyList <string> args) { switch (args[0].ToLower()) { case "sync": SetSyncVariables(args); SynchronizeSubscribedDatasets(); break; case "add": SetAddVariables(args); GetCapabilities.Run(); break; default: WriteHelp(); break; } }
public async Task <ActionResult> GetCapabilities(string serviceName, string version) { GetCapabilities getCapabilities = new GetCapabilities(version); ContentResult result = await GetCapabilities(serviceName, getCapabilities); return(result); }
private void btnCapabilitesFile_Click(object sender, EventArgs e) { // use a file to fill the capabilites text box GetCapabilities.ShowDialog(); string capabilitiesFile = GetCapabilities.FileName; // read file into text box txtCapabilities.Text = File.ReadAllText(capabilitiesFile); }
public void ToKeyValuePairs_ShouldEncodeDefault() { var request=new GetCapabilities(); var result = ( (Ows.IRequest)request ).ToKeyValuePairs(); Assert.Contains( "request", result.Cast<string>() ); Assert.Equal("GetCapabilities", result["request"]); Assert.Contains( "service", result.Cast<string>() ); Assert.Equal("CSW", result["service"]); }
public void ToKeyValuePairs_ShouldEncodeDefault() { var request = new GetCapabilities(); var result = ((Ows.IRequest)request).ToKeyValuePairs(); Assert.Contains("request", result.Cast <string>()); Assert.Equal("GetCapabilities", result["request"]); Assert.Contains("service", result.Cast <string>()); Assert.Equal("CSW", result["service"]); }
public async Task <ActionResult> GetCapabilities(string serviceName, string version) { GetCapabilities getCapabilities = new GetCapabilities(); if (!string.IsNullOrEmpty(version)) { getCapabilities.AcceptVersions = new string[] { version }; } ContentResult result = await GetCapabilities(serviceName, getCapabilities); return(result); }
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"); 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); }); }
public virtual Capabilities GetCapabilities(string path, GetCapabilities getCapabilities) { Capabilities capabilities = null; if (!File.Exists(path) || getCapabilities?.service != Service || getCapabilities.AcceptVersions == null || !getCapabilities.AcceptVersions.Contains(Version)) { return(capabilities); } try { XmlSerializer serializer = GetXmlSerializer(typeof(Capabilities)); using (FileStream fs = File.OpenRead(path)) { capabilities = (Capabilities)serializer.Deserialize(fs); fs.Close(); } } catch { } return(capabilities); }
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); }); }
/// <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="pixelSensitivity">Tolerance for GetFeatureInfo requests</param> ///<param name="intersectDelegate">Delegate for Getfeatureinfo intersecting, when null, the WMS will default to ICanQueryLayer implementation</param> public static void ParseQueryString(Map map, Capabilities.WmsServiceDescription description, int pixelSensitivity, InterSectDelegate intersectDelegate) { _pixelSensitivity = pixelSensitivity; _intersectDelegate = intersectDelegate; if (map == null) { throw (new ArgumentException("Map for WMS is null")); } if (map.Layers.Count == 0) { throw (new ArgumentException("Map doesn't contain any layers for WMS service")); } if (HttpContext.Current == null) { throw new ApplicationException("An attempt was made to access the WMS server outside a valid HttpContext"); } HttpContext context = HttpContext.Current; //IgnoreCase value should be set according to the VERSION parameter //v1.3.0 is case sensitive, but since it causes a lot of problems with several WMS clients, we ignore casing anyway. const bool ignorecase = true; //Collect parameters string request = context.Request.Params["REQUEST"]; string version = context.Request.Params["VERSION"]; //Check for required parameters //Request parameter is mandatory if (request == null) { WmsException.ThrowWmsException("Required parameter REQUEST not specified"); return; } //Check if version is supported if (version != null) { if (String.Compare(version, "1.3.0", ignorecase) != 0) { WmsException.ThrowWmsException("Only version 1.3.0 supported"); return; } } else { //Version is mandatory if REQUEST!=GetCapabilities. Check if this is a capabilities request, since VERSION is null if (String.Compare(request, "GetCapabilities", ignorecase) != 0) { WmsException.ThrowWmsException("VERSION parameter not supplied"); return; } } HandlerParams @params = new HandlerParams(context, map, description, ignorecase); GetFeatureInfoParams infoParams = new GetFeatureInfoParams(_pixelSensitivity, _intersectDelegate); IWmsHandler handler = null; if (String.Compare(request, "GetCapabilities", ignorecase) == 0) { handler = new GetCapabilities(@params); } else if (String.Compare(request, "GetFeatureInfo", ignorecase) == 0) { handler = new GetFeatureInfo(@params, infoParams); } else if (String.Compare(request, "GetMap", ignorecase) == 0) { handler = new GetMap(@params); } if (handler == null) { WmsException.ThrowWmsException( WmsException.WmsExceptionCode.OperationNotSupported, String.Format("Invalid request: {0}", request)); } else { handler.Handle(); } }
private async Task <ContentResult> GetCapabilities(string serviceName, GetCapabilities getCapabilities) { ContentResult result = new ContentResult() { ContentType = "application/xml" }; int statusCode = 200; ExceptionReport exception = null; if (string.IsNullOrWhiteSpace(serviceName)) { exception = ExceptionReportHelper.GetExceptionReport("MissingParameterValue", "serviceName", exceptionText: "Bad request"); statusCode = 400; goto Exception; } string version = null; if (getCapabilities.AcceptVersions?.Length > 0) { version = getCapabilities.AcceptVersions[0]; } if (string.IsNullOrWhiteSpace(version)) { exception = ExceptionReportHelper.GetExceptionReport("MissingParameterValue", "version", exceptionText: "Bad request"); statusCode = 400; goto Exception; } if (version != "1.0.0") { exception = ExceptionReportHelper.GetExceptionReport("InvalidParameterValue", "version", exceptionText: "Bad request"); statusCode = 400; goto Exception; } ServiceRecord serviceRecord = await GetServiceRecord(serviceName, version); if (serviceRecord == null) { exception = ExceptionReportHelper.GetExceptionReport("InvalidParameterValue", exceptionText: "Bad request"); statusCode = 400; goto Exception; } if (!System.IO.File.Exists(serviceRecord.Path)) { exception = ExceptionReportHelper.GetExceptionReport("NoApplicableCode", exceptionText: "Internal server error"); statusCode = 500; goto Exception; } IWmtsService wmts1Service = GetWmts1Service(version); Capabilities capabilities = wmts1Service.GetCapabilities(serviceRecord.Path, getCapabilities); if (getCapabilities.AcceptFormats?.Length > 0) { result.ContentType = getCapabilities.AcceptFormats[0].Trim(); } StringBuilder sb = new StringBuilder(); using (StringWriter sw = new StringWriter(sb)) { wmts1Service.XmlSerialize(sw, capabilities); sw.Close(); } result.Content = sb.ToString(); goto Success; Exception: result.Content = XmlHelper.XmlSerialize(exception, Encoding, null); Success: result.StatusCode = statusCode; return(result); }
private async Task <ContentResult> GetFeatureInfo(string serviceName, GetFeatureInfo getFeatureInfo) { GetTile getTile = getFeatureInfo.GetTile; string content = null; ExceptionReport exception = null; int statusCode = 200; #region Validate parameters if (string.IsNullOrWhiteSpace(serviceName)) { exception = ExceptionReportHelper.GetExceptionReport("MissingParameterValue", "serviceName", exceptionText: "Bad request"); statusCode = 400; goto Exception; } string serviceType = getTile.service; if (string.IsNullOrWhiteSpace(serviceType)) { exception = ExceptionReportHelper.GetExceptionReport("MissingParameterValue", "service", exceptionText: "Bad request"); statusCode = 400; goto Exception; } if (serviceType != "wmts") { exception = ExceptionReportHelper.GetExceptionReport("InvalidParameterValue", "version", exceptionText: "Bad request"); statusCode = 400; goto Exception; } string version = getTile.version; if (string.IsNullOrWhiteSpace(version)) { exception = ExceptionReportHelper.GetExceptionReport("MissingParameterValue", "version", exceptionText: "Bad request"); statusCode = 400; goto Exception; } if (version != "1.0.0") { exception = ExceptionReportHelper.GetExceptionReport("InvalidParameterValue", "version", exceptionText: "Bad request"); statusCode = 400; goto Exception; } string layerName = getTile.Layer; if (string.IsNullOrWhiteSpace(layerName)) { exception = ExceptionReportHelper.GetExceptionReport("MissingParameterValue", "layer", exceptionText: "Bad request"); statusCode = 400; goto Exception; } string style = getTile.Style; if (string.IsNullOrWhiteSpace(style)) { exception = ExceptionReportHelper.GetExceptionReport("MissingParameterValue", "style", exceptionText: "Bad request"); statusCode = 400; goto Exception; } string format = getTile.Format; if (string.IsNullOrWhiteSpace(format)) { exception = ExceptionReportHelper.GetExceptionReport("MissingParameterValue", "format", exceptionText: "Bad request"); statusCode = 400; goto Exception; } string tileMatrixSet = getTile.TileMatrixSet; if (string.IsNullOrWhiteSpace(tileMatrixSet)) { exception = ExceptionReportHelper.GetExceptionReport("MissingParameterValue", "tileMatrixSet", exceptionText: "Bad request"); statusCode = 400; goto Exception; } string tileMatrix = getTile.TileMatrix; if (string.IsNullOrWhiteSpace(tileMatrix)) { exception = ExceptionReportHelper.GetExceptionReport("MissingParameterValue", "tileMatrix", exceptionText: "Bad request"); statusCode = 400; goto Exception; } ServiceRecord serviceRecord = await GetServiceRecord(serviceName, version); if (serviceRecord == null) { exception = ExceptionReportHelper.GetExceptionReport("InvalidParameterValue", exceptionText: "Bad request"); statusCode = 400; goto Exception; } if (!System.IO.File.Exists(serviceRecord.Path)) { exception = ExceptionReportHelper.GetExceptionReport("NoApplicableCode", exceptionText: "Internal server error"); statusCode = 500; goto Exception; } LayerRecord layerRecord = await GetLayerRecord(serviceRecord, layerName); if (layerRecord == null) { exception = ExceptionReportHelper.GetExceptionReport("InvalidParameterValue", exceptionText: "Bad request"); statusCode = 400; goto Exception; } if (!System.IO.File.Exists(layerRecord.Path)) { exception = ExceptionReportHelper.GetExceptionReport("NoApplicableCode", exceptionText: "Internal server error"); statusCode = 500; goto Exception; } #endregion GetCapabilities getCapabilities = new GetCapabilities(); IWmtsService wmts1Service = GetWmts1Service(version); Capabilities capabilities = wmts1Service.GetCapabilities(serviceRecord.Path, getCapabilities); if (capabilities == null) { exception = ExceptionReportHelper.GetExceptionReport("NoApplicableCode", exceptionText: "Internal server error"); statusCode = 500; goto Exception; } LayerType layerType = capabilities.Contents?.DatasetDescriptionSummary?.FirstOrDefault(x => x.Identifier?.Value == layerName && x is LayerType) as LayerType; if (layerType == null) { exception = ExceptionReportHelper.GetExceptionReport("NoApplicableCode", exceptionText: "Internal server error"); statusCode = 500; goto Exception; } if (!layerType.Format.Contains(format)) { exception = ExceptionReportHelper.GetExceptionReport("InvalidParameterValue", "format", exceptionText: "Bad request"); statusCode = 400; goto Exception; } if (layerType.TileMatrixSetLink == null || layerType.TileMatrixSetLink.Length == 0) { exception = ExceptionReportHelper.GetExceptionReport("NoApplicableCode", exceptionText: "Internal server error"); statusCode = 500; goto Exception; } string layerTileMatrixSetStr = layerType.TileMatrixSetLink[0].TileMatrixSet; if (layerTileMatrixSetStr != null) { TileMatrixSet layerTileMatrixSet = capabilities.Contents.TileMatrixSet?.FirstOrDefault(x => x.Identifier?.Value == layerTileMatrixSetStr); if (layerTileMatrixSet != null) { TileMatrix layerTileMatrix = layerTileMatrixSet.TileMatrix?.FirstOrDefault(x => x.Identifier.Value == getTile.TileMatrix); if (layerTileMatrix != null) { bool ret = layerTileMatrix.TopLeftCorner.ToPosition(out double left, out double top); if (!ret) { exception = ExceptionReportHelper.GetExceptionReport("NoApplicableCode", exceptionText: "Internal server error"); statusCode = 500; goto Exception; } BoundingBoxType boundingBoxType = layerType.BoundingBox?.Length > 0 ? layerType.BoundingBox[0] : layerType.WGS84BoundingBox?.Length > 0 ? layerType.WGS84BoundingBox[0] : null; if (boundingBoxType == null) { exception = ExceptionReportHelper.GetExceptionReport("NoApplicableCode", exceptionText: "Internal server error"); statusCode = 500; goto Exception; } bool ret1 = boundingBoxType.LowerCorner.ToPosition(out double xMin, out double yMin); bool ret2 = boundingBoxType.UpperCorner.ToPosition(out double xMax, out double yMax); if (!ret1 || !ret2) { exception = ExceptionReportHelper.GetExceptionReport("NoApplicableCode", exceptionText: "Internal server error"); statusCode = 500; goto Exception; } double tileXMin = 0, tileYMin = 0, tileXMax = 0, tileYMax = 0; int tileWidth = Convert.ToInt32(layerTileMatrix.TileWidth); int tileHeight = Convert.ToInt32(layerTileMatrix.TileHeight); tileXMin = left + getTile.TileCol * tileWidth * layerTileMatrix.ScaleDenominator; tileXMax = left + (getTile.TileCol + 1) * tileWidth * layerTileMatrix.ScaleDenominator; tileYMax = top - getTile.TileRow * tileHeight * layerTileMatrix.ScaleDenominator; tileYMin = top - (getTile.TileRow + 1) * tileHeight * layerTileMatrix.ScaleDenominator; if (tileXMax <= xMin || tileXMin >= xMax || tileYMax <= yMin || tileYMin >= yMax) { exception = ExceptionReportHelper.GetExceptionReport("TileOutOfRange", exceptionText: "Bad request"); statusCode = 400; goto Exception; } if (getFeatureInfo.I < 0 || getFeatureInfo.I >= tileWidth || getFeatureInfo.J < 0 || getFeatureInfo.J >= tileHeight) { exception = ExceptionReportHelper.GetExceptionReport("PointIJOutOfRange", exceptionText: "Bad request"); statusCode = 400; goto Exception; } } } } FeatureInfoResponse featureInfoResponse = wmts1Service.GetFeatureInfo(serviceRecord.Path, getFeatureInfo); content = XmlHelper.XmlSerialize(featureInfoResponse, Encoding, null); goto Success; Exception: content = XmlHelper.XmlSerialize(exception, Encoding, null); Success: ContentResult result = new ContentResult() { StatusCode = statusCode, Content = content }; return(result); }
internal void Init(string CapabilitiesString, WFSDataset wfsDataset) { try { _themes = new List <IWebServiceTheme>(); XmlDocument doc = new XmlDocument(); doc.LoadXml(CapabilitiesString); XmlNode CapabilitiesNode = doc.SelectSingleNode("WMT_MS_Capabilities/Capability"); _getCapabilities = new GetCapabilities(CapabilitiesNode.SelectSingleNode("Request/GetCapabilities")); _getMap = new GetMap(CapabilitiesNode.SelectSingleNode("Request/GetMap")); _getFeatureInfo = new GetFeatureInfo(CapabilitiesNode.SelectSingleNode("Request/GetFeatureInfo")); _describeLayer = new DescribeLayer(CapabilitiesNode.SelectSingleNode("Request/DescribeLayer")); _getLegendGraphic = new GetLegendGraphic(CapabilitiesNode.SelectSingleNode("Request/GetLegendGraphic")); _getStyles = new GetStyles(CapabilitiesNode.SelectSingleNode("Request/GetStyles")); _exceptions = new WMSExceptions(CapabilitiesNode.SelectSingleNode("Exception")); _userDefinedSymbolization = new UserDefinedSymbolization(CapabilitiesNode.SelectSingleNode("UserDefinedSymbolization")); XmlNode service = CapabilitiesNode.SelectSingleNode("Layer"); XmlNode title = service.SelectSingleNode("Title"); if (title != null) { _name = title.InnerText; } _srs = new SRS(service); this.SRSCode = _srs.Srs[_srs.SRSIndex]; foreach (XmlNode layer in service.SelectNodes("Layer")) { string name = "", Title = ""; XmlNode nameNode = layer.SelectSingleNode("Name"); XmlNode titleNode = layer.SelectSingleNode("Title"); if (nameNode == null) { continue; } name = Title = nameNode.InnerText; if (titleNode != null) { Title = titleNode.InnerText; } XmlNodeList styles = layer.SelectNodes("Style"); WFSFeatureClass wfsFc = null; if (wfsDataset != null) { IDatasetElement wfsElement = wfsDataset[name]; if (wfsElement != null && wfsElement.Class is WFSFeatureClass) { wfsFc = wfsElement.Class as WFSFeatureClass; } } if (styles.Count == 0) { IClass wClass = null; if (wfsFc != null) { wClass = wfsFc; } else if (layer.Attributes["queryable"] != null && layer.Attributes["queryable"].Value == "1") { wClass = new WMSQueryableThemeClass(_dataset, name, String.Empty, layer, _getFeatureInfo, _srs, _exceptions); } else { wClass = new WMSThemeClass(_dataset, name, String.Empty, layer); } IWebServiceTheme theme; if (wClass is WFSFeatureClass) { theme = new WebServiceTheme2( wClass, Title, name, true, this); } else { theme = new WebServiceTheme( wClass, Title, name, true, this ); } _themes.Add(theme); } else { foreach (XmlNode style in styles) { string sName = "", sTitle = ""; XmlNode sNameNode = style.SelectSingleNode("Name"); XmlNode sTitleNode = style.SelectSingleNode("Title"); if (sNameNode == null) { continue; } sName = sTitle = sNameNode.InnerText; if (sTitleNode != null) { sTitle = sTitleNode.InnerText; } IClass wClass = null; if (wfsFc is WFSFeatureClass) { wClass = wfsFc; ((WFSFeatureClass)wClass).Style = sName; } else if (layer.Attributes["queryable"] != null && layer.Attributes["queryable"].Value == "1") { wClass = new WMSQueryableThemeClass(_dataset, name, sName, layer, _getFeatureInfo, _srs, _exceptions); } else { wClass = new WMSThemeClass(_dataset, name, sName, layer); } IWebServiceTheme theme; if (wClass is WFSFeatureClass) { theme = new WebServiceTheme2( wClass, Title + " (Style=" + sTitle + ")", name, true, this); } else { theme = new WebServiceTheme( wClass, Title + " (Style=" + sTitle + ")", name, true, this ); } _themes.Add(theme); } } } doc = null; } catch (Exception ex) { string errMsg = ex.Message; } }
public XRootNamespace(GetCapabilities root) { this.doc=new XDocument(root.Untyped); this.rootObject=root; }
private async Task <ActionResult> GetTile(string serviceName, GetTile getTile) { ActionResult result = null; ExceptionReport exception = null; int statusCode = 200; #region Validate parameters if (string.IsNullOrWhiteSpace(serviceName)) { exception = ExceptionReportHelper.GetExceptionReport("MissingParameterValue", "serviceName", exceptionText: "Bad request"); statusCode = 400; goto Exception; } string serviceType = getTile.service; if (string.IsNullOrWhiteSpace(serviceType)) { exception = ExceptionReportHelper.GetExceptionReport("MissingParameterValue", "service", exceptionText: "Bad request"); statusCode = 400; goto Exception; } if (serviceType.ToLower() != "wmts") { exception = ExceptionReportHelper.GetExceptionReport("InvalidParameterValue", "version", exceptionText: "Bad request"); statusCode = 400; goto Exception; } string version = getTile.version; if (string.IsNullOrWhiteSpace(version)) { exception = ExceptionReportHelper.GetExceptionReport("MissingParameterValue", "version", exceptionText: "Bad request"); statusCode = 400; goto Exception; } if (version != "1.0.0") { exception = ExceptionReportHelper.GetExceptionReport("InvalidParameterValue", "version", exceptionText: "Bad request"); statusCode = 400; goto Exception; } string layerName = getTile.Layer; if (string.IsNullOrWhiteSpace(layerName)) { exception = ExceptionReportHelper.GetExceptionReport("MissingParameterValue", "layer", exceptionText: "Bad request"); statusCode = 400; goto Exception; } string style = getTile.Style; if (string.IsNullOrWhiteSpace(style)) { exception = ExceptionReportHelper.GetExceptionReport("MissingParameterValue", "style", exceptionText: "Bad request"); statusCode = 400; goto Exception; } string format = getTile.Format; if (string.IsNullOrWhiteSpace(format)) { exception = ExceptionReportHelper.GetExceptionReport("MissingParameterValue", "format", exceptionText: "Bad request"); statusCode = 400; goto Exception; } string tileMatrixSet = getTile.TileMatrixSet; if (string.IsNullOrWhiteSpace(tileMatrixSet)) { exception = ExceptionReportHelper.GetExceptionReport("MissingParameterValue", "tileMatrixSet", exceptionText: "Bad request"); statusCode = 400; goto Exception; } string tileMatrix = getTile.TileMatrix; if (string.IsNullOrWhiteSpace(tileMatrix)) { exception = ExceptionReportHelper.GetExceptionReport("MissingParameterValue", "tileMatrix", exceptionText: "Bad request"); statusCode = 400; goto Exception; } ServiceRecord serviceRecord = await GetServiceRecord(serviceName, version); if (serviceRecord == null) { exception = ExceptionReportHelper.GetExceptionReport("InvalidParameterValue", exceptionText: "Bad request"); statusCode = 400; goto Exception; } if (!System.IO.File.Exists(serviceRecord.Path)) { exception = ExceptionReportHelper.GetExceptionReport("NoApplicableCode", exceptionText: "Internal server error"); statusCode = 500; goto Exception; } LayerRecord layerRecord = await GetLayerRecord(serviceRecord, layerName); if (layerRecord == null) { exception = ExceptionReportHelper.GetExceptionReport("InvalidParameterValue", exceptionText: "Bad request"); statusCode = 400; goto Exception; } #endregion GetCapabilities getCapabilities = new GetCapabilities(version); IWmtsService wmts1Service = GetWmts1Service(version); Capabilities capabilities = wmts1Service.GetCapabilities(serviceRecord.Path, getCapabilities); if (capabilities == null) { exception = ExceptionReportHelper.GetExceptionReport("NoApplicableCode", exceptionText: "Internal server error"); statusCode = 500; goto Exception; } LayerType layerType = capabilities.GetLayerType(layerRecord.Name); if (layerType == null) { exception = ExceptionReportHelper.GetExceptionReport("NoApplicableCode", exceptionText: "Internal server error"); statusCode = 500; goto Exception; } if (!layerType.Format.Contains(format)) { exception = ExceptionReportHelper.GetExceptionReport("InvalidParameterValue", "format", exceptionText: "Bad request"); statusCode = 400; goto Exception; } if (layerType.TileMatrixSetLink == null || layerType.TileMatrixSetLink.Length == 0) { exception = ExceptionReportHelper.GetExceptionReport("NoApplicableCode", exceptionText: "Internal server error"); statusCode = 500; goto Exception; } string layerTileMatrixSetStr = layerType.TileMatrixSetLink[0].TileMatrixSet; if (layerTileMatrixSetStr != null) { TileMatrixSet layerTileMatrixSet = capabilities.Contents.TileMatrixSet?.FirstOrDefault(x => x.Identifier?.Value == layerTileMatrixSetStr); if (layerTileMatrixSet != null) { TileMatrix layerTileMatrix = layerTileMatrixSet.TileMatrix?.FirstOrDefault(x => x.Identifier.Value == getTile.TileMatrix); if (layerTileMatrix != null) { bool ret = layerTileMatrix.TopLeftCorner.ToPosition(out double left, out double top); if (!ret) { exception = ExceptionReportHelper.GetExceptionReport("NoApplicableCode", exceptionText: "Internal server error"); statusCode = 500; goto Exception; } BoundingBoxType boundingBoxType = layerType.BoundingBox?.Length > 0 ? layerType.BoundingBox[0] : layerType.WGS84BoundingBox?.Length > 0 ? layerType.WGS84BoundingBox[0] : null; if (boundingBoxType == null) { exception = ExceptionReportHelper.GetExceptionReport("NoApplicableCode", exceptionText: "Internal server error"); statusCode = 500; goto Exception; } bool ret0 = boundingBoxType.LowerCorner.ToPosition(out double xMin, out double yMin); bool ret1 = boundingBoxType.UpperCorner.ToPosition(out double xMax, out double yMax); if (!ret0 || !ret1) { exception = ExceptionReportHelper.GetExceptionReport("NoApplicableCode", exceptionText: "Internal server error"); statusCode = 500; goto Exception; } bool isDegree = layerTileMatrixSet.GetIsDegreeByLocalDb(); layerTileMatrix.GetTileIndex(isDegree, xMin, yMax, out int startCol, out int startRow); int matrixWidth = Convert.ToInt32(layerTileMatrix.MatrixWidth); int matrixHeight = Convert.ToInt32(layerTileMatrix.MatrixHeight); if (getTile.TileCol < startCol || getTile.TileCol >= startCol + matrixWidth || getTile.TileRow < startRow || getTile.TileRow >= startRow + matrixHeight) { exception = ExceptionReportHelper.GetExceptionReport("TileOutOfRange", exceptionText: "Bad request"); statusCode = 400; goto Exception; } } } } try { byte[] tileBuffer = wmts1Service.GetTile(capabilities, layerRecord.Path, getTile); result = new FileContentResult(tileBuffer, getTile.Format); } catch (Exception e) { Debug.WriteLine($"获取瓦片{getTile.TileMatrix}_{getTile.TileCol}_{getTile.TileRow}失败:{e.Message}"); } goto Success; Exception: string content = XmlHelper.XmlSerialize(exception, Encoding, null); result = new ContentResult() { StatusCode = statusCode, Content = content }; Success: return(result); }
/// <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); } }
/// <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="pixelSensitivity">Tolerance for GetFeatureInfo requests</param> ///<param name="intersectDelegate">Delegate for Getfeatureinfo intersecting, when null, the WMS will default to ICanQueryLayer implementation</param> public static void ParseQueryString(Map map, Capabilities.WmsServiceDescription description, int pixelSensitivity, InterSectDelegate intersectDelegate) { _pixelSensitivity = pixelSensitivity; _intersectDelegate = intersectDelegate; if (map == null) throw (new ArgumentException("Map for WMS is null")); if (map.Layers.Count == 0) throw (new ArgumentException("Map doesn't contain any layers for WMS service")); if (HttpContext.Current == null) throw new ApplicationException("An attempt was made to access the WMS server outside a valid HttpContext"); HttpContext context = HttpContext.Current; //IgnoreCase value should be set according to the VERSION parameter //v1.3.0 is case sensitive, but since it causes a lot of problems with several WMS clients, we ignore casing anyway. const bool ignorecase = true; //Collect parameters string request = context.Request.Params["REQUEST"]; string version = context.Request.Params["VERSION"]; //Check for required parameters //Request parameter is mandatory if (request == null) { WmsException.ThrowWmsException("Required parameter REQUEST not specified"); return; } //Check if version is supported if (version != null) { if (String.Compare(version, "1.3.0", ignorecase) != 0) { WmsException.ThrowWmsException("Only version 1.3.0 supported"); return; } } else { //Version is mandatory if REQUEST!=GetCapabilities. Check if this is a capabilities request, since VERSION is null if (String.Compare(request, "GetCapabilities", ignorecase) != 0) { WmsException.ThrowWmsException("VERSION parameter not supplied"); return; } } HandlerParams @params = new HandlerParams(context, map, description, ignorecase); GetFeatureInfoParams infoParams = new GetFeatureInfoParams(_pixelSensitivity, _intersectDelegate); IWmsHandler handler = null; if (String.Compare(request, "GetCapabilities", ignorecase) == 0) handler = new GetCapabilities(@params); else if (String.Compare(request, "GetFeatureInfo", ignorecase) == 0) handler = new GetFeatureInfo(@params, infoParams); else if (String.Compare(request, "GetMap", ignorecase) == 0) handler = new GetMap(@params); if (handler == null) { WmsException.ThrowWmsException( WmsException.WmsExceptionCode.OperationNotSupported, String.Format("Invalid request: {0}", request)); } else handler.Handle(); }
public bool Open() { try { _elements.Clear(); string param = "REQUEST=GetCapabilities&VERSION=1.0.0&SERVICE=WFS"; string url = WMSDataset.Append2Url(_url, param); string response = WebFunctions.HttpSendRequest(url, "GET", null); response = WMSDataset.RemoveDOCTYPE(response); XmlDocument doc = new XmlDocument(); doc.LoadXml(response); XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable); ns.AddNamespace("WFS", "http://www.opengis.net/wfs"); ns.AddNamespace("OGC", "http://www.opengis.net/ogc"); ns.AddNamespace("GML", "http://www.opengis.net/gml"); XmlNode CapabilitiesNode = doc.SelectSingleNode("WFS:WFS_Capabilities/WFS:Capability", ns); _getCapabilities = new GetCapabilities(CapabilitiesNode.SelectSingleNode("WFS:Request/WFS:GetCapabilities", ns), ns); _decribeFeatureType = new DescribeFeatureType(CapabilitiesNode.SelectSingleNode("WFS:Request/WFS:DescribeFeatureType", ns), ns); _getFeature = new GetFeature(CapabilitiesNode.SelectSingleNode("WFS:Request/WFS:GetFeature", ns), ns); XmlNode FeatureTypeListNode = doc.SelectSingleNode("WFS:WFS_Capabilities/WFS:FeatureTypeList", ns); _operations = new Operations(FeatureTypeListNode.SelectSingleNode("WFS:Operations", ns)); foreach (XmlNode featureTypeNode in FeatureTypeListNode.SelectNodes("WFS:FeatureType", ns)) { string name = ""; string title = ""; XmlNode nameNode = featureTypeNode.SelectSingleNode("WFS:Name", ns); XmlNode titleNode = featureTypeNode.SelectSingleNode("WFS:Title", ns); WMSClass.SRS srs = new WMSClass.SRS(featureTypeNode, ns, "WFS"); name = title = nameNode.InnerText; if (titleNode != null) { title = titleNode.InnerText; } WFSFeatureClass featureClass = new WFSFeatureClass(this, name, srs); //DatasetElement dselement = new DatasetElement(featureClass); ILayer dselement = LayerFactory.Create(featureClass); if (dselement == null) { continue; } dselement.Title = name; _elements.Add(dselement); } _filter_capabilites = new Filter_Capabilities(doc.SelectSingleNode("WFS:WFS_Capabilities/OGC:Filter_Capabilities", ns), ns); return(true); } catch (Exception ex) { string err = ex.Message; return(false); } }
/// <summary> /// Process operation request /// </summary> /// <param name="request"></param> /// <returns>Resposne object to be sent back to the client</returns> public override OperationResult ProcessRequest(HttpRequest request, OwsRequestBase payload = null) { GetCapabilities getCapabilities = payload as GetCapabilities; // Validate request parameter if (getCapabilities == null) { throw new NoApplicableCodeException(string.Format(CultureInfo.CurrentCulture, "Type '{0}' is invalid request type.", request.GetType().FullName)); } OperationResult result = new OperationResult(request); // TODO: Consider to implement updateSequence as described in OGC 06-121r3 7.3.4 // Validate acceptFormats parameter if (getCapabilities.AcceptFormats != null) { var formats = from sf in this._supportedFormats from af in getCapabilities.AcceptFormats where sf.ToStringValue() == af.Trim() select sf; if (formats.Count() > 0) { result.OutputFormat = formats.First(); } } Capabilities capabilities = new Capabilities(); // Make sure client can accept current version of response if (getCapabilities.AcceptVersions != null && !getCapabilities.AcceptVersions.Contains(capabilities.Version)) { throw new VersionNegotiationException(string.Format(CultureInfo.InvariantCulture, "Only '{0}' version is supported", capabilities.Version)); } // Make sure client can accept current formats if (getCapabilities.AcceptFormats != null) { bool supportedFormatFound = false; foreach (var format in getCapabilities.AcceptFormats) { OutputFormat outputFormat; supportedFormatFound = format.TryParseEnum <OutputFormat>(out outputFormat); if (supportedFormatFound) { break; } } if (!supportedFormatFound) { throw new InvalidParameterValueException("Provided accept formats are not supported"); } } // TODO: updateSequence currently not implemented //capabilities.UpdateSequence = DateTime.UtcNow.ToUnicodeStringValue(); if (getCapabilities.Sections == null || getCapabilities.Sections.Contains("ServiceProvider")) { capabilities.ServiceProvider = this.GetServiceProvider(); } if (getCapabilities.Sections == null || getCapabilities.Sections.Contains("ServiceIdentification")) { capabilities.ServiceIdentification = this.GetServiceIdentification(); } if (getCapabilities.Sections == null || getCapabilities.Sections.Contains("OperationsMetadata")) { capabilities.OperationsMetadata = this.GetOperationsMetadata(this.Accessor, this.Cache, this.ServiceProvider); } if (getCapabilities.Sections == null || getCapabilities.Sections.Contains("ProcessOfferings")) { capabilities.ProcessOfferings = this.GetProcessOfferings(); } if (getCapabilities.Sections == null || getCapabilities.Sections.Contains("Languages")) { capabilities.Languages = this.GetLanguages(); } if (getCapabilities.Sections == null || getCapabilities.Sections.Contains("WSDL")) { capabilities.WSDL = this.GetWSDL(); } result.ResultObject = capabilities; return(result); }