private void Initialize() { // Create a spatial reference that's suitable for creating planar buffers in north central Texas (State Plane). SpatialReference statePlaneNorthCentralTexas = new SpatialReference(32038); // Define a polygon that represents the valid area of use for the spatial reference. // This information is available at https://developers.arcgis.com/net/latest/wpf/guide/pdf/projected_coordinate_systems_rt100_3_0.pdf List <MapPoint> spatialReferenceExtentCoords = new List <MapPoint> { new MapPoint(-103.070, 31.720, SpatialReferences.Wgs84), new MapPoint(-103.070, 34.580, SpatialReferences.Wgs84), new MapPoint(-94.000, 34.580, SpatialReferences.Wgs84), new MapPoint(-94.00, 31.720, SpatialReferences.Wgs84) }; _spatialReferenceArea = new Polygon(spatialReferenceExtentCoords); _spatialReferenceArea = GeometryEngine.Project(_spatialReferenceArea, statePlaneNorthCentralTexas) as Polygon; // Create a map that uses the North Central Texas state plane spatial reference. Map bufferMap = new Map(statePlaneNorthCentralTexas); // Add some base layers (counties, cities, and highways). Uri usaLayerSource = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/USA/MapServer"); ArcGISMapImageLayer usaLayer = new ArcGISMapImageLayer(usaLayerSource); bufferMap.Basemap.BaseLayers.Add(usaLayer); // Use a new EnvelopeBuilder to expand the spatial reference extent 120%. EnvelopeBuilder envBuilder = new EnvelopeBuilder(_spatialReferenceArea.Extent); envBuilder.Expand(1.2); // Set the map's initial extent to the expanded envelope. Envelope startingEnvelope = envBuilder.ToGeometry(); bufferMap.InitialViewpoint = new Viewpoint(startingEnvelope); // Assign the map to the MapView. _myMapView.Map = bufferMap; // Create a graphics overlay to show the buffer polygon graphics. GraphicsOverlay bufferGraphicsOverlay = new GraphicsOverlay { // Give the overlay an ID so it can be found later. Id = "buffers" }; // Create a graphic to show the spatial reference's valid extent (envelope) with a dashed red line. SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, Color.Red, 5); Graphic spatialReferenceExtentGraphic = new Graphic(_spatialReferenceArea, lineSymbol); // Add the graphic to a new overlay. GraphicsOverlay spatialReferenceGraphicsOverlay = new GraphicsOverlay(); spatialReferenceGraphicsOverlay.Graphics.Add(spatialReferenceExtentGraphic); // Add the graphics overlays to the MapView. _myMapView.GraphicsOverlays.Add(bufferGraphicsOverlay); _myMapView.GraphicsOverlays.Add(spatialReferenceGraphicsOverlay); }
private Task <Tuple <IDisposable, long> > AddFeatureToOverlay(MapViewMouseEventArgs e) { return(QueuedTask.Run(() => { double llx = e.ClientPoint.X - 3; double lly = e.ClientPoint.Y - 3; double urx = e.ClientPoint.X + 3; double ury = e.ClientPoint.Y + 3; EnvelopeBuilder envBuilder = new EnvelopeBuilder(ActiveMapView.ClientToMap(new Point(llx, lly)), ActiveMapView.ClientToMap(new Point(urx, ury))); MapPoint mp = ActiveMapView.ClientToMap(e.ClientPoint); var cursor = _trees.Search(new SpatialQueryFilter() { FilterGeometry = envBuilder.ToGeometry(), SpatialRelationship = SpatialRelationship.Intersects }); if (cursor.MoveNext()) { return new Tuple <IDisposable, long>( ActiveMapView.AddOverlay(ActiveMapView.ClientToMap(e.ClientPoint), _overlaySymbol.MakeSymbolReference()), cursor.Current.GetObjectID()); } //var select = _trees.Select(new SpatialQueryFilter() { // FilterGeometry = envBuilder.ToGeometry(), // SpatialRelationship = SpatialRelationship.Intersects //}); //if (select.GetCount() > 0) { // return ActiveMapView.AddOverlay(ActiveMapView.ClientToMap(e.ClientPoint), _overlaySymbol.MakeSymbolReference()); //} return new Tuple <IDisposable, long>(null, -1); })); }
private void Watcher_PositionChanged(object sender, GeoPositionChangedEventArgs <GeoCoordinate> e) { GeoCoordinate coord = e.Position.Location; var mapView = MapView.Active; if (mapView == null) { return; } if (coord.IsUnknown != true) { System.Diagnostics.Debug.WriteLine("Lat: {0}, Long: {1}", coord.Latitude, coord.Longitude); ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => { MapPoint zoomToPnt = MapPointBuilder.CreateMapPoint(coord.Longitude, coord.Latitude, SpatialReferences.WGS84); var geoProject = GeometryEngine.Instance.Project(zoomToPnt, SpatialReferences.WebMercator) as MapPoint; var expandSize = 200.0; var minPoint = MapPointBuilder.CreateMapPoint(geoProject.X - expandSize, geoProject.Y - expandSize, SpatialReferences.WebMercator); var maxPoint = MapPointBuilder.CreateMapPoint(geoProject.X + expandSize, geoProject.Y + expandSize, SpatialReferences.WebMercator); Envelope env = EnvelopeBuilder.CreateEnvelope(minPoint, maxPoint); mapView.ZoomTo(env, new TimeSpan(0, 0, 3)); _graphic = MapView.Active.AddOverlay(zoomToPnt, _pointSymbol.MakeSymbolReference()); }); } else { MessageBox.Show("Unknown latitude and longitude. Check your control panel for Location Privacy settings."); } }
internal static Geometry MakeFishnetPolygon(Polygon inputPoly) { Envelope envPoly = inputPoly.Extent; var interval = GetFishnetIntervalDistance(envPoly); var pb = new PolygonBuilder(inputPoly.SpatialReference) { HasZ = true }; for (var dX = envPoly.XMin; dX < envPoly.XMax + interval; dX += interval) { for (var dY = envPoly.YMin; dY < envPoly.YMax + interval; dY += interval) { var cutEnv = EnvelopeBuilder.CreateEnvelope(dX, dY, dX + interval, dY + interval, envPoly.SpatialReference); if (GeometryEngine.Instance.Intersects(cutEnv, inputPoly)) { var addPolygonPart = GeometryEngine.Instance.Clip(inputPoly, cutEnv) as Polygon; if (addPolygonPart.Area < 0) { System.Diagnostics.Debug.WriteLine($@"area: {addPolygonPart.Area}"); } pb.AddPart(addPolygonPart.Points); } } } return(pb.ToGeometry()); }
private void MapView_ExtentChanged(object sender, EventArgs e) { Envelope newExtent = null; if (MyMapView.WrapAround) { Geometry normalizedExtent = GeometryEngine.NormalizeCentralMeridian(MyMapView.Extent); if (normalizedExtent is Polygon) { var normalizedPolygon = (Polygon)normalizedExtent; if (normalizedPolygon.Parts.Count == 1) { newExtent = normalizedPolygon.Extent; } else { var newExtentBuilder = new EnvelopeBuilder(MyMapView.SpatialReference); foreach (var p in normalizedPolygon.Parts[0].GetPoints()) { if (p.X < newExtentBuilder.XMin || double.IsNaN(newExtentBuilder.XMin)) { newExtentBuilder.XMin = p.X; } if (p.Y < newExtentBuilder.YMin || double.IsNaN(newExtentBuilder.YMin)) { newExtentBuilder.YMin = p.Y; } } foreach (var p in normalizedPolygon.Parts[1].GetPoints()) { if (p.X > newExtentBuilder.XMax || double.IsNaN(newExtentBuilder.XMax)) { newExtentBuilder.XMax = p.X; } if (p.Y > newExtentBuilder.YMax || double.IsNaN(newExtentBuilder.YMax)) { newExtentBuilder.YMax = p.Y; } } newExtent = newExtentBuilder.ToGeometry(); } } else if (normalizedExtent is Envelope) { newExtent = normalizedExtent as Envelope; } } else { newExtent = MyMapView.Extent; } MinXNormalized.Text = newExtent.XMin.ToString("0.000"); MinYNormalized.Text = newExtent.YMin.ToString("0.000"); MaxXNormalized.Text = newExtent.XMax.ToString("0.000"); MaxYNormalized.Text = newExtent.YMax.ToString("0.000"); }
// 관리번호로 해당Feature 객체찾기 public async void SelectFct(string _FTR_CDE, string _FTR_IDN, FeatureLayer _featureLayer) { // 0.Feature 테이블 가져오기 //FeatureLayer __featureLayer = _featureLayer.Clone() as FeatureLayer; FeatureTable _featureTable = _featureLayer.FeatureTable; // Create a query parameters that will be used to Query the feature table. QueryParameters queryParams = new QueryParameters(); // Construct and assign the where clause that will be used to query the feature table. queryParams.WhereClause = " FTR_CDE = '" + _FTR_CDE + "' ORDER BY FTR_IDN DESC"; if (!FmsUtil.IsNull(_FTR_IDN)) { queryParams.WhereClause = " FTR_CDE = '" + _FTR_CDE + "' AND FTR_IDN like '%' || " + _FTR_IDN + " || '%'"; } List <Feature> features; try { // Query the feature table. FeatureQueryResult queryResult = await _featureTable.QueryFeaturesAsync(queryParams); // Cast the QueryResult to a List so the results can be interrogated. features = queryResult.ToList(); } catch (Exception e) { Messages.ShowErrMsgBox(e.Message); return; } if (features.Any()) { // Create an envelope. EnvelopeBuilder envBuilder = new EnvelopeBuilder(SpatialReferences.WebMercator); if (features.Count == 1) { //한건인 경우 선택처리 ShowFctPage(features[0]); } else { //피쳐영역 Extent 위치이동 foreach (Feature feature in features) { envBuilder.UnionOf(feature.Geometry.Extent); //복수의 피처영역 합치기 } // Zoom to the extent of the selected feature(s). await mapView.SetViewpointGeometryAsync(envBuilder.ToGeometry(), 50); } } }
public void Dulicate_message_is_detected() { var streamer = EnvelopeStreamer.CreateDefault(typeof(Message)); var builder = new CqrsEngineBuilder(streamer); var cfg = new MemoryStorageConfig(); var sender = cfg.CreateSimpleSender(streamer, "in"); builder.Handle(cfg.CreateInbox("in"), envelope => Console.WriteLine("Got message")); var env = new EnvelopeBuilder("fixed ID").Build(); using (var token = new CancellationTokenSource()) using (var build = builder.Build()) using (TestObserver.When<EnvelopeDuplicateDiscarded>(discarded => token.Cancel())) { sender.SendBatch(new object[]{new Message()}, IdGeneration.HashContent); sender.SendBatch(new object[] { new Message()}, IdGeneration.HashContent); build.Start(token.Token); if (Debugger.IsAttached) { token.Token.WaitHandle.WaitOne(); } else { token.Token.WaitHandle.WaitOne(10000); } Assert.IsTrue(token.IsCancellationRequested); } }
void InnerSendBatch(Action<EnvelopeBuilder> configure, object[] messageItems) { if (messageItems.Length == 0) return; var id = _idGenerator(); var builder = new EnvelopeBuilder(id); foreach (var item in messageItems) { builder.AddItem(item); } configure(builder); var envelope = builder.Build(); var queue = GetOutboundQueue(); if (Transaction.Current == null) { queue.PutMessage(envelope); _observer.Notify(new EnvelopeSent(queue.Name, envelope.EnvelopeId, false, envelope.Items.Select(x => x.MappedType.Name).ToArray())); } else { var action = new CommitActionEnlistment(() => { queue.PutMessage(envelope); _observer.Notify(new EnvelopeSent(queue.Name, envelope.EnvelopeId, true, envelope.Items.Select(x => x.MappedType.Name).ToArray())); }); Transaction.Current.EnlistVolatile(action, EnlistmentOptions.None); } }
public static Action <ImmutableEnvelope> Route(Func <string, IQueueWriter> factory, IEnvelopeStreamer serializer, ITapeStorageFactory tapes) { var events = factory(EventsQueue); var timerQueue = factory(TimerQueue); var entityQueue = factory(EntityQueue); var services = factory(ServiceQueue); var log = tapes.GetOrCreateStream(DomainLogName); return(envelope => { var data = serializer.SaveEnvelopeData(envelope); if (!log.TryAppend(data)) { throw new InvalidOperationException("Failed to record domain log"); } if (envelope.DeliverOnUtc > Current.UtcNow) { timerQueue.PutMessage(data); return; } if (envelope.Items.All(i => i.Content is ICommand <IIdentity>)) { entityQueue.PutMessage(data); return; } if (envelope.Items.All(i => i.Content is IEvent <IIdentity>)) { // we can have more than 1 entity event. // all entity events are routed to events as separate for (int i = 0; i < envelope.Items.Length; i++) { var name = envelope.EnvelopeId + "-e" + i; var copy = EnvelopeBuilder.CloneProperties(name, envelope); copy.AddItem(envelope.Items[i]); events.PutMessage(serializer.SaveEnvelopeData(copy.Build())); } return; } if (envelope.Items.Length != 1) { throw new InvalidOperationException( "Only entity commands or entity events can be batched"); } var item = envelope.Items[0].Content; if (item is IFunctionalCommand) { services.PutMessage(data); return; } if (item is IFunctionalEvent || item is ISampleEvent) { events.PutMessage(data); return; } throw new InvalidOperationException(string.Format("Unroutable message {0}", item)); }); }
public void Empty_roundtrip_should_work() { var builder = new EnvelopeBuilder("my-id"); var envelope = RoundtripViaSerializer(builder); Assert.AreEqual(envelope.EnvelopeId, "my-id"); }
public void Dulicate_message_is_detected() { var streamer = EnvelopeStreamer.CreateDefault(typeof(Message)); var builder = new CqrsEngineBuilder(streamer); var cfg = new MemoryStorageConfig(); var sender = cfg.CreateSimpleSender(streamer, "in"); builder.Handle(cfg.CreateInbox("in"), envelope => Console.WriteLine("Got message")); var env = new EnvelopeBuilder("fixed ID").Build(); using (var token = new CancellationTokenSource()) using (var build = builder.Build()) using (TestObserver.When <EnvelopeDuplicateDiscarded>(discarded => token.Cancel())) { sender.SendBatch(new object[] { new Message() }, IdGeneration.HashContent); sender.SendBatch(new object[] { new Message() }, IdGeneration.HashContent); build.Start(token.Token); if (Debugger.IsAttached) { token.Token.WaitHandle.WaitOne(); } else { token.Token.WaitHandle.WaitOne(10000); } Assert.IsTrue(token.IsCancellationRequested); } }
private void Initialize() { // Define the route stop locations (points) MapPoint fromPoint = new MapPoint(-117.15494348793044, 32.706506537686927, SpatialReferences.Wgs84); MapPoint toPoint = new MapPoint(-117.14905088669816, 32.735308180609138, SpatialReferences.Wgs84); // Create Stop objects with the points and add them to a list of stops Stop stop1 = new Stop(fromPoint); Stop stop2 = new Stop(toPoint); _routeStops = new List <Stop> { stop1, stop2 }; // Picture marker symbols: from = car, to = checkered flag PictureMarkerSymbol carSymbol = new PictureMarkerSymbol(_carIconUri); PictureMarkerSymbol flagSymbol = new PictureMarkerSymbol(_checkedFlagIconUri); // Add a slight offset (pixels) to the picture symbols. carSymbol.OffsetX = -carSymbol.Width / 2; carSymbol.OffsetY = -carSymbol.Height / 2; flagSymbol.OffsetX = -flagSymbol.Width / 2; flagSymbol.OffsetY = -flagSymbol.Height / 2; // Set the height and width. flagSymbol.Height = 60; flagSymbol.Width = 60; carSymbol.Height = 60; carSymbol.Width = 60; // Create graphics for the stops Graphic fromGraphic = new Graphic(fromPoint, carSymbol) { ZIndex = 1 }; Graphic toGraphic = new Graphic(toPoint, flagSymbol) { ZIndex = 1 }; // Create the graphics overlay and add the stop graphics _routeGraphicsOverlay = new GraphicsOverlay(); _routeGraphicsOverlay.Graphics.Add(fromGraphic); _routeGraphicsOverlay.Graphics.Add(toGraphic); // Get an Envelope that covers the area of the stops (and a little more) Envelope routeStopsExtent = new Envelope(fromPoint, toPoint); EnvelopeBuilder envBuilder = new EnvelopeBuilder(routeStopsExtent); envBuilder.Expand(1.5); // Create a new viewpoint apply it to the map view when the spatial reference changes Viewpoint sanDiegoViewpoint = new Viewpoint(envBuilder.ToGeometry()); MyMapView.SpatialReferenceChanged += (s, e) => MyMapView.SetViewpoint(sanDiegoViewpoint); // Add a new Map and the graphics overlay to the map view MyMapView.Map = new Map(BasemapStyle.ArcGISStreets); MyMapView.GraphicsOverlays.Add(_routeGraphicsOverlay); }
private void Initialize() { // Define the route stop locations (points) MapPoint fromPoint = new MapPoint(-117.15494348793044, 32.706506537686927, SpatialReferences.Wgs84); MapPoint toPoint = new MapPoint(-117.14905088669816, 32.735308180609138, SpatialReferences.Wgs84); // Create Stop objects with the points and add them to a list of stops Stop stop1 = new Stop(fromPoint); Stop stop2 = new Stop(toPoint); _routeStops = new List <Stop> { stop1, stop2 }; // Picture marker symbols: from = car, to = checkered flag PictureMarkerSymbol carSymbol = new PictureMarkerSymbol(_carIconUri) { Height = 40, Width = 40 }; PictureMarkerSymbol flagSymbol = new PictureMarkerSymbol(_checkedFlagIconUri) { Height = 40, Width = 40, // Offset the icon so that it is anchored at the bottom of the flagpole OffsetX = 20, OffsetY = 20 }; // Create graphics for the stops Graphic fromGraphic = new Graphic(fromPoint, carSymbol) { // Make sure the icons are shown over the route line ZIndex = 1 }; Graphic toGraphic = new Graphic(toPoint, flagSymbol) { ZIndex = 1 }; // Create the graphics overlay and add the stop graphics _routeGraphicsOverlay = new GraphicsOverlay(); _routeGraphicsOverlay.Graphics.Add(fromGraphic); _routeGraphicsOverlay.Graphics.Add(toGraphic); // Get an Envelope that covers the area of the stops (and a little more) Envelope routeStopsExtent = new Envelope(fromPoint, toPoint); EnvelopeBuilder envBuilder = new EnvelopeBuilder(routeStopsExtent); envBuilder.Expand(1.5); // Create a new viewpoint apply it to the map view when the spatial reference changes Viewpoint sanDiegoViewpoint = new Viewpoint(envBuilder.ToGeometry()); _myMapView.SpatialReferenceChanged += (s, e) => _myMapView.SetViewpoint(sanDiegoViewpoint); // Add a new Map and the graphics overlay to the map view _myMapView.Map = new Map(Basemap.CreateStreets()); _myMapView.GraphicsOverlays.Add(_routeGraphicsOverlay); }
public static ImmutableEnvelope BuildEnvelope(this IMessage message) { var eb = new EnvelopeBuilder(Guid.NewGuid().ToString()); eb.AddItem((object) message); return eb.Build(); }
/// <summary> /// This method must be called on the MCT /// </summary> /// <remarks>If multiple features are selected just the ObjectID of the first feature /// in the selected set is returned</remarks> /// <param name="point"></param> /// <returns>The object id of the selected feature or -1</returns> internal static Polyline SelectLineFeature(MapPoint point) { if (OnUIThread) { throw new CalledOnWrongThreadException(); } var pt = MapView.Active.MapToClient(point); double llx = pt.X - 5; double lly = pt.Y - 5; double urx = pt.X + 5; double ury = pt.Y + 5; EnvelopeBuilder envBuilder = new EnvelopeBuilder(MapView.Active.ClientToMap(new Point(llx, lly)), MapView.Active.ClientToMap(new Point(urx, ury))); //Just get feature layers that are line types var selection = MapView.Active.SelectFeatures(envBuilder.ToGeometry()).Where( k => k.Key.ShapeType == esriGeometryType.esriGeometryPolyline ).ToList(); Polyline selectedLine = null; if (selection.Count() > 0) { //return the first of the selected features var flayer = selection.First().Key; var oid = selection.First().Value[0]; var inspector = new Inspector(); inspector.Load(flayer, oid); selectedLine = inspector["SHAPE"] as Polyline; } return(selectedLine); }
async public static void CreateNew() { #region TableFrame_CreateNew //Create a new table frame on the active layout. Layout layout = LayoutView.Active.Layout; //Perform on the worker thread await QueuedTask.Run(() => { //Build 2D envelope geometry Coordinate2D rec_ll = new Coordinate2D(1.0, 3.5); Coordinate2D rec_ur = new Coordinate2D(7.5, 4.5); Envelope rec_env = EnvelopeBuilder.CreateEnvelope(rec_ll, rec_ur); //Reference map frame MapFrame mf = layout.FindElement("Map Frame") as MapFrame; //Reference layer Map m = mf.Map; FeatureLayer lyr = m.FindLayers("GreatLakes").First() as FeatureLayer; //Build fields list var fields = new[] { "NAME", "Shape_Area", "Shape_Length" }; //Construct the table frame TableFrame tabFrame = LayoutElementFactory.Instance.CreateTableFrame(layout, rec_env, mf, lyr, fields); }); #endregion TableFrame_CreateNew }
public void AppendToStream(IIdentity id, long originalVersion, ICollection<IEvent<IIdentity>> events, string explanation) { if (events.Count == 0) return; var stream = _factory.GetOrCreateStream(IdentityConvert.ToStream(id)); var b = new EnvelopeBuilder("unknown"); if (!String.IsNullOrEmpty(explanation)) { b.AddString("explain", explanation); } foreach (var e in events) { b.AddItem((object)e); } var data = _streamer.SaveEnvelopeData(b.Build()); var result = stream.TryAppend(data, TapeAppendCondition.VersionIs(originalVersion)); if (result == 0) { throw new InvalidOperationException("Failed to update the stream - it has been changed concurrently"); } PublishDomainSuccess(id, events, originalVersion); }
void AppendToStream(IIdentity id, string envelopeId, Applied then, string explanation) { var stream = _factory.GetOrCreateStream(IdentityConvert.ToStream(id)); var b = new EnvelopeBuilder("unknown"); b.AddString("caused-by", envelopeId); if (!String.IsNullOrEmpty(explanation)) { b.AddString("explain", explanation); } foreach (var e in then.Events) { b.AddItem((object)e); } var data = _streamer.SaveEnvelopeData(b.Build()); Context.Debug("?? Append {0} at v{3} to '{1}' in thread {2}", then.Events.Count, IdentityConvert.ToStream(id), Thread.CurrentThread.ManagedThreadId, then.Version); if (!stream.TryAppend(data, TapeAppendCondition.VersionIs(then.Version))) { throw new InvalidOperationException("Failed to update the stream - it has been changed concurrently"); } }
public async void UpdateExtents(object sender, RoutedEventArgs e) { statusTextBlock.Text = "Updating Extents"; QueryParameters queryParams = new QueryParameters(); queryParams.WhereClause = "TaxID LIKE '" + _currTaxID + "'"; FeatureQueryResult queryResult = await sfFeatTable.QueryFeaturesAsync(queryParams); List <Feature> features = queryResult.ToList(); if (features.Any()) { EnvelopeBuilder envBuilder = new EnvelopeBuilder(SpatialReference.Create(102715)); foreach (Feature feature in features) { envBuilder.UnionOf(feature.Geometry.Extent); newFeatureLayer.ClearSelection(); newFeatureLayer.SelectFeature(feature); } await MyMapView.SetViewpointGeometryAsync(envBuilder.ToGeometry(), 20); statusTextBlock.Text = ""; } else { statusTextBlock.Text = "No parcel found for current query"; } }
private void PutLocalIP(EnvelopeBuilder builder) { var ip = Dns.GetHostEntry(Dns.GetHostName()).AddressList .Where(address => address.AddressFamily == AddressFamily.InterNetwork) .FirstOrDefault(); builder.AddString(ContextAttributes.ORIGINATING_MACHINE, ip == null ? "?" : ip.ToString()); }
private void PutLocalIP(EnvelopeBuilder builder) { var ip = Dns.GetHostEntry(Dns.GetHostName()).AddressList .Where(address => address.AddressFamily == AddressFamily.InterNetwork) .FirstOrDefault(); builder.AddString(ContextAttributes.ORIGINATING_MACHINE, ip==null ? "?" : ip.ToString()); }
protected Envelope CreateHitBox(MapView mapView, MapPoint location, double sizeInPoints, SpatialReference spatialRef) { var sizeInPixels = Drawing.PixelsFromPoints(sizeInPoints); var refPoint = mapView.MapToClient(location); var minPoint = mapView.ClientToMap(new System.Windows.Point(refPoint.X - sizeInPixels, refPoint.Y + sizeInPixels)); // remember, screen Y axis starts from top to bottom var maxPoint = mapView.ClientToMap(new System.Windows.Point(refPoint.X + sizeInPixels, refPoint.Y - sizeInPixels)); return(EnvelopeBuilder.CreateEnvelope(minPoint, maxPoint, spatialRef)); }
public void Test() { var b = new EnvelopeBuilder("GUID"); b.DelayBy(TimeSpan.FromSeconds(10)); b.AddString("Test"); b.AddItem(new { Cool = "1"}).AddAttribute("D2","D1"); Console.WriteLine(b.Build().PrintToString(o => o.Dump())); }
protected override async Task <bool> OnSketchCompleteAsync(Geometry geometry) { var bottomRight = new Point(); IList <Tuple <string, string, long> > tripleTuplePoints = new List <Tuple <string, string, long> >(); var hasSelection = await QueuedTask.Run(() => { // geometry is a point var clickedPnt = geometry as MapPoint; if (clickedPnt == null) { System.Windows.MessageBox.Show("Clicked point is null"); return(false); } // pixel tolerance var tolerance = 10; //Get the client point edges var topLeft = new Point(clickedPnt.X - tolerance, clickedPnt.Y + tolerance); bottomRight = new Point(clickedPnt.X + tolerance, clickedPnt.Y - tolerance); //convert the client points to Map points var mapTopLeft = MapView.Active.ClientToMap(topLeft); var mapBottomRight = MapView.Active.ClientToMap(bottomRight); //create a geometry using these points Geometry envelopeGeometry = EnvelopeBuilder.CreateEnvelope(mapTopLeft, mapBottomRight); if (envelopeGeometry == null) { System.Windows.MessageBox.Show("envleope is null"); return(false); } //Get the features that intersect the sketch geometry. var result = ActiveMapView.GetFeatures(geometry); foreach (var kvp in result) { var bfl = kvp.Key; // only look at points if (kvp.Key.ShapeType != esriGeometryType.esriGeometryPoint) { continue; } var layerName = bfl.Name; var oidName = bfl.GetTable().GetDefinition().GetObjectIDField(); foreach (var oid in kvp.Value) { tripleTuplePoints.Add(new Tuple <string, string, long>(layerName, oidName, oid)); } } return(true); }); if (hasSelection) { //System.Windows.MessageBox.Show("Has selection"); ShowContextMenu(bottomRight, tripleTuplePoints); } return(true); }
/// <summary> /// Erzeugt eine neue Instanz und verwendet den angegebenen Endpunkt. /// </summary> /// <param name="url">der Endpunkt eines Dienstes</param> /// <param name="mapSpatialReference">der Raumbezug der Karte</param> public TrafficLayer(string url, Esri.ArcGISRuntime.Geometry.SpatialReference mapSpatialReference) { // TODO: Dispose des Dienstes implementieren _service = new TrafficService(); _url = url; _mapSpatialReference = mapSpatialReference; Overlay = CreateOverlay(); AreaOfInterest = new EnvelopeBuilder(mapSpatialReference).ToGeometry(); }
private async void Initialize() { // Get all the ColorRamp names from the PresetColorRampType Enumeration and put them // in an array of strings, then set the ComboBox.ItemSource to the array, and finally // select the first item in the ComboBox string[] myPresetColorRampTypes = Enum.GetNames(typeof(PresetColorRampType)); ColorRamps.ItemsSource = myPresetColorRampTypes; ColorRamps.SelectedIndex = 0; // Get all the SlopeType names from the SlopeType Enumeration and put them // in an array of strings, then set the ComboBox.ItemSource to the array, and finally // select the first item in the ComboBox string[] mySlopeTypes = Enum.GetNames(typeof(SlopeType)); SlopeTypes.ItemsSource = mySlopeTypes; SlopeTypes.SelectedIndex = 0; // Set the altitude slider min/max and initial value Altitude_Slider.Minimum = 0; Altitude_Slider.Maximum = 90; Altitude_Slider.Value = 45; // Set the azimuth slider min/max and initial value Azimuth_Slider.Minimum = 0; Azimuth_Slider.Maximum = 360; Azimuth_Slider.Value = 180; // Load the raster file using a path on disk Raster myRasterImagery = new Raster(GetRasterPath_Imagery()); // Create the raster layer from the raster RasterLayer myRasterLayerImagery = new RasterLayer(myRasterImagery); // Create a new map using the raster layer as the base map Map myMap = new Map(new Basemap(myRasterLayerImagery)); // Wait for the layer to load - this enabled being able to obtain the extent information // of the raster layer await myRasterLayerImagery.LoadAsync(); // Create a new EnvelopeBuilder from the full extent of the raster layer EnvelopeBuilder myEnvelopBuilder = new EnvelopeBuilder(myRasterLayerImagery.FullExtent); // Zoom in the extent just a bit so that raster layer encompasses the entire viewable area of the map myEnvelopBuilder.Expand(0.75); // Set the viewpoint of the map to the EnvelopeBuilder's extent myMap.InitialViewpoint = new Viewpoint(myEnvelopBuilder.ToGeometry().Extent); // Add map to the map view MyMapView.Map = myMap; // Wait for the map to load await myMap.LoadAsync(); // Enable the 'Update Renderer' button now that the map has loaded UpdateRenderer.IsEnabled = true; }
public static Envelope CreateEnvelope( double x0, double y0, double x1, double y1, SpatialReference sref = null) { var p0 = new Coordinate2D(x0, y0); var p1 = new Coordinate2D(x1, y1); return(EnvelopeBuilder.CreateEnvelope(p0, p1, sref)); }
public static byte[] SaveEnvelopeData(this IEnvelopeStreamer streamer, object message, Action<EnvelopeBuilder> build = null) { var builder = new EnvelopeBuilder(Guid.NewGuid().ToString()); builder.AddItem(message); if (null != build) { build(builder); } return streamer.SaveEnvelopeData(builder.Build()); }
public void Payload_should_be_serialized() { var builder = new EnvelopeBuilder("my-id"); builder.AddItem(new MyMessage("42")); var envelope = RoundtripViaSerializer(builder); Assert.AreEqual(1, envelope.Items.Length); Assert.AreEqual("42", ((MyMessage)envelope.Items[0].Content).Value); }
private void MapView_ExtentChanged(object sender, System.EventArgs e) { Envelope newExtent = null; // Get current viewpoints extent from the MapView var currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry); var viewpointExtent = currentViewpoint.TargetGeometry.Extent; if (MyMapView.WrapAround) { Geometry normalizedExtent = GeometryEngine.NormalizeCentralMeridian(viewpointExtent); if (normalizedExtent is Polygon) { var normalizedPolygon = (Polygon)normalizedExtent; if (normalizedPolygon.Parts.Count == 1) newExtent = normalizedPolygon.Extent; else { var newExtentBuilder = new EnvelopeBuilder(MyMapView.SpatialReference); foreach (var p in normalizedPolygon.Parts[0].GetPoints()) { if (Geometry.IsNullOrEmpty(newExtent) || p.X < newExtent.XMin || double.IsNaN(newExtent.XMin)) newExtentBuilder.XMin = p.X; if (Geometry.IsNullOrEmpty(newExtent) || p.Y < newExtent.YMin || double.IsNaN(newExtent.YMin)) newExtentBuilder.YMin = p.Y; } foreach (var p in normalizedPolygon.Parts[1].GetPoints()) { if (Geometry.IsNullOrEmpty(newExtent) || p.X > newExtent.XMax || double.IsNaN(newExtent.XMax)) newExtentBuilder.XMax = p.X; if (Geometry.IsNullOrEmpty(newExtent) || p.Y > newExtent.YMax || double.IsNaN(newExtent.YMax)) newExtentBuilder.YMax = p.Y; } newExtent = newExtentBuilder.ToGeometry(); } } else if (normalizedExtent is Envelope) newExtent = normalizedExtent as Envelope; } else newExtent = viewpointExtent; MinXNormalized.Text = newExtent.XMin.ToString("0.000"); MinYNormalized.Text = newExtent.YMin.ToString("0.000"); MaxXNormalized.Text = newExtent.XMax.ToString("0.000"); MaxYNormalized.Text = newExtent.YMax.ToString("0.000"); MinXAbsolute.Text = viewpointExtent.XMin.ToString("0.000"); MinYAbsolute.Text = viewpointExtent.YMin.ToString("0.000"); MaxXAbsolute.Text = viewpointExtent.XMax.ToString("0.000"); MaxYAbsolute.Text = viewpointExtent.YMax.ToString("0.000"); }
private void UpdateMapExtent() { // Return if mapview is null. if (myMapView == null) { return; } // Get the new viewpoint. Viewpoint myViewPoint = myMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry); // Return if viewpoint is null. if (myViewPoint == null) { return; } // Get the updated extent for the new viewpoint. Envelope extent = myViewPoint.TargetGeometry as Envelope; // Return if extent is null. if (extent == null) { return; } // Create an envelope that is a bit smaller than the extent. EnvelopeBuilder envelopeBldr = new EnvelopeBuilder(extent); envelopeBldr.Expand(0.80); // Get the (only) graphics overlay in the map view. GraphicsOverlay extentOverlay = myMapView.GraphicsOverlays.FirstOrDefault(); // Return if the extent overlay is null. if (extentOverlay == null) { return; } // Get the extent graphic. Graphic extentGraphic = extentOverlay.Graphics.FirstOrDefault(); // Create the extent graphic and add it to the overlay if it doesn't exist. if (extentGraphic == null) { extentGraphic = new Graphic(envelopeBldr.ToGeometry()); extentOverlay.Graphics.Add(extentGraphic); } else { // Otherwise, update the graphic's geometry. extentGraphic.Geometry = envelopeBldr.ToGeometry(); } }
void RunScheduler(CancellationToken token) { while (!token.IsCancellationRequested) { try { var date = DateTime.UtcNow; const int count = 100; List <Record> list; lock (_scheduler) { list = _scheduler.Where(r => r.DeliverOn <= date).Take(count).ToList(); } if (list.Count > 0) { foreach (var record in list) { var item = _storage.GetItem(record.Name); ImmutableEnvelope e; using (var mem = new MemoryStream()) { item.ReadInto((x, y) => y.CopyTo(mem)); e = _streamer.ReadAsEnvelopeData(mem.ToArray()); } // we need to reset the timer here. var newEnvelope = EnvelopeBuilder.CloneProperties(e.EnvelopeId + "-future", e); newEnvelope.DeliverOnUtc(DateTime.MinValue); newEnvelope.AddString("original-id", e.EnvelopeId); foreach (var message in e.Items) { newEnvelope.AddItem(message); } _target.PutMessage(_streamer.SaveEnvelopeData(newEnvelope.Build())); item.Delete(); lock (_scheduler) { _scheduler.Remove(record); } } } token.WaitHandle.WaitOne(5000); } catch (Exception ex) { Trace.WriteLine(ex); token.WaitHandle.WaitOne(2000); } } }
private static void CreateField(Report report) { #region Create a new field in the report //This is the gap between two fields. double fieldIncrement = 0.9388875113593206276389; //On the QueuedTask //New field to add. var newReportField = new CIMReportField { Name = "POP1990", FieldOrder = 2, }; //Get the "ReportSection element" var mainReportSection = report.Elements.OfType <ReportSection>().FirstOrDefault(); if (mainReportSection == null) { return; } //Get the "ReportDetails" within the ReportSectionElement. ReportDetails is where "fields" are. var reportDetailsSection = mainReportSection?.Elements.OfType <ReportDetails>().FirstOrDefault(); if (reportDetailsSection == null) { return; } //Within ReportDetails find the envelope that encloses a field. //We get the first CIMParagraphTextGraphic in the collection so that we can add the new field next to it. var lastFieldGraphic = reportDetailsSection.Elements.FirstOrDefault((r) => { var gr = r as GraphicElement; if (gr == null) { return(false); } return(gr.GetGraphic() is CIMParagraphTextGraphic ? true : false); }); //Get the Envelope of the last field var graphicBounds = lastFieldGraphic.GetBounds(); //Min and Max values of the envelope var xMinOfFieldEnvelope = graphicBounds.XMin; var yMinOfFieldEnvelope = graphicBounds.YMin; var xMaxOfFieldEnvelope = graphicBounds.XMax; var YMaxOfFieldEnvelope = graphicBounds.YMax; //create the new Envelope to be offset from the existing field MapPoint newMinPoint = MapPointBuilder.CreateMapPoint(xMinOfFieldEnvelope + fieldIncrement, yMinOfFieldEnvelope); MapPoint newMaxPoint = MapPointBuilder.CreateMapPoint(xMaxOfFieldEnvelope + fieldIncrement, YMaxOfFieldEnvelope); Envelope newFieldEnvelope = EnvelopeBuilder.CreateEnvelope(newMinPoint, newMaxPoint); //Create field GraphicElement fieldGraphic = ReportElementFactory.Instance.CreateFieldValueTextElement(reportDetailsSection, newFieldEnvelope, newReportField); #endregion }
private async void ArtistListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { // Get the selected track info TrackInfo ti = ArtistListBox.SelectedItem as TrackInfo; // If the track info is good, show it in the info panel if (ti == null) { return; } ArtistInfoPanel.DataContext = ti; // Filter the layers by artist ID string artistFilter = "artistid = '" + ti.ArtistId + "'"; _artistHometownLayer.DefinitionExpression = artistFilter; _listenerLayer.DefinitionExpression = artistFilter; _otherLocationsLayer.DefinitionExpression = artistFilter; // Make sure all layers are visible except tours _artistHometownLayer.IsVisible = true; _listenerLayer.IsVisible = true; _otherLocationsLayer.IsVisible = true; _tourLayer.IsVisible = false; // Dismiss any tour event callouts ArtistMapView.DismissCallout(); // Zoom the main map to the artist hometown await ArtistMapView.SetViewpointCenterAsync(ti.HometownLocation, 250000); // Zoom the listener map to the extent of features in the listener layer QueryParameters query = new QueryParameters { WhereClause = artistFilter }; FeatureQueryResult listenerQueryResult = await _listenerLayer.FeatureTable.QueryFeaturesAsync(query); EnvelopeBuilder extentBuilder = new EnvelopeBuilder(ListenersMapView.SpatialReference); foreach (Feature f in listenerQueryResult) { extentBuilder.UnionOf(f.Geometry.Extent); } Envelope extent = extentBuilder.ToGeometry(); if (extent.IsEmpty) { return; } await ListenersMapView.SetViewpointGeometryAsync(extentBuilder.ToGeometry(), 30); }
/// <summary> /// Zoom to the specified location /// </summary> /// <param name="extent">The extent of the geocoded candidate</param> /// <returns></returns> public static Task ZoomToLocation(CandidateExtent extent) { return(QueuedTask.Run(() => { ArcGIS.Core.Geometry.SpatialReference spatialReference = SpatialReferenceBuilder.CreateSpatialReference(extent.WKID); ArcGIS.Core.Geometry.Envelope envelope = EnvelopeBuilder.CreateEnvelope(extent.XMin, extent.YMin, extent.XMax, extent.YMax, spatialReference); //apply extent MapView.Active.ZoomTo(GeometryEngine.Expand(envelope, 3, 3, true)); })); }
public override bool CompareEnvelopes() { _logger.Info(LoggerMessage.COMPARE_ENVELOPES); if (ViewToDisplay.ModelToView.CompareTo(EnvelopeBuilder.Create()) != 0) { return(true); } return(false); }
private EnvelopeBuilder GetExtentFromDifferenceCursor(EnvelopeBuilder envelopeBuilder, DifferenceCursor differenceCursor) { while (differenceCursor.MoveNext()) { using (Feature differenceFeature = differenceCursor.Current as Feature) { Envelope newEnvelope = differenceFeature.GetShape().Extent; envelopeBuilder = Union(envelopeBuilder, newEnvelope); } } return(envelopeBuilder); }
private EnvelopeBuilder Union(EnvelopeBuilder envelopeBuilder, Envelope newEnvelope) { if (envelopeBuilder.IsEmpty) { return(new EnvelopeBuilder(newEnvelope)); } else { envelopeBuilder.Union(newEnvelope); return(envelopeBuilder); } }
public void DispatchCommand(object command, Action<EnvelopeBuilder> builder = null) { var envelopeBuilder = new EnvelopeBuilder(Guid.NewGuid().ToString()); envelopeBuilder.AddItem(command); if (builder != null) builder(envelopeBuilder); var envelope = envelopeBuilder.Build(); var data = _serializer.SaveEnvelopeData(envelope); if (!_tapeStream.TryAppend(data)) throw new InvalidOperationException("Failed to record domain log"); _aggregateFactory.Dispatch(envelope); }
public void command_sender_should_send_envelope() { // arrange var builder = new EnvelopeBuilder("env"); builder.AddItem(new CreateAccount(Identifier)); builder.AddItem(new CreateAccount(Identifier)); builder.AddItem(new CreateAccount(Identifier)); // act Sender.SendEnvelope(builder.Build()); // assert }
public void Envelope_attributes_should_be_present() { var time = DateTime.UtcNow; var builder = new EnvelopeBuilder("my-id"); builder.AddString("Custom", "1"); var envelope = RoundtripViaSerializer(builder); Assert.AreEqual("1", envelope.GetAttribute("Custom")); Assert.GreaterOrEqual(envelope.CreatedOnUtc, time, "start time"); var now = DateTime.UtcNow; Assert.LessOrEqual(envelope.CreatedOnUtc, now, "now"); }
void Dispatch(string id, IEnumerable<ICommand> commands) { var stream = _factory.GetOrCreateStream(id); var records = stream.ReadRecords(0, int.MaxValue).ToList(); var events = records .Select(tr => _streamer.ReadAsEnvelopeData(tr.Data)) .SelectMany(i => i.Items) .Select(i => (IEvent)i.Content) .ToList(); var then = AggregateFactory .LoadProject(events, commands) .Select(e => new MessageBuilder(e.GetType(), e)).ToList(); if (then.Count == 0) return; // events are stored here as envelopes ) var b = new EnvelopeBuilder("unknown"); foreach (var e in then) { b.Items.Add(e); } var version = records.Count == 0 ? 0 : records.Last().Version; var data = _streamer.SaveEnvelopeData(b.Build()); var result = stream.TryAppend( data, TapeAppendCondition.VersionIs(version)); if (!result) throw new InvalidOperationException( "Data was modified concurrently, and we don't have merging implemented, yet"); var args = _path.Split(':'); IQueueWriterFactory factory; if (!_queue.TryGet(args[0], out factory)) throw new InvalidOperationException("Not found " + _path); var arVersion = events.Count + 1; var arName = id; for (int i = 0; i < then.Count; i++) { var name = string.Format("{0}/{1}/{2}", arName, arVersion, i); var builder = new EnvelopeBuilder(name); builder.Items.Add(then[i]); builder.AddString("from-entity", arName); factory.GetWriteQueue(args[1]).PutMessage(builder.Build()); } }
public SetSpatialReference() { this.InitializeComponent(); // Create initial extend and set it note that this doesn't set MapView.SpatialReference. var envelopeBuilder = new EnvelopeBuilder(SpatialReference.Create(26777)); envelopeBuilder.XMin = 661140; envelopeBuilder.YMin = -1420246; envelopeBuilder.XMax = 3015668; envelopeBuilder.YMax = 1594451; MyMapView.Map.InitialViewpoint = new Esri.ArcGISRuntime.Controls.Viewpoint(envelopeBuilder.ToGeometry()); MyMapView.Map.SpatialReference = SpatialReference.Create(26777); //Force map spatial reference to Wkid=26777 }
private void SendMessage(object command, string optionalID = null) { var auth = FormsAuth.GetSessionIdentityFromRequest(); var envelopeId = optionalID ?? Guid.NewGuid().ToString().ToLowerInvariant(); var eb = new EnvelopeBuilder(envelopeId); if (auth.HasValue) { eb.AddString("web-user", auth.Value.User.Identifier.ToString(CultureInfo.InvariantCulture)); eb.AddString("web-token", auth.Value.Token); } eb.AddItem(command); m_queueWriter.PutMessage(eb.Build()); }
private void MapView_ExtentChanged(object sender, EventArgs e) { Envelope newExtent = null; if (MyMapView.WrapAround) { Geometry normalizedExtent = GeometryEngine.NormalizeCentralMeridian(MyMapView.Extent); if (normalizedExtent is Polygon) { var normalizedPolygon = (Polygon)normalizedExtent; if (normalizedPolygon.Parts.Count == 1) newExtent = normalizedPolygon.Extent; else { var newExtentBuilder = new EnvelopeBuilder(MyMapView.SpatialReference); foreach (var p in normalizedPolygon.Parts[0].GetPoints()) { if (p.X < newExtentBuilder.XMin || double.IsNaN(newExtentBuilder.XMin)) newExtentBuilder.XMin = p.X; if (p.Y < newExtentBuilder.YMin || double.IsNaN(newExtentBuilder.YMin)) newExtentBuilder.YMin = p.Y; } foreach (var p in normalizedPolygon.Parts[1].GetPoints()) { if (p.X > newExtentBuilder.XMax || double.IsNaN(newExtentBuilder.XMax)) newExtentBuilder.XMax = p.X; if (p.Y > newExtentBuilder.YMax || double.IsNaN(newExtentBuilder.YMax)) newExtentBuilder.YMax = p.Y; } newExtent = newExtentBuilder.ToGeometry(); } } else if (normalizedExtent is Envelope) newExtent = normalizedExtent as Envelope; } else newExtent = MyMapView.Extent; MinXNormalized.Text = newExtent.XMin.ToString("0.000"); MinYNormalized.Text = newExtent.YMin.ToString("0.000"); MaxXNormalized.Text = newExtent.XMax.ToString("0.000"); MaxYNormalized.Text = newExtent.YMax.ToString("0.000"); }
public override void Handle(IHttpContext context) { var msg = new EnvelopeBuilder(Guid.NewGuid().ToString()); var contract = context.GetRequestUrl().Remove(0,"/send/".Length); Type contractType; if (!_serializer.TryGetContractTypeByName(contract, out contractType)) { context.WriteString(string.Format("Trying to post command with unknown contract '{0}'.", contract)); context.SetStatusTo(HttpStatusCode.BadRequest); return; } _writer.PutMessage(_streamer.SaveEnvelopeData(msg.Build())); context.WriteString(string.Format(@" Normally this should be a JSON POST, containing serialized data for {0} but let's pretend that you successfully sent a message. Or routed it", contractType)); context.SetStatusTo(HttpStatusCode.OK); }
public void AppendToStream(IIdentity id, long originalVersion, ICollection<IEvent> events) { if (events.Count == 0) return; var stream = _factory.GetOrCreateStream(IdentityConvert.ToStream(id)); var b = new EnvelopeBuilder("unknown"); foreach (var e in events) { b.AddItem((object)e); } var data = _streamer.SaveEnvelopeData(b.Build()); var result = stream.TryAppend(data, TapeAppendCondition.VersionIs(originalVersion)); if (result == 0) { // this is temporary implementation throw OptimisticConcurrencyException.Create(-1, originalVersion, id, null); } PublishDomainSuccess(id, events, originalVersion); }
public override void Handle(IHttpContext context) { var contract = context.GetRequestUrl().Remove(0, "/mouseevents/".Length); var envelopeBuilder = new EnvelopeBuilder(contract + " - " + DateTime.Now.Ticks.ToString()); Type contractType; if (!_serializer.TryGetContractTypeByName(contract, out contractType)) { context.WriteString(string.Format("Trying to post command with unknown contract '{0}'.", contract)); context.SetStatusTo(HttpStatusCode.BadRequest); return; } var decodedData = HttpUtility.UrlDecode(context.Request.QueryString.ToString()); var mouseEvent = JsonSerializer.DeserializeFromString(decodedData, contractType); envelopeBuilder.AddItem(mouseEvent); _writer.PutMessage(_streamer.SaveEnvelopeData(envelopeBuilder.Build())); context.SetStatusTo(HttpStatusCode.OK); }
public void Multiple_payloads_are_handled_in_sequence() { var builder = new EnvelopeBuilder("my-id"); for (int i = 0; i < 5; i++) { var content = new string('*',i); var added = builder.AddItem(new MyMessage(content)); added.AddAttribute("hum", i.ToString()); } var envelope = RoundtripViaSerializer(builder); Assert.AreEqual(5, envelope.Items.Length); for (int i = 0; i < 5; i++) { var messageItem = envelope.Items[i]; Assert.AreEqual(new string('*', i), ((MyMessage)messageItem.Content).Value); Assert.AreEqual(i.ToString(), messageItem.GetAttribute("hum", "")); } }
public Task<bool> SelectFeaturesInDxLayers() { try { File.Delete(Common.GetConfiguration("DesignTxt")); } catch { } string designNameAndExpressDesignID = SelectedDesign.ToString(); int firstParen = designNameAndExpressDesignID.IndexOf("("); int lastParen = designNameAndExpressDesignID.IndexOf(")"); int selectedDesign = Convert.ToInt32(designNameAndExpressDesignID.Substring(firstParen + 1, lastParen - firstParen - 1)); var featuresInDesign = DxCommisionModel.GetFeaturesInDesign(selectedDesign); Dictionary<string, int> idsByName = new Dictionary<string, int>(); foreach (KeyValuePair<int, string> kvp in DxCommisionModel.GetNameByID) { if (kvp.Value != null && kvp.Key != null) { idsByName.Add(kvp.Value, kvp.Key); } } Dictionary<string, string> objectIDsToSelectByLayer = new Dictionary<string, string>(); foreach (var dxFe in featuresInDesign) { string className = DxCommisionModel.GetNameByID[dxFe.FeatureClassID]; if (objectIDsToSelectByLayer.ContainsKey(className) == false) { objectIDsToSelectByLayer.Add(className,dxFe.FeatureOID.ToString()); } else { objectIDsToSelectByLayer[className] += "," + dxFe.FeatureOID.ToString(); } } return QueuedTask.Run(() => { EnvelopeBuilder envBuilder = new EnvelopeBuilder(); if (true) { #region Get Extent from ArcGIS Pro StreamWriter sw = File.CreateText(Common.GetConfiguration("DesignTxt")); //Determine the extent //EnvelopeBuilder envBuilder = new EnvelopeBuilder(); envBuilder.XMin = 0; envBuilder.XMax = 0; envBuilder.YMin = 0; envBuilder.YMax = 0; var env = envBuilder.ToGeometry().Extent; List<FeatureLayer> dxLayers = GetDxLayers(); foreach (var f in dxLayers) { try { if (objectIDsToSelectByLayer.ContainsKey(f.Name)) { var oids = objectIDsToSelectByLayer[f.Name]; if (oids.Count() > 0) { Table table = f.GetTable(); sw.WriteLine(f.Name); foreach (string oid in oids.Split(',')) { List<Row> features = null; features = GetRowListFor(table, new QueryFilter { WhereClause = "OBJECTID = " + oid }); using (var feature = features[0]) { Geometry shape = feature.GetOriginalValue(feature.FindField("SHAPE")) as Geometry; Common.UnionEnvelopes(envBuilder, shape); sw.WriteLine(oid); } } } } } catch (Exception ex) { if (Common.GetConfiguration("DebugMessages") == "True") { MessageBox.Show("ERROR : " + ex.ToString()); } } finally { } } //Select the features //if (Common.GetConfiguration("DebugMessages") == "True") //{ // MessageBox.Show("About to close the stream"); //} sw.Close(); //if (Common.GetConfiguration("DebugMessages") == "True") //{ //MessageBox.Show("closed the stream stream"); //} ArcGIS.Core.Data.QueryFilter qf = new ArcGIS.Core.Data.QueryFilter(); //if (Common.GetConfiguration("DebugMessages") == "True") //{ // MessageBox.Show("dx layer count is " + dxLayers.Count); //} foreach (FeatureLayer fl in dxLayers) { if (objectIDsToSelectByLayer.ContainsKey(fl.Name)) { qf.WhereClause = "OBJECTID in (" + objectIDsToSelectByLayer[fl.Name] + ")"; //if (Common.GetConfiguration("DebugMessages") == "True") //{ // MessageBox.Show("Where clause for " + fl.Name + " : " + qf.WhereClause); //} try { fl.Select(qf, ArcGIS.Desktop.Mapping.SelectionCombinationMethod.New); //New works, add throws error } catch (Exception ex) { //MessageBox.Show("Selection Error " + ex.ToString()); } } } //Zoom to it //if (Common.GetConfiguration("DebugMessages") == "True") //{ // MessageBox.Show("About to zoom"); //} #endregion } else { //Get from ArcObjects } Map activeMap = MapView.Active.Map; var extent = envBuilder.ToGeometry().Extent; var expandedExtent = extent.Expand(1.2, 1.2, true); MapView.Active.ZoomTo(expandedExtent); return true; }); //return Task.FromResult(true); }
private static EditOperation CreateOperationAndBuildInitialEnvelope(ref EnvelopeBuilder envBuilder, ref ArcGIS.Core.Geometry.Envelope env) { var createOperation = new EditOperation(); createOperation.Name = "Highlight Design Features"; createOperation.SelectNewFeatures = false; if (envBuilder == null) { envBuilder = new EnvelopeBuilder(); envBuilder.XMin = 0; envBuilder.XMax = 0; envBuilder.YMin = 0; envBuilder.YMax = 0; env = envBuilder.ToGeometry().Extent; } return createOperation; }
void InnerSendBatch(Action<EnvelopeBuilder> configure, object[] messageItems, IdGeneration id = IdGeneration.Default) { string envelopeId; switch (id) { case IdGeneration.Default: envelopeId = _idGenerator(); break; case IdGeneration.HashContent: envelopeId = HashContents(configure, messageItems); break; default: throw new ArgumentOutOfRangeException("id"); } var builder = new EnvelopeBuilder(envelopeId); foreach (var item in messageItems) { builder.AddItem(item); } configure(builder); var envelope = builder.Build(); var data = _streamer.SaveEnvelopeData(envelope); var queue = GetOutboundQueue(); queue.PutMessage(data); SystemObserver.Notify(new EnvelopeSent(queue.Name, envelope.EnvelopeId, envelope.Items.Select(x => x.MappedType.Name).ToArray(), envelope.GetAllAttributes())); }
string HashContents(Action<EnvelopeBuilder> configure, object[] messageItems) { var builder = new EnvelopeBuilder("hash"); builder.OverrideCreatedOnUtc(DateTime.MinValue); foreach (var item in messageItems) { builder.AddItem(item); } configure(builder); var envelope = builder.Build(); var data = _streamer.SaveEnvelopeData(envelope); using (var sha1 = new SHA1Managed()) { var hash = sha1.ComputeHash(data); return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant(); } }
protected override ImmutableEnvelope RoundtripViaSerializer(EnvelopeBuilder builder) { var bytes = _streamer.SaveEnvelopeData(builder.Build()); return _streamer.ReadAsEnvelopeData(bytes); }
public static ArcGIS.Core.Geometry.Geometry GetGeometry(int featureClassID, int OID, out bool isLine, FeatureLayer lineFeatureLayer, FeatureLayer pointFeatureLayer) { isLine = true; IFeatureClass fc = null; if(_fcIDToFeatureClass.ContainsKey(featureClassID) == false) { IFeatureWorkspaceManage2 fwsm2 = (IFeatureWorkspaceManage2)_fws; string className = fwsm2.GetObjectClassNameByID(featureClassID); _fcIDToFeatureClass.Add(featureClassID,_fws.OpenFeatureClass(className) ); } fc = _fcIDToFeatureClass[featureClassID]; var shape = fc.GetFeature(OID).Shape; if (shape.GeometryType == ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint) { IPoint pnt = (IPoint)shape; //var coord = new Coordinate(xCoord, yCoord); //newMapPoint = MapPointBuilder.CreateMapPoint(coord, spatialReference); isLine = false; } else { isLine = true; } bool isLineForLambda = isLine; QueuedTask.Run(() => { EnvelopeBuilder envBuilder = new EnvelopeBuilder(); envBuilder.XMin = 0; envBuilder.XMax = 0; envBuilder.YMin = 0; envBuilder.YMax = 0; var env = envBuilder.ToGeometry().Extent; var pntFeatureClass = pointFeatureLayer.GetTable() as ArcGIS.Core.Data.FeatureClass; var pntClassDefinition = pntFeatureClass.GetDefinition() as FeatureClassDefinition; var spatialReference = pntClassDefinition.GetSpatialReference(); var createOperation = new EditOperation(); createOperation.Name = "Highlight Design Features"; createOperation.SelectNewFeatures = false; if (isLineForLambda == false) //point { IPoint pnt = (IPoint)shape; var coord = new Coordinate(pnt.X,pnt.Y); var newMapPoint = MapPointBuilder.CreateMapPoint(coord, spatialReference); // queue feature creation createOperation.Create(pointFeatureLayer, newMapPoint); Common.UnionEnvelopes(envBuilder, newMapPoint); } else { IPointCollection pc = (IPointCollection)shape; var lineCoordinates = new List<Coordinate>(pc.PointCount); for (int i = 0; i < pc.PointCount; i++) { var vertex = new Coordinate(pc.get_Point(i).X, pc.get_Point(i).Y); lineCoordinates.Add(vertex); var newPolyline = PolylineBuilder.CreatePolyline(lineCoordinates, spatialReference); createOperation.Create(lineFeatureLayer, newPolyline); Common.UnionEnvelopes(envBuilder, newPolyline); } } }); return null; }
void InnerSendBatch(Action<EnvelopeBuilder> configure, object[] messageItems) { var id = _idGenerator(); var builder = new EnvelopeBuilder(id); foreach (var item in messageItems) { builder.AddItem(item); } configure(builder); var envelope = builder.Build(); SendEnvelope(envelope); }
/// <summary> /// This method must be called on the MCT /// </summary> /// <remarks>If multiple features are selected just the ObjectID of the first feature /// in the selected set is returned</remarks> /// <param name="point"></param> /// <returns>The object id of the selected feature or -1</returns> internal static Polyline SelectLineFeature(MapPoint point) { if (OnUIThread) throw new CalledOnWrongThreadException(); var pt = MapView.Active.MapToClient(point); double llx = pt.X - 5; double lly = pt.Y - 5; double urx = pt.X + 5; double ury = pt.Y + 5; EnvelopeBuilder envBuilder = new EnvelopeBuilder(MapView.Active.ClientToMap(new Point(llx, lly)), MapView.Active.ClientToMap(new Point(urx, ury))); //Just get feature layers that are line types var selection = MapView.Active.SelectFeatures(envBuilder.ToGeometry()).Where( k => k.Key.ShapeType == esriGeometryType.esriGeometryPolyline ).ToList(); Polyline selectedLine = null; if (selection.Count() > 0) { //return the first of the selected features var flayer = selection.First().Key; var oid = selection.First().Value[0]; var inspector = new Inspector(); inspector.Load(flayer, oid); selectedLine = inspector["SHAPE"] as Polyline; } return selectedLine; }
private void DecorateEnvelope(EnvelopeBuilder builder) { PutLocalIP(builder); }
protected override ImmutableEnvelope RoundtripViaSerializer(EnvelopeBuilder builder) { return builder.Build(); }