====== Source Code WorldMapWmsService Project Templates Wpf CS.zip ====== ====MapModel.cs==== using System; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Runtime.Serialization.Json; using System.Text; using System.Windows; using System.Windows.Input; using System.Windows.Media.Imaging; using ThinkGeo.MapSuite.Core; using ThinkGeo.MapSuite.WmsServiceClient.Properties; using ThinkGeo.MapSuite.WpfDesktopEdition; namespace ThinkGeo.MapSuite.WmsServiceClient { public class MapModel { private const string packUriFormat = @"pack://application:,,,/MapSuiteWmsServiceClient;component/Image/{0}"; private const string serviceUri = "http://localhost:52289/WmsHandler.axd"; private static Cursor handCursor; private string selectedProjection; private SimpleMarkerOverlay markerOverlay; private WmsOverlay wmsOverlay; private User currentUser; private WpfMap mapControl; private InMemoryFeatureLayer highlightLayer; private PointShape selectedPoint; private Collection projections; static MapModel() { Uri uri = new Uri(string.Format(CultureInfo.InvariantCulture, packUriFormat, "cursor_hand.cur"), UriKind.RelativeOrAbsolute); handCursor = new Cursor(Application.GetResourceStream(uri).Stream); } public MapModel(WpfMap wpfMap) { mapControl = wpfMap; InitializeWmsSettingData(); mapControl.MapUnit = GeographyUnit.DecimalDegree; mapControl.CurrentExtent = new RectangleShape(-170, 70, 170, -70); mapControl.MapTools.Logo.IsEnabled = false; mapControl.MapTools.MouseCoordinate.IsEnabled = true; mapControl.MapTools.MouseCoordinate.Visibility = Visibility.Hidden; mapControl.MapTools.MouseCoordinate.Margin = new Thickness(0, 0, 180, 5); mapControl.MapTools.MouseCoordinate.MouseCoordinateType = MouseCoordinateType.Custom; TrackMode = TrackMode.None; InitializeMapOverlays(); } public WpfMap MapControl { get { return mapControl; } } public string SelectedProjection { get { return selectedProjection; } set { selectedProjection = value; } } public TrackMode TrackMode { get { return mapControl.TrackOverlay.TrackMode; } set { mapControl.TrackOverlay.TrackMode = value; mapControl.Cursor = mapControl.TrackOverlay.TrackMode == TrackMode.None ? handCursor : Cursors.Arrow; } } public Collection Projections { get { return projections; } } public void ClearHighlightFeaturesAndMarkers() { highlightLayer.InternalFeatures.Clear(); markerOverlay.Markers.Clear(); mapControl.Refresh(); } public void RefreshMapByProjection(string projection) { if (projection.Equals("DecimalDegree")) { mapControl.MapUnit = GeographyUnit.DecimalDegree; wmsOverlay.Parameters["SRS"] = Resources.EPSG4326; } else { mapControl.MapUnit = GeographyUnit.Meter; wmsOverlay.Parameters["SRS"] = Resources.EPSG900913; } ClearHighlightFeaturesAndMarkers(); } public void RefreshMapByUser(User user) { currentUser = user; wmsOverlay.Parameters["ClientId"] = user.ClientId; wmsOverlay.Parameters["UserName"] = user.UserName; wmsOverlay.Refresh(); } private void InitializeWmsSettingData() { projections = new Collection(); projections.Add("DecimalDegree"); projections.Add("Mercator"); selectedProjection = projections[0]; } private void InitializeMapOverlays() { wmsOverlay = new WmsOverlay(new Uri(serviceUri)); wmsOverlay.Parameters.Add("layers", "WorldMap"); wmsOverlay.Parameters.Add("styles", "DEFAULT"); wmsOverlay.Parameters["SRS"] = Resources.EPSG4326; wmsOverlay.Parameters["FORMAT"] = TileImageFormat.Png.ToString(); mapControl.Overlays.Add(wmsOverlay); LayerOverlay highlightOverlay = new LayerOverlay(); highlightLayer = new InMemoryFeatureLayer(); GeoColor serviceAreaGeoColor = new GeoColor(120, GeoColor.FromHtml("#1749c9")); highlightLayer.ZoomLevelSet.ZoomLevel01.DefaultAreaStyle = AreaStyles.CreateSimpleAreaStyle(serviceAreaGeoColor, GeoColor.FromHtml("#fefec1"), 3, LineDashStyle.Solid); highlightLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20; highlightOverlay.Layers.Add(highlightLayer); mapControl.Overlays.Add(highlightOverlay); markerOverlay = new SimpleMarkerOverlay(); mapControl.Overlays.Add(markerOverlay); mapControl.TrackOverlay.TrackEnded += TrackOverlay_TrackEnded; } private void SetDisplayMarker(PointShape selectedPoint) { Marker centerMarker = new Marker(selectedPoint); centerMarker.ImageSource = new BitmapImage(new Uri(string.Format(CultureInfo.InvariantCulture, packUriFormat, "drawPoint.png"), UriKind.RelativeOrAbsolute)); centerMarker.YOffset = -16; centerMarker.XOffset = -16; Feature currentFeature = highlightLayer.InternalFeatures.FirstOrDefault(); if (currentFeature != null) { centerMarker.ToolTip = new PopupUserControl(currentFeature); markerOverlay.Markers.Add(centerMarker); } } private void TrackOverlay_TrackEnded(object sender, TrackEndedTrackInteractiveOverlayEventArgs e) { if (mapControl.TrackOverlay.TrackShapeLayer.InternalFeatures.Count > 0) { BaseShape shape = mapControl.TrackOverlay.TrackShapeLayer.InternalFeatures[0].GetShape(); mapControl.TrackOverlay.TrackShapeLayer.InternalFeatures.Clear(); markerOverlay.Markers.Clear(); if (shape is PointShape) { selectedPoint = (PointShape)shape; HighlightSelectedFeature(selectedPoint); SetDisplayMarker(selectedPoint); mapControl.Refresh(); } } } private string ConvertBoundingBoxToString(RectangleShape boundingBox) { return String.Format(CultureInfo.InvariantCulture, "{0},{1},{2},{3}", boundingBox.LowerLeftPoint.X, boundingBox.LowerLeftPoint.Y, boundingBox.UpperRightPoint.X, boundingBox.UpperRightPoint.Y); } private void HighlightSelectedFeature(PointShape selectedPoint) { highlightLayer.InternalFeatures.Clear(); // Construct the service request url. string serviceUrl = GetServiceUrl(selectedPoint); // Send request to server. HttpWebRequest getFeatureRequest = (HttpWebRequest)WebRequest.Create(serviceUrl); HttpWebResponse reponse = (HttpWebResponse)getFeatureRequest.GetResponse(); // Deserilize the feature from response. DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(SerializableFeatures[])); try { Stream responseStream = reponse.GetResponseStream(); SerializableFeatures[] features = (SerializableFeatures[])serializer.ReadObject(responseStream); highlightLayer.InternalFeatures.Add(features.FirstOrDefault().features.FirstOrDefault().ConcreteFeature); highlightLayer.Open(); mapControl.CurrentExtent = highlightLayer.GetBoundingBox(); } catch (Exception) { MessageBox.Show("No result found, please click on the continent to try again."); } } private string GetServiceUrl(PointShape centerPoint) { ScreenPointF screenPoint = ExtentHelper.ToScreenCoordinate(mapControl.CurrentExtent, centerPoint.X, centerPoint.Y, (float)mapControl.ActualWidth, (float)mapControl.ActualHeight); const string featureFormat = "TEXT/JSON"; string clientId = currentUser.ClientId; string mapFormat = TileImageFormat.Png.ToString(); string projection = selectedProjection.Equals("DecimalDegree") ? Resources.EPSG4326 : Resources.EPSG900913; string bbox = ConvertBoundingBoxToString(mapControl.CurrentExtent); StringBuilder parameters = new StringBuilder(); parameters.Append(serviceUri + "?"); parameters.Append("LAYERS=WorldMap&"); parameters.Append("STYLES=DEFAULT&"); parameters.Append("SERVICE=WMS&"); parameters.Append("VERSION=1.1.1&"); parameters.Append("REQUEST=GETFEATUREINFO&"); parameters.Append("QUERY_LAYERS=WorldMap&"); parameters.AppendFormat(CultureInfo.InvariantCulture, "X={0}&", (int)screenPoint.X); parameters.AppendFormat(CultureInfo.InvariantCulture, "Y={0}&", (int)screenPoint.Y); parameters.AppendFormat(CultureInfo.InvariantCulture, "INFO_FORMAT={0}&", featureFormat); parameters.AppendFormat(CultureInfo.InvariantCulture, "ClientId={0}&", clientId); parameters.AppendFormat(CultureInfo.InvariantCulture, "FEATURE_COUNT={0}&", 1); parameters.AppendFormat(CultureInfo.InvariantCulture, "FORMAT={0}&", mapFormat); parameters.AppendFormat(CultureInfo.InvariantCulture, "SRS={0}&", projection); parameters.AppendFormat(CultureInfo.InvariantCulture, "WIDTH={0}&", (int)mapControl.ActualWidth); parameters.AppendFormat(CultureInfo.InvariantCulture, "HEIGHT={0}&", (int)mapControl.ActualHeight); parameters.AppendFormat(CultureInfo.InvariantCulture, "BBOX={0}", bbox); return parameters.ToString(); } } } ====SerializableFeature.cs==== using System.Collections.Generic; using System.Runtime.Serialization; using ThinkGeo.MapSuite.Core; namespace ThinkGeo.MapSuite.WmsServiceClient { [DataContract] public class SerializableFeature { private string id; private string wkt; private Feature concreteFeature; [DataMember(Name|= "fieldValues")] public Dictionary fieldValues { get; set; } [DataMember(Name|= "id")] public string Id { get { return id; } set { id = value; } } [DataMember(Name|= "wkt")] public string Wkt { get { return wkt; } set { wkt = value; concreteFeature = new Feature(wkt); foreach (var fieldValue in fieldValues) { concreteFeature.ColumnValues.Add(fieldValue.Key, fieldValue.Value); } } } public Feature ConcreteFeature { get { return concreteFeature; } set { concreteFeature = value; } } } } ====User.cs==== namespace ThinkGeo.MapSuite.WmsServiceClient { public class User { private string clientId; private string mapStyle; private string userName; public string UserName { get { return userName; } set { userName = value; } } public string ClientId { get { return clientId; } set { clientId = value; } } public string MapStyle { get { return mapStyle; } set { mapStyle = value; } } } } ====TrackModeToBoolConvertor.cs==== using System; using System.Globalization; using System.Windows.Data; using ThinkGeo.MapSuite.WpfDesktopEdition; namespace ThinkGeo.MapSuite.WmsServiceClient { public class TrackModeToBoolConvertor : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { bool result = false; TrackMode trackMode = (TrackMode)value; string description = parameter as string; if (description.ToUpperInvariant() == "PAN") { result = trackMode == TrackMode.None; } else if (description.ToUpperInvariant() == "DRAWPOINT") { result = trackMode == TrackMode.Point; } return result; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { TrackMode result = TrackMode.None; bool isChecked = (bool)value; string description = parameter as string; if (description.ToUpperInvariant() == "PAN") { result = isChecked ? TrackMode.None : TrackMode.Point; } else if (description.ToUpperInvariant() == "DRAWPOINT") { result = isChecked ? TrackMode.Point : TrackMode.None; } return result; } } } ====CommandBase.cs==== using System; using System.Diagnostics; using System.Windows.Input; namespace ThinkGeo.MapSuite.WmsServiceClient { public class CommandBase : ICommand { private readonly Predicate canExecute; private readonly Action execute; public CommandBase(Action execute) : this(execute, null) { } public CommandBase(Action execute, Predicate canExecute) { if (execute == null) throw new ArgumentNullException("execute"); this.execute = execute; this.canExecute = canExecute; } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } [DebuggerStepThrough] public bool CanExecute(object parameter) { return canExecute == null ? true : canExecute(parameter); } public void Execute(object parameter) { execute(parameter); } } } ====MainWindowViewModel.cs==== using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Windows; using System.Xml.Linq; using ThinkGeo.MapSuite.WpfDesktopEdition; namespace ThinkGeo.MapSuite.WmsServiceClient { public class MainWindowViewModel : ViewModelBase { private string coordinateY; private string coordinateX; private MapModel mapModel; private WpfMap mapControl; private User selectedUser; private List users; private CommandBase clearAllCommand; public MainWindowViewModel() : this(null) { } public MainWindowViewModel(WpfMap wpfMap) { MapControl = wpfMap; MapControl.MapTools.MouseCoordinate.CustomFormatted += MouseCoordinate_CustomFormatted; users = GetUsers(); SelectedUser = users[0]; } public WpfMap MapControl { get { return mapControl; } set { mapControl = value; mapModel = new MapModel(value); } } public string SelectedWmsMapProjection { get { return mapModel.SelectedProjection; } set { mapModel.SelectedProjection = value; mapModel.RefreshMapByProjection(value); RaisePropertyChanged(() => SelectedWmsMapProjection); } } public User SelectedUser { get { return selectedUser; } set { if (value.UserName.ToUpperInvariant() == "ANONYMOUS") { TrackMode = TrackMode.None; } selectedUser = value; mapModel.RefreshMapByUser(value); RaisePropertyChanged(() => SelectedUser); } } public List Users { get { return users; } } public Collection WmsMapProjection { get { return mapModel.Projections; } } public TrackMode TrackMode { get { return mapModel.TrackMode; } set { if (SelectedUser != null) { if (SelectedUser.UserName.ToUpperInvariant() == "ANONYMOUS") { if (value != TrackMode.None) { string warningText = "Anonymous is not allowed to query the WMS service by clicking the map."; new WarningWindow(warningText) { Owner = App.Current.MainWindow, WindowStartupLocation = WindowStartupLocation.CenterOwner }.ShowDialog(); } } else { mapModel.TrackMode = value; RaisePropertyChanged(() => TrackMode); } } } } public string CoordinateX { get { return coordinateX; } set { coordinateX = value; RaisePropertyChanged(() => CoordinateX); } } public string CoordinateY { get { return coordinateY; } set { coordinateY = value; RaisePropertyChanged(() => CoordinateY); } } public CommandBase ClearAllCommand { get { return clearAllCommand ?? (clearAllCommand = new CommandBase(btn => { TrackMode = TrackMode.None; mapModel.ClearHighlightFeaturesAndMarkers(); })); } } private List GetUsers() { return (XDocument.Load(@"UserDataXml\Users.xml") .Descendants("User") .Select(userElement => new User() { UserName = userElement.Element("UserName").Value, ClientId = userElement.Element("ClientId") == null ? string.Empty : userElement.Element("ClientId").Value, MapStyle = userElement.Element("MapStyle") == null ? string.Empty : userElement.Element("MapStyle").Value })).ToList(); } private void MouseCoordinate_CustomFormatted(object sender, CustomFormattedMouseCoordinateMapToolEventArgs e) { string format = "N6"; if (SelectedWmsMapProjection.Equals("Mercator", StringComparison.OrdinalIgnoreCase)) { format = "N2"; } CoordinateX = e.WorldCoordinate.X.ToString(format, CultureInfo.InvariantCulture); CoordinateY = e.WorldCoordinate.Y.ToString(format, CultureInfo.InvariantCulture); } } } ====PopupUserControlViewModel.cs==== using System; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using ThinkGeo.MapSuite.Core; namespace ThinkGeo.MapSuite.WmsServiceClient { public class PopupUserControlViewModel : ViewModelBase { private string header; private string information; public PopupUserControlViewModel(Feature feature) : base() { information = GetColumnValue(feature, "POP_CNTRY"); if (!string.IsNullOrEmpty(information)) { information = string.Format(CultureInfo.InvariantCulture, "{0} : {1}", "POP_CNTRY", information); } header = GetColumnValue(feature, "LONG_NAME"); } public string Header { get { return header; } } public string Information { get { return information; } } private static string GetColumnValue(Feature feature, string columnName) { var columnValuePair = feature.ColumnValues.FirstOrDefault(f => f.Key.Equals(columnName, StringComparison.InvariantCultureIgnoreCase)); return columnValuePair.Value; } } } ====MainWindow.xaml==== Map Suite World Map WMS Service Client Access the WMS service as this user: (If you select "Anonymous", a watermark will be displayed and querying will be disabled)