Пример #1
0
        private void SetParameters(SQLiteCommand cmd, Envelope window)
		{
			cmd.Parameters[0].Value = window.MinX;
			cmd.Parameters[1].Value = window.MinY;
			cmd.Parameters[2].Value = window.MaxX;
			cmd.Parameters[3].Value = window.MaxY;
		}
Пример #2
0
        public Envelope CreateEnvelope(Envelope original)
        {
            var outgoing = original.ForResponse(_outgoing);
            outgoing.ExecutionTime = Time;

            return outgoing;
        }
Пример #3
0
 public Envelope Reproject(Envelope envelope, ISpatialReference @from, ISpatialReference to)
 {
     double[] xy;
     ToDotSpatial(envelope, out xy);
     DotSpatial.Projections.Reproject.ReprojectPoints(xy, null, GetProjectionInfo(@from), GetProjectionInfo(to), 0, 4);
     return ToGeoAPI(xy);
 }
 private static Envelope ComputeVertexEnvelope(IEnumerable<Vertex> vertices)
 {
     Envelope env = new Envelope();
     foreach (Vertex v in vertices)
         env.ExpandToInclude(v.Coordinate);
     return env;
 }
Пример #5
0
        public Envelope CreateEnvelope(Envelope original)
        {
            var response = original.ForResponse(_outgoing);
            response.Destination = original.ReplyUri;

            return response;
        }
        public override void Execute(object parameter)
        {
            if (Layer == null)
                return;

            GraphicsLayer graphicsLayer = Layer as GraphicsLayer;
            if (graphicsLayer == null)
                return;

            IEnumerable<Graphic> SelectedGraphics = graphicsLayer.SelectedGraphics;
            if (Map != null && SelectedGraphics != null)
            {
                Envelope newMapExtent = null;
                foreach (Graphic graphic in SelectedGraphics)
                {
                    if (graphic.Geometry != null && graphic.Geometry.Extent != null)
                        newMapExtent = graphic.Geometry.Extent.Union(newMapExtent);
                }
                if (newMapExtent != null)
                {
                    if (newMapExtent.Width > 0 || newMapExtent.Height > 0)
                    {
                        newMapExtent = new Envelope(newMapExtent.XMin - newMapExtent.Width * EXPAND_EXTENT_RATIO, newMapExtent.YMin - newMapExtent.Height * EXPAND_EXTENT_RATIO,
                            newMapExtent.XMax + newMapExtent.Width * EXPAND_EXTENT_RATIO, newMapExtent.YMax + newMapExtent.Height * EXPAND_EXTENT_RATIO);
                        Map.ZoomTo(newMapExtent);
                    }
                    else
                        Map.PanTo(newMapExtent);
                }
            }
        }
        public static IGeometry Grid(IGeometry g, int nCells)
        {
            var geoms = new List<IGeometry>();

            var env = FunctionsUtil.GetEnvelopeOrDefault(g);
            var geomFact = FunctionsUtil.GetFactoryOrDefault(g);

            var nCellsOnSide = (int) Math.Sqrt(nCells) + 1;
            var cellSizeX = env.Width/nCellsOnSide;
            var cellSizeY = env.Height/nCellsOnSide;

            for (var i = 0; i < nCellsOnSide; i++)
            {
                for (var j = 0; j < nCellsOnSide; j++)
                {
                    var x1 = env.MinX + i * cellSizeX;
                    var y1 = env.MinY + j * cellSizeY;
                    var x2 = env.MinX + (i+1) * cellSizeX;
                    var y2 = env.MinY + (j+1) * cellSizeY;
                    var cellEnv = new Envelope(x1, x2, y1, y2);

                    geoms.Add(geomFact.ToGeometry(cellEnv));
                }
            }
            return geomFact.BuildGeometry(geoms);
        }
 private Envelope Expand(Envelope e)
 {
     double factor = 0.6;
     MapPoint centerMapPoint = e.GetCenter();
     return new Envelope(centerMapPoint.X - e.Width * factor, centerMapPoint.Y - e.Height * factor,
         centerMapPoint.X + e.Width * factor, centerMapPoint.Y + e.Height * factor);
 }
Пример #9
0
 public void Execute(Envelope envelope, ContinuationContext context)
 {
     envelope.Message = null; // Prevent the error from throwing again.
     context.SendFailureAcknowledgement(envelope, "Deserialization failed");
     context.Logger.Error(envelope.CorrelationId, _exception.Message, _exception);
     envelope.Callback.MoveToErrors(new ErrorReport(envelope, _exception));
 }
Пример #10
0
        public virtual async Task Invoke(Envelope envelope, IEnvelopeContext context)
        {
            envelope.Attempts++; // needs to be done here.
            IContinuation continuation = null;

            try
            {
                continuation = await FindContinuation(envelope, context).ConfigureAwait(false);
                continuation.Execute(envelope, context);
            }
            catch (EnvelopeDeserializationException ex)
            {
                new DeserializationFailureContinuation(ex).Execute(envelope, context);
            }
            catch (AggregateException e)
            {
                e.Flatten().InnerExceptions.Each(ex =>
                {
                    envelope.Callback.MarkFailed(e);
                    var message = "Failed while invoking message {0} with continuation {1}".ToFormat(envelope.Message ?? envelope,
                        (object)continuation ?? "could not find continuation");

                    context.Error(envelope.CorrelationId, message, e);
                });
            }
            catch (Exception e)
            {
                envelope.Callback.MarkFailed(e); // TODO -- watch this one.
                var message = "Failed while invoking message {0} with continuation {1}".ToFormat(envelope.Message ?? envelope,
                    (object)continuation ?? "could not find continuation");
                context.Error(envelope.CorrelationId, message, e);
            }
        }
Пример #11
0
        protected override void GetSource( Envelope extent, int width, int height, DynamicLayer.OnImageComplete onComplete )
        {
            _currentWidth = width;
            _currentHeight = height;

            MapPoints = new List<MapPoint>();

            //Make up some dummy data
            int count = 0;
            while( count < 1000 )
            {
                MapPoints.Add( new MapPoint( extent.XMin + ( extent.Width * ( _random.Next( 100 ) / 100.00 ) ),
                    extent.YMin + ( extent.Height * ( _random.Next( 100 ) / 100.00 ) ),
                    extent.SpatialReference ) );
                count++;
            }
            //Make up some dummy data

            _pngRenderer = new PixelPngRenderer( _currentWidth, _currentHeight, MapPoints );

            ParameterizedThreadStart starter = new ParameterizedThreadStart( ( pngRenderer ) =>
            {
                Stream imageStream = InitalizeImage( pngRenderer as PixelPngRenderer );

                Dispatcher.BeginInvoke( () =>
                {
                    _image = new BitmapImage();
                    _image.SetSource( imageStream );
                    onComplete( _image, width, height, extent );
                } );
            } );
            new Thread( starter ).Start( _pngRenderer );
        }
Пример #12
0
        public void AddWhenTimoutAndMultipleObjectsTest()
        {
            var _objects = new Quadtree<object>();
            var _newObject = new object();
            var _newObject2 = new object();

            var _envelope = new Envelope(new Coordinate(1, 1));
            var _envelope2 = new Envelope(new Coordinate(2, 2));

            Parallel.Invoke(
                () =>
                    {
                        _objects.Add(_envelope, _newObject, 100, () => _objects.Remove(_envelope, _newObject));
                        _objects.Add(_envelope2, _newObject2, 500, () => _objects.Remove(_envelope2, _newObject2));
                    },
                () =>
                    {
                        Thread.Sleep(10);

                        Assert.IsTrue(_objects.Contains(_envelope));
                        Assert.IsTrue(_objects.Contains(_envelope2));

                        Thread.Sleep(250);
                    }
                );

            Assert.IsFalse(_objects.Contains(_envelope));
            Assert.IsTrue(_objects.Contains(_envelope2));
        }
Пример #13
0
        // virtual for testing as usual
        public virtual async Task<IContinuation> FindContinuation(Envelope envelope, IEnvelopeContext context)
        {
            foreach (var handler in _handlers)
            {
                var continuation = await handler.Handle(envelope).ConfigureAwait(false);
                if (continuation != null)
                {
                    context.DebugMessage(() => new EnvelopeContinuationChosen
                    {   
                        ContinuationType = continuation.GetType(),
                        HandlerType = handler.GetType(),
                        Envelope = envelope.ToToken()
                    });

                    return continuation;
                }
            }

            // TODO - add rules for what to do when we have no handler
            context.DebugMessage(() => new EnvelopeContinuationChosen
            {
                ContinuationType = typeof(MoveToErrorQueue),
                HandlerType = typeof(HandlerPipeline),
                Envelope = envelope.ToToken()
            });

            return new MoveToErrorQueue(new NoHandlerException(envelope.Message.GetType()));
        }
Пример #14
0
        public void Send(object message, IDictionary<string, string> headers)
        {
            // create an envelope for the message
            Envelope newEnvelope = new Envelope();
            newEnvelope.Headers = headers ?? new Dictionary<string, string>();

            // create a message context for message processing
            MessageContext ctx = new MessageContext(
                MessageContext.Directions.Out, newEnvelope, message);

            // process the message
            this.ProcessMessage(ctx, () =>
            {
                try
                {
                    _envelopeSender.Send(ctx.Envelope);
                }
                catch (Exception ex)
                {
                    string msg = "Failed to send an envelope.";
                    Log.Error(msg, ex);
                    throw new MessageException(msg, ex);
                }
            });
        }
Пример #15
0
        /// <summary>
        /// Serialize an envelope
        /// to a string
        /// </summary>
        /// <param name="envelope"></param>
        /// <returns></returns>
        public string Serialize(Envelope envelope)
        {            
            if (envelope == null)
            {
                throw new ArgumentNullException("envelope");
            }

            if (envelope is Notification)
            {
                return JsonSerializer<Notification>.Serialize((Notification)envelope);
            }
            else if (envelope is Message)
            {
                return JsonSerializer<Message>.Serialize((Message)envelope);
            }
            else if (envelope is Command)
            {
                return JsonSerializer<Command>.Serialize((Command)envelope);
            }
            else if (envelope is Session)
            {
                return JsonSerializer<Session>.Serialize((Session)envelope);
            }
            else
            {
                throw new ArgumentException("The envelope type is unknown");
            }
        }
Пример #16
0
        public Sid(int[][] newWaveformTable, int sampleRate, int cyclesNum, int cyclesDen)
        {
            _sampleRate = sampleRate;
            _cpuCyclesNum = cyclesNum;
		    _sampleCyclesDen = cyclesDen*sampleRate;

            _envelopes = new Envelope[3];
			for (var i = 0; i < 3; i++)
				_envelopes[i] = new Envelope();
		    _envelope0 = _envelopes[0];
            _envelope1 = _envelopes[1];
            _envelope2 = _envelopes[2];

            _voices = new Voice[3];
			for (var i = 0; i < 3; i++)
				_voices[i] = new Voice(newWaveformTable);
		    _voice0 = _voices[0];
            _voice1 = _voices[1];
            _voice2 = _voices[2];

            _filterEnable = new bool[3];
			for (var i = 0; i < 3; i++)
				_filterEnable[i] = false;

		    _outputBuffer = new short[sampleRate];
		}
Пример #17
0
 public IGeometryReader ExecuteGeometryReader(SpatialPredicate predicate, Envelope envelope)
 {
     if (predicate != SpatialPredicate.Intersects)
         throw new NotSupportedException();
     
     return new ProviderGeometryReader(_provider.GetGeometriesInView(envelope));
 }
Пример #18
0
 public override Task Send(Envelope envelope, params string[] messages)
 {
     var payload = Tuple.Create(envelope, messages);
     _messages.Add(payload);
     _messagesObservable.OnNext(payload);
     return base.Send(envelope, messages);
 }
 public static Envelope BuildStreamingEnvelope(string sequenceId, int position)
 {
     Envelope envelope = new Envelope();
     envelope.Headers.Add(SEC.SEQUENCE_ID, sequenceId);
     envelope.Headers.Add(SEC.POSITION, position + "");
     return envelope;
 }
        public void Execute(Envelope envelope, ContinuationContext context)
        {
            context.Outgoing.SendOutgoingMessages(envelope, _context.OutgoingMessages());

            envelope.Callback.MarkSuccessful();
            context.Logger.InfoMessage(() => new MessageSuccessful {Envelope = envelope.ToToken()});
        }
Пример #21
0
        private BrokeredMessage BuildMessage(Envelope<ICommand> command)
        {
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);
            this.serializer.Serialize(writer, command.Body);
            stream.Position = 0;

            var message = new BrokeredMessage(stream, true);
            if (!default(Guid).Equals(command.Body.Id))
            {
                message.MessageId = command.Body.Id.ToString();
            }

            var metadata = this.metadataProvider.GetMetadata(command.Body);
            if (metadata != null)
            {
                foreach (var pair in metadata)
                {
                    message.Properties[pair.Key] = pair.Value;
                }
            }

            if (command.Delay != TimeSpan.Zero)
                message.ScheduledEnqueueTimeUtc = DateTime.UtcNow.Add(command.Delay);

            return message;
        }
Пример #22
0
        private void WorldFileLoaded(object sender, DownloadStringCompletedEventArgs e)
        {
            //Checks to see if there was an error
            if (e.Error == null)
            {
                //grab the data from the world file
                string myData = e.Result;
                //split string into an array based on new line characters
                string[] lines = myData.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
                //convert the strings into doubles
                double[] coordValues = new double[6];
                for(int i = 0; i < 6; i++) {
                    coordValues[i] = Convert.ToDouble(lines[i]);
                }
                //calculate the pixel height and width in real world coordinates
                double pixelWidth = Math.Sqrt(Math.Pow(coordValues[0], 2) + Math.Pow(coordValues[1], 2));
                double pixelHeight = Math.Sqrt(Math.Pow(coordValues[2], 2) + Math.Pow(coordValues[3], 2));

                //Create a map point for the top left and bottom right
                MapPoint topLeft = new MapPoint(coordValues[4], coordValues[5]);
                MapPoint bottomRight = new MapPoint(coordValues[4] + (pixelWidth * imageWidth), coordValues[5] + (pixelHeight * imageHeight));
                //create an envelope for the elmently layer
                Envelope extent = new Envelope(topLeft.X, topLeft.Y, bottomRight.X, bottomRight.Y);
                ElementLayer.SetEnvelope(image, extent);
                //Zoom to the extent of the image
                MyMap.Extent = extent;
            }
        }
        private void Initialize()
        {
            // Create new Map with basemap
            Map myMap = new Map(Basemap.CreateTopographic());

            // Create and set initial map area
            Envelope initialLocation = new Envelope(
                -1.30758164047166E7, 4014771.46954516, -1.30730056797177E7, 4016869.78617381,
                SpatialReferences.WebMercator);
            myMap.InitialViewpoint = new Viewpoint(initialLocation);

            // Create uri to the used feature service
            var serviceUri = new Uri(
               "http://sampleserver6.arcgisonline.com/arcgis/rest/services/PoolPermits/FeatureServer/0");

            // Create feature table for the pools feature service
            ServiceFeatureTable poolsFeatureTable = new ServiceFeatureTable(serviceUri);

            // Define the request mode
            poolsFeatureTable.FeatureRequestMode = FeatureRequestMode.OnInteractionNoCache;

            // Create FeatureLayer that uses the created table
            FeatureLayer poolsFeatureLayer = new FeatureLayer(poolsFeatureTable);

            // Add created layer to the map
            myMap.OperationalLayers.Add(poolsFeatureLayer);

            // Assign the map to the MapView
            MyMapView.Map = myMap;
        }
Пример #24
0
        public void Should_Not_Continue_Processing_If_Processor_Does_Not_Call_Continuation()
        {
            // create an envelope and context
            Envelope env = new Envelope() { Payload = Encoding.UTF8.GetBytes("Test") };
            EnvelopeContext ctx = new EnvelopeContext(EnvelopeContext.Directions.In, env);

            // mock a transport provider and envelope processor
            Mock<ITransportProvider> txMock = _mocker.Create<ITransportProvider>();
            Mock<IEnvelopeProcessor> procMock = _mocker.Create<IEnvelopeProcessor>();

            // create a processor chain and add the mock processor to it
            List<IEnvelopeProcessor> processorChain = new List<IEnvelopeProcessor>();
            processorChain.Add(procMock.Object);

            // the continuation that, if called, fails the test
            Action continuation = new Action( () =>
                Assert.Fail("The continuation action should not have been called"));

            // this is what we're testing (extended class gives public access to protected method)
            ExtendedDefaultEnvelopeBus bus = new ExtendedDefaultEnvelopeBus(txMock.Object);
            bus.PublicProcessEnvelope(ctx, processorChain, continuation);

            // make sure that the processor was called once
            procMock.Verify(proc => proc.ProcessEnvelope(ctx, It.IsAny<Action>()), Times.Once());

            // and that since it did nothing, the transport provider didn't get the envelope
            txMock.Verify(tx => tx.Send(env), Times.Never());
        }
Пример #25
0
        public static FeatureDataRow FindGeoNearPoint(GeoAPI.Geometries.IPoint point, VectorLayer layer, double amountGrow)
        {
            var box = new Envelope(point.Coordinate);
            box.ExpandBy(amountGrow);

            var fds = new FeatureDataSet();
            layer.DataSource.ExecuteIntersectionQuery(box, fds);

            FeatureDataRow result = null;
            var minDistance = double.MaxValue;

            foreach (FeatureDataTable fdt in fds.Tables)
            {
                foreach (FeatureDataRow fdr in fdt.Rows)
                {
                    if (fdr.Geometry != null)
                    {
                        var distance = point.Distance(fdr.Geometry);
                        if (distance < minDistance)
                        {
                            result = fdr;
                            minDistance = distance;
                        }
                    }
                }
            }

            return result;
        }
Пример #26
0
        public void EnvelopeSizeCheck()
        {
            double w = 0;
            // Measure starting point memory use
            var start = GC.GetTotalMemory(true);

            // Allocate a new array of 100000 Extent classes.
            // If methods don't count, should be about 3,200,000 bytes.
            var memhog = new Envelope[100000];

            for (var i = 0; i < 100000; i++)
            {
                memhog[i] = new Envelope(new Coordinate(0, 0, 0), new Coordinate(1, 1, 1));
            }

            // Obtain measurements after creating the new byte[]
            var end = GC.GetTotalMemory(true);
            Debug.WriteLine("width: " + w);
            var size = (end - start) / 100000;

            // Ensure that the Array stays in memory and doesn't get optimized away
            Debug.WriteLine("Memory size of Extent = " + size);
            // Size of Envelope = 104

        }
Пример #27
0
        public async override Task Send(Envelope envelope, params string[] messages)
        {
            await base.Send(envelope, messages);
            

            if (messages == null)
            {
                return;
            }

            foreach (var message in messages.Where(message => !string.IsNullOrWhiteSpace(message)))
            {
                var escapedMessage = WebUtility.HtmlEncode(message);
                var args = JsonConvert.SerializeObject(new
                {
                    username = Robot.Name,
                    channel =
                        string.IsNullOrEmpty(envelope.User.Room)
                            ? envelope.User.Name
                            : _channelMapping.GetValueOrDefault(envelope.User.Room, envelope.User.Room),
                    text = escapedMessage,
                    link_names = _linkNames ? 1 : 0
                });

                await Post("/services/hooks/hubot", args);
            }
        }
Пример #28
0
        protected override void Process(object state)
        {
            Initialize();

            Successful = false;

            if (ReceivedEnvelope != null && ValidateProcessState())
            {
                ProcessRequest();
                Envelope reply = new Envelope()
                {
                    Message = CreateReply(),
                    Ep = ReceivedEnvelope.Ep
                };
                // the msgNr is the next one for this process
                // the convId is the same as the requester's convId
                reply.Message.SetMessageAndConversationNumbers(MessageNumber.Create(), ReceivedEnvelope.Message.ConvId);

                CommSubsystem.Communicator.Send(reply);
                Successful = true;
            }

            if (!Successful)
                ProcessFailure();
            
            Stop();
        }
Пример #29
0
        public override void Initialize()
        {
            FullExtent = new Envelope(-cornerCoordinate, -cornerCoordinate, cornerCoordinate, cornerCoordinate)
            {
                SpatialReference = new SpatialReference(WKID)
            };
            //This layer's spatial reference
            //Set up tile information. Each tile is 256x256px, 19 levels.
            TileInfo = new TileInfo
            {
                Height = 256,
                Width = 256,
                Origin = new MapPoint(-cornerCoordinate, cornerCoordinate) { SpatialReference = new SpatialReference(WKID) },
                Lods = new Lod[6]
            };
            //Set the resolutions for each level. Each level is half the resolution of the previous one.
            var resolution = cornerCoordinate * 2 / 256;
            for (var i = 0; i < TileInfo.Lods.Length; i++)
            {
                TileInfo.Lods[i] = new Lod { Resolution = resolution };
                resolution /= 2;
            }
            //Call base initialize to raise the initialization event
            base.Initialize();

            base.Initialize();
        }
Пример #30
0
        private static IGeometryCollection ClipGeometryCollection(IGeometryCollection geom, Envelope clipEnv)
        {
            var clipPoly = geom.Factory.ToGeometry(clipEnv);
            var clipped = new List<IGeometry>();
            for (var i = 0; i < geom.NumGeometries; i++)
            {
                var g = geom.GetGeometryN(i);
                IGeometry result = null;
                // don't clip unless necessary
                if (clipEnv.Contains(g.EnvelopeInternal))
                    result = g;
                else if (clipEnv.Intersects(g.EnvelopeInternal))
                {
                    result = clipPoly.Intersection(g);
                    // keep vertex key info
                    result.UserData = g.UserData;
                }

                if (result != null && !result.IsEmpty)
                {
                    clipped.Add(result);
                }
            }
            return geom.Factory.CreateGeometryCollection(GeometryFactory.ToGeometryArray(clipped));
        }
Пример #31
0
 public bool TryDequeue(out Envelope envelope)
 {
     return(_queue.TryTake(out envelope));
 }
Пример #32
0
 public EnvelopeContext(Directions direction, Envelope envelope)
     : this(direction)
 {
     this.Envelope = envelope;
 }
Пример #33
0
 /// <summary>
 /// Receiver for the input data.
 /// </summary>
 /// <param name="data">A buffer containing the input data.</param>
 /// <param name="e">The message envelope for the input data.</param>
 protected override void Receive(float[] data, Envelope e)
 {
     this.ComputeFFTPower(data, ref this.fftPower);
     this.Out.Post(this.fftPower, e.OriginatingTime);
 }
        private async void OnExecuteStatisticsQueryClicked(object sender, EventArgs e)
        {
            // Create definitions for each statistic to calculate
            StatisticDefinition statDefinitionAvgPop    = new StatisticDefinition("POP", StatisticType.Average, "");
            StatisticDefinition statDefinitionMinPop    = new StatisticDefinition("POP", StatisticType.Minimum, "");
            StatisticDefinition statDefinitionMaxPop    = new StatisticDefinition("POP", StatisticType.Maximum, "");
            StatisticDefinition statDefinitionSumPop    = new StatisticDefinition("POP", StatisticType.Sum, "");
            StatisticDefinition statDefinitionStdDevPop = new StatisticDefinition("POP", StatisticType.StandardDeviation, "");
            StatisticDefinition statDefinitionVarPop    = new StatisticDefinition("POP", StatisticType.Variance, "");

            // Create a definition for count that includes an alias for the output
            StatisticDefinition statDefinitionCount = new StatisticDefinition("POP", StatisticType.Count, "CityCount");

            // Add the statistics definitions to a list
            List <StatisticDefinition> statDefinitions = new List <StatisticDefinition>
            {
                statDefinitionAvgPop,
                statDefinitionCount,
                statDefinitionMinPop,
                statDefinitionMaxPop,
                statDefinitionSumPop,
                statDefinitionStdDevPop,
                statDefinitionVarPop
            };

            // Create the statistics query parameters, pass in the list of definitions
            StatisticsQueryParameters statQueryParams = new StatisticsQueryParameters(statDefinitions);

            // If only using features in the current extent, set up the spatial filter for the statistics query parameters
            if (OnlyInExtentSwitch.IsToggled)
            {
                // Get the current extent (envelope) from the map view
                Envelope currentExtent = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry as Envelope;

                // Set the statistics query parameters geometry with the envelope
                statQueryParams.Geometry = currentExtent;

                // Set the spatial relationship to Intersects (which is the default)
                statQueryParams.SpatialRelationship = SpatialRelationship.Intersects;
            }

            // If only evaluating the largest cities (over 5 million in population), set up an attribute filter
            if (OnlyBigCitiesSwitch.IsToggled)
            {
                // Set a where clause to get the largest cities (could also use "POP_CLASS = '5,000,000 and greater'")
                statQueryParams.WhereClause = "POP_RANK = 1";
            }

            try
            {
                // Execute the statistical query with these parameters and await the results
                StatisticsQueryResult statQueryResult = await _worldCitiesTable.QueryStatisticsAsync(statQueryParams);

                // Display results in the list box
                StatResultsList.ItemsSource = statQueryResult.First().Statistics.Select(m => $"{m.Key}:{m.Value}").ToList();
                ResultsGrid.IsVisible       = true;
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Error", ex.Message, "OK");
            }
        }
        /// <summary>
        /// Draw a branch with no segments; this will usually be drawn with the style for the default value.
        /// </summary>
        /// <param name="map"></param>
        /// <param name="coverage"></param>
        /// <param name="g"></param>
        /// <param name="style"></param>
        /// <param name="mapExtents"></param>
        /// <param name="drawnBranches"></param>
        /// <param name="theme"></param>
        private static void RenderSegmentFreeBranches(IMap map, INetworkCoverage coverage, Graphics g, VectorStyle style, Envelope mapExtents, HashSet <IBranch> drawnBranches, ITheme theme)
        {
            var visibleBranches = coverage.Network.Branches.Where(b => b.Geometry.EnvelopeInternal.Intersects(mapExtents)).ToList();

            visibleBranches.ForEach(vb =>
            {
                if (!drawnBranches.Contains(vb))
                {
                    VectorRenderingHelper.RenderGeometry(g, map, vb.Geometry, style, null, true);
                }
            });
        }
        public override IEnumerable <IFeature> GetFeatures(Envelope box, ILayer layer)
        {
            var coverage = (INetworkCoverage)((NetworkCoverageSegmentLayer)layer).Coverage;

            return(coverage.Segments.Values.Where(networkLocation => networkLocation.Geometry.EnvelopeInternal.Intersects(box)).Cast <IFeature>());
        }
Пример #37
0
        /// <summary>
        /// Receiver for the combined VAD signal and audio data.
        /// </summary>
        /// <param name="data">A message containing the combined VAD signal and audio data.</param>
        /// <param name="e">The message envelope</param>
        /// <returns>The <see cref="Task"/> representing the asynchronous operation.</returns>
        protected override async Task ReceiveAsync(ValueTuple <AudioBuffer, bool> data, Envelope e)
        {
            byte[] audioData = data.Item1.Data;
            bool   hasSpeech = data.Item2;

            this.lastAudioOriginatingTime = e.OriginatingTime;

            // Throw if a fatal error has occurred in the OnConversationError event handler
            if (this.fatalError)
            {
                if (this.conversationError != null)
                {
                    var error = this.conversationError;
                    this.conversationError = null;
                    throw error;
                }

                // Stop processing until the pipeline terminates
                return;
            }

            if (hasSpeech || this.lastAudioContainedSpeech)
            {
                // Send the audio data to the cloud
                await this.speechRecognitionClient.SendAudioAsync(audioData, this.cancellationTokenSource.Token);

                // Add audio to the current utterance queue so we can reconstruct it in the recognition result later
                this.currentQueue.Enqueue(data.DeepClone(this.In.Recycler));
            }

            // If this is the last audio packet containing speech
            if (!hasSpeech && this.lastAudioContainedSpeech)
            {
                this.lastVADSpeechEndTime      = e.OriginatingTime;
                this.lastVADSpeechTimeInterval = new TimeInterval(this.lastVADSpeechStartTime, this.lastVADSpeechEndTime);

                // Allocate a buffer large enough to hold the buffered audio
                BufferWriter bw = new BufferWriter(this.currentQueue.Sum(b => b.Item1.Length));

                // Get the audio associated with the recognized text from the current queue.
                ValueTuple <AudioBuffer, bool> buffer;
                while (this.currentQueue.TryDequeue(out buffer))
                {
                    bw.Write(buffer.Item1.Data);

                    // We are done with this buffer so enqueue it for recycling
                    this.In.Recycle(buffer);
                }

                // Save the buffered audio
                this.lastAudioBuffer = bw.Buffer;

                // Call EndAudio to signal that this is the last packet
                await this.speechRecognitionClient.SendEndAudioAsync(this.cancellationTokenSource.Token);
            }
            else if (hasSpeech && !this.lastAudioContainedSpeech)
            {
                // If this is the first audio packet containing speech
                this.lastVADSpeechStartTime = e.OriginatingTime;

                // Also post a null partial recognition result
                this.lastPartialResult = string.Empty;
                this.OutputResult(this.BuildPartialSpeechRecognitionResult(this.lastPartialResult), e.OriginatingTime);
            }

            // Remember last audio state.
            this.lastAudioContainedSpeech = hasSpeech;
        }
Пример #38
0
 public void Execute(Envelope envelope, IEnvelopeContext context)
 {
     context.Retry(envelope);
 }
        /// <summary>
        /// Toggles the query UI on or off
        /// </summary>
        public void Execute(object parameter)
        {
            ToolExecuting = true;

            // Updates tool DataContext with savedConfiguration.
            var toolViewModel = toolView.DataContext as QueryViewModel;

            if (toolViewModel == null)
            {
                toolViewModel        = savedConfiguration != null ? new QueryViewModel(savedConfiguration) : new QueryViewModel();
                toolView.DataContext = toolViewModel;
            }
            else if (savedConfiguration != null)
            {
                toolViewModel.ApplyChanges(savedConfiguration);
            }

            // Sets map and proxy url based on application settings.
            if (MapApplication.Current != null)
            {
                toolViewModel.Map = MapApplication.Current.Map;
                if (MapApplication.Current.Urls != null)
                {
                    toolViewModel.ProxyUrl = MapApplication.Current.Urls.ProxyUrl;
                }
            }

            // Updates default/selection on each query expression.
            toolViewModel.ResetExpressions();

            // Sets the result layer name.
            toolViewModel.SetLayerNameAction = (layer, title) =>
            {
                if (layer != null && !string.IsNullOrEmpty(title))
                {
                    var    index     = 1;
                    string layerName = title;
                    if (MapApplication.Current != null && MapApplication.Current.Map != null && MapApplication.Current.Map.Layers != null)
                    {
                        LayerCollection layers = MapApplication.Current.Map.Layers;
                        while (layers.Any(l => MapApplication.GetLayerName(l) == layerName))
                        {
                            index++;
                            layerName = string.Format("{0} ({1})", title, index);
                        }
                    }

                    MapApplication.SetLayerName(layer, layerName);
                }
            };

            // Adds result layer to map.
            toolViewModel.AddLayerAction = (layer) =>
            {
                if (layer != null)
                {
                    if (MapApplication.Current.Map != null && MapApplication.Current.Map.Layers != null)
                    {
                        if (!MapApplication.Current.Map.Layers.Contains(layer))
                        {
                            MapApplication.Current.Map.Layers.Add(layer);
                        }
                    }
                }
            };

            // Removes result layer from map.
            toolViewModel.RemoveLayerAction = (layer) =>
            {
                if (layer != null)
                {
                    if (MapApplication.Current.Map != null && MapApplication.Current.Map.Layers != null)
                    {
                        if (MapApplication.Current.Map.Layers.Contains(layer))
                        {
                            MapApplication.Current.Map.Layers.Remove(layer);
                        }
                    }
                }
            };

            // Updates layer selection on map after query is executed.
            toolViewModel.SelectLayerAction = (layer) =>
            {
                if (layer != null)
                {
                    MapApplication.Current.SelectedLayer = layer;
                }
            };

            // Zooms to result layer.
            toolViewModel.ZoomToExtentAction = (geometry) =>
            {
                if (geometry != null)
                {
                    var env = geometry.Extent;
                    if (env.Width > 0 || env.Height > 0)
                    {
                        env = new Envelope(env.XMin - env.Width * EXPAND_EXTENT_RATIO, env.YMin - env.Height * EXPAND_EXTENT_RATIO,
                                           env.XMax + env.Width * EXPAND_EXTENT_RATIO, env.YMax + env.Height * EXPAND_EXTENT_RATIO);
                        if (MapApplication.Current.Map != null)
                        {
                            MapApplication.Current.Map.ZoomTo(env);
                        }
                    }
                    else
                    {
                        if (MapApplication.Current.Map != null)
                        {
                            MapApplication.Current.Map.PanTo(env);
                        }
                    }
                }
            };

            // Updates visibility of data grid after query is expecuted.
            toolViewModel.UpdateDataGridVisibility = (visibility) =>
            {
                UpdateFeatureDataGridVisibility(visibility);
            };

            // Displays QueryToolView.
            MapApplication.Current.ShowWindow(toolViewModel.QueryTitle, toolView, false,
                                              null,
                                              (s, e) =>
            {
                ToolExecuting = false;
                // Clears map of query results when done.
                toolViewModel.ClearResults();

                foreach (ExpressionViewModel exp in toolViewModel.QueryExpressions)
                {
                    exp.ClearValidationExceptions();
                }
            },
                                              WindowType.Floating);

            // Executes query on click when there are no visible expression.
            if (!toolViewModel.HasVisibleExpression)
            {
                if (toolViewModel.Execute.CanExecute(null))
                {
                    toolViewModel.Execute.Execute(null);
                }
            }
        }
Пример #40
0
 private void Raise <T, TEvent>(T command, TEvent @event) where T : class where TEvent : AppEvent
 {
     RaiseEvent(Envelope.Create(SimpleMapper.Map(command, @event)));
 }
 public void ExecuteIntersectionQuery(Envelope box, FeatureDataSet ds)
 {
     ((ICanQueryLayer)_innerLayer).ExecuteIntersectionQuery(box, ds);
 }
 /// <summary>
 /// Sends the specified command.
 /// </summary>
 public void Send(Envelope <ICommand> command)
 {
     this.sender.Send(() => BuildMessage(command));
 }
Пример #43
0
 private static List <Point3D> Adapter(List <Point3D?> value, Envelope env)
 {
     return(value?.Where(p => p.HasValue).Select(p => p.Value).ToList());
 }
Пример #44
0
 /// <summary>
 ///     Sends the specified event.
 /// </summary>
 public void Publish(Envelope <IEvent> @event)
 {
     sender.Send(() => BuildMessage(@event));
 }
Пример #45
0
 public override SchemaState Apply(Envelope <IEvent> @event)
 {
     return(Clone().Update(@event, (e, s) => s.ApplyEvent(e)));
 }
Пример #46
0
        public AssetState Apply(Envelope <IEvent> @event)
        {
            var payload = (SquidexEvent)@event.Payload;

            return(Clone().Update(payload, @event.Headers, r => r.DispatchAction(payload)));
        }
Пример #47
0
        /// <summary>
        /// Gets the source image to display in the dynamic layer. Override this to generate
        /// or modify images.
        /// </summary>
        /// <param name="properties">The image export properties.</param>
        /// <param name="onComplete">The method to call when the image is ready.</param>
        /// <seealso cref="ESRI.ArcGIS.Client.DynamicLayer.OnProgress"/>
        protected override void GetSource(DynamicLayer.ImageParameters properties, DynamicLayer.OnImageComplete onComplete)
        {
            if (!IsInitialized || HeatMapPoints == null || HeatMapPoints.Count == 0)
            {
                onComplete(null, null);
                return;
            }
            Envelope extent = properties.Extent;
            int      width  = properties.Width;
            int      height = properties.Height;

            if (renderThread != null && renderThread.IsBusy)
            {
                renderThread.CancelAsync();                 //render already running. Cancel current process, and queue up new
                enqueueExport     = new ImageParameters(extent, width, height);
                enqueueOnComplete = onComplete;
                return;
            }

            //Accessing a GradientStop collection from a non-UI thread is not allowed,
            //so we used a private class gradient collection
            List <ThreadSafeGradientStop> stops = new List <ThreadSafeGradientStop>(Gradient.Count);

            foreach (GradientStop stop in Gradient)
            {
                stops.Add(new ThreadSafeGradientStop()
                {
                    Color = stop.Color, Offset = stop.Offset
                });
            }
            //Gradients must be sorted by offset
            stops.Sort((ThreadSafeGradientStop g1, ThreadSafeGradientStop g2) => { return(g1.Offset.CompareTo(g2.Offset)); });

            List <HeatPoint> points = new List <HeatPoint>();
            double           res    = extent.Width / width;
            //adjust extent to include points slightly outside the view so pan won't affect the outcome
            Envelope extent2 = new Envelope(extent.XMin - Intensity * res, extent.YMin - Intensity * res,
                                            extent.XMax + Intensity * res, extent.YMax + Intensity * res);

            //get points within the extent and transform them to pixel space
            foreach (MapPoint p in HeatMapPoints)
            {
                if (Map != null && Map.WrapAroundIsActive)
                {
                    // Note : this should work even if WrapAround is not active but it's probably less performant
                    if (p.Y >= extent2.YMin && p.Y <= extent2.YMax)
                    {
                        Point screenPoint = Map.MapToScreen(p, true);
                        if (!double.IsNaN(width) && Map.FlowDirection == FlowDirection.RightToLeft)
                        {
                            screenPoint.X = width - screenPoint.X;
                        }

                        if (screenPoint.X >= -Intensity && screenPoint.X <= width + Intensity)
                        {
                            points.Add(new HeatPoint()
                            {
                                X = (int)Math.Round(screenPoint.X),
                                Y = (int)Math.Round(screenPoint.Y)
                            });
                        }
                    }
                }
                else
                {
                    if (p.X >= extent2.XMin && p.Y >= extent2.YMin &&
                        p.X <= extent2.XMax && p.Y <= extent2.YMax)
                    {
                        points.Add(new HeatPoint()
                        {
                            X = (int)Math.Round((p.X - extent.XMin) / res),
                            Y = (int)Math.Round((extent.YMax - p.Y) / res)
                        });
                    }
                }
            }
            //Start the render thread
            renderThread.RunWorkerAsync(
                new object[] { extent, width, height, (int)Math.Round(this.Intensity), stops, points, onComplete });
        }
 private static Windows.Point3D?Adapter(MathNet.Point3D? value, Envelope env)
 {
     return(value.HasValue ? new Windows.Point3D(value.Value.X, value.Value.Y, value.Value.Z) as Windows.Point3D? : null);
 }
Пример #49
0
 bool IMessageQueue.TryDequeue(out Envelope envelope)
 {
     return(MessageQueue.TryDequeue(out envelope));
 }
Пример #50
0
        /// <summary>
        /// Handles the DoWork event of the renderThread control. This is where we
        /// render the heatmap outside the UI thread.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.ComponentModel.DoWorkEventArgs"/> instance
        /// containing the event data.</param>
        private void renderThread_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = (BackgroundWorker)sender;

            object[] args   = (object[])e.Argument;
            Envelope extent = (Envelope)args[0];
            int      width  = (int)args[1];
            int      height = (int)args[2];
            int      size   = (int)args[3];
            List <ThreadSafeGradientStop> stops = (List <ThreadSafeGradientStop>)args[4];
            List <HeatPoint> points             = (List <HeatPoint>)args[5];
            OnImageComplete  onComplete         = (OnImageComplete)args[6];

            size = size * 2 + 1;
            ushort[] matrix = CreateDistanceMatrix(size);
            int[]    output = new int[width * height];
            foreach (HeatPoint p in points)
            {
                AddPoint(matrix, size, p.X, p.Y, output, width);
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    e.Result = null;
                    return;
                }
            }
            matrix = null;
            int max = 0;

            foreach (int val in output)             //find max - used for scaling the intensity
            {
                if (max < val)
                {
                    max = val;
                }
            }

            //If we only have single points in the view, don't show them with too much intensity.
            if (max < 2)
            {
                max = 2;
            }
#if SILVERLIGHT
            PngEncoder ei = new PngEncoder(width, height);
#else
            int[] pixels = new int[height * width];
#endif
            for (int idx = 0; idx < height; idx++)                  // Height (y)
            {
#if SILVERLIGHT
                int rowstart = ei.GetRowStart(idx);
#endif
                for (int jdx = 0; jdx < width; jdx++)                     // Width (x)
                {
                    Color c = InterpolateColor(output[idx * width + jdx] / (float)max, stops);
#if SILVERLIGHT
                    ei.SetPixelAtRowStart(jdx, rowstart, c.R, c.G, c.B, c.A);
#else
                    int color = (c.A << 24) + (c.R << 16) + (c.G << 8) + c.B;
                    pixels[idx * width + jdx] = color;
#endif
                }
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    e.Result = null;
                    output   = null;
#if SILVERLIGHT
                    ei = null;
#else
                    pixels = null;
#endif
                    return;
                }
                //Raise the progress event for each line rendered
                worker.ReportProgress((idx + 1) * 100 / height);
            }
            stops.Clear();
            output = null;

            // Get stream and set image source
#if SILVERLIGHT
            e.Result = new object[] { ei, width, height, extent, onComplete };
#else
            e.Result = new object[] { pixels, width, height, extent, onComplete };
#endif
        }
        async public void MoveMF(string elmName)
        {
            Globals.i_correct = Globals.i_correct + 1;

            LayoutView layoutView = LayoutView.Active;
            Layout     layout     = layoutView.Layout;

            if (elmName == "Rectangle 1")
            {
                MapFrame mf1 = layout.FindElement("MF1") as MapFrame;
                await QueuedTask.Run(() => mf1.SetX(4));

                await QueuedTask.Run(() => mf1.SetY(0.5));
            }
            if (elmName == "Rectangle 2")
            {
                MapFrame mf2 = layout.FindElement("MF2") as MapFrame;
                await QueuedTask.Run(() => mf2.SetX(7));

                await QueuedTask.Run(() => mf2.SetY(0.5));
            }
            if (elmName == "Rectangle 3")
            {
                MapFrame mf3 = layout.FindElement("MF3") as MapFrame;
                await QueuedTask.Run(() => mf3.SetX(10));

                await QueuedTask.Run(() => mf3.SetY(0.5));
            }
            if (elmName == "Rectangle 4")
            {
                MapFrame mf4 = layout.FindElement("MF4") as MapFrame;
                await QueuedTask.Run(() => mf4.SetX(10));

                await QueuedTask.Run(() => mf4.SetY(3.5));
            }
            if (elmName == "Rectangle 5")
            {
                MapFrame mf5 = layout.FindElement("MF5") as MapFrame;
                await QueuedTask.Run(() => mf5.SetX(7));

                await QueuedTask.Run(() => mf5.SetY(3.5));
            }
            if (elmName == "Rectangle 6")
            {
                MapFrame mf6 = layout.FindElement("MF6") as MapFrame;
                await QueuedTask.Run(() => mf6.SetX(4));

                await QueuedTask.Run(() => mf6.SetY(3.5));
            }

            TextElement    statusText = layout.FindElement("Status") as TextElement;
            TextProperties statusProp = statusText.TextProperties;

            if (Globals.i_correct == 1)
            {
                statusProp.Text = "Nice job!  You got " + Globals.i_correct.ToString() + " correct out of " + Globals.i_guesses + " attempt.";
            }
            else
            {
                statusProp.Text = "Nice job!  You got " + Globals.i_correct.ToString() + " correct out of " + Globals.i_guesses + " attempts.";
            }
            await QueuedTask.Run(() => statusText.SetTextProperties(statusProp));

            if (Globals.i_correct == 6) //YOU WIN
            {
                statusProp.Text = "GAME OVER!  You got " + Globals.i_correct.ToString() + " correct out of " + Globals.i_guesses + " attempts.";
                await QueuedTask.Run(() => statusText.SetTextProperties(statusProp));

                //Turn off rectangles
                GraphicElement rec1 = layout.FindElement("Rectangle 1") as GraphicElement;
                await QueuedTask.Run(() => rec1.SetVisible(false));

                GraphicElement rec2 = layout.FindElement("Rectangle 2") as GraphicElement;
                await QueuedTask.Run(() => rec2.SetVisible(false));

                GraphicElement rec3 = layout.FindElement("Rectangle 3") as GraphicElement;
                await QueuedTask.Run(() => rec3.SetVisible(false));

                GraphicElement rec4 = layout.FindElement("Rectangle 4") as GraphicElement;
                await QueuedTask.Run(() => rec4.SetVisible(false));

                GraphicElement rec5 = layout.FindElement("Rectangle 5") as GraphicElement;
                await QueuedTask.Run(() => rec5.SetVisible(false));

                GraphicElement rec6 = layout.FindElement("Rectangle 6") as GraphicElement;
                await QueuedTask.Run(() => rec6.SetVisible(false));

                //Toggle MFs
                MapFrame mf1 = layout.FindElement("MF1") as MapFrame;
                await QueuedTask.Run(() => mf1.SetVisible(false));

                MapFrame mf2 = layout.FindElement("MF2") as MapFrame;
                await QueuedTask.Run(() => mf2.SetVisible(false));

                MapFrame mf3 = layout.FindElement("MF3") as MapFrame;
                await QueuedTask.Run(() => mf3.SetVisible(false));

                MapFrame mf4 = layout.FindElement("MF4") as MapFrame;
                await QueuedTask.Run(() => mf4.SetVisible(false));

                MapFrame mf5 = layout.FindElement("MF5") as MapFrame;
                await QueuedTask.Run(() => mf5.SetVisible(false));

                MapFrame mf6 = layout.FindElement("MF6") as MapFrame;
                await QueuedTask.Run(() => mf6.SetVisible(false));

                MapFrame mainMF = layout.FindElement("Main MF") as MapFrame;
                await QueuedTask.Run(() => mainMF.SetVisible(true));

                //Update title
                TextElement    titleText = layout.FindElement("Title") as TextElement;
                TextProperties titleProp = titleText.TextProperties;
                titleProp.Text = "Not any more!";
                await QueuedTask.Run(() => titleText.SetTextProperties(titleProp));

                //New Game
                TextElement    instrText = layout.FindElement("Instructions") as TextElement;
                TextProperties instrProp = instrText.TextProperties;
                instrProp.Text = "<bol>Instructions: </bol> " +
                                 "\n\n\n\n\n\n\n\n\n - Click the 'New Game' command if you want to play again.";
                await QueuedTask.Run(() => instrText.SetTextProperties(instrProp));

                //Zoomto finished puzzle area
                Coordinate2D ll = new Coordinate2D(3, 0);
                Coordinate2D ur = new Coordinate2D(14, 7.5);

                await QueuedTask.Run(() =>
                {
                    Envelope env = EnvelopeBuilder.CreateEnvelope(ll, ur);
                    layoutView.ZoomTo(env);
                });


                //Turn off selection changed events
                Globals.selEvents = false;
            }
        }
Пример #52
0
 /// <summary>
 /// Handles the CollectionChanged event of the heatMapPoints control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="System.Collections.Specialized.NotifyCollectionChangedEventArgs"/> instance containing the event data.</param>
 private void heatMapPoints_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
 {
     fullExtent = null;
     OnLayerChanged();
 }
Пример #53
0
        /// <summary>
        /// Returns all features with the view box
        /// </summary>
        /// <param name="bbox">view box</param>
        /// <param name="ds">FeatureDataSet to fill data into</param>
        public override void ExecuteIntersectionQuery(Envelope bbox, FeatureDataSet ds)
        {
            using (var conn = new OracleConnection(ConnectionString))
            {
                //Get bounding box string
                var strBbox = GetBoxFilterStr(bbox);

                var strSql = "SELECT * ";
                strSql += "FROM " + Table + " g WHERE ";

                if (!String.IsNullOrEmpty(_definitionQuery))
                {
                    strSql += DefinitionQuery + " AND ";
                }

                strSql += strBbox;

                if (!string.IsNullOrEmpty(_orderQuery))
                {
                    strSql += " ORDER BY " + PriorityColumn;
                }

                using (var adapter = new OracleDataAdapter(strSql, conn))
                {
                    conn.Open();
                    var ds2 = new DataSet();
                    adapter.Fill(ds2);
                    conn.Close();
                    if (ds2.Tables.Count > 0)
                    {
                        var fdt = new FeatureDataTable(ds2.Tables[0]);
                        foreach (DataColumn col in ds2.Tables[0].Columns)
                        {
                            if (string.Compare(col.ColumnName, GeometryColumn, CultureInfo.InvariantCulture, CompareOptions.OrdinalIgnoreCase) != 0)
                            {
                                fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression);
                            }
                        }
                        foreach (DataRow dr in ds2.Tables[0].Rows)
                        {
                            FeatureDataRow fdr = fdt.NewRow();
                            foreach (DataColumn col in ds2.Tables[0].Columns)
                            {
                                if (string.Compare(col.ColumnName, GeometryColumn, CultureInfo.InvariantCulture, CompareOptions.OrdinalIgnoreCase) != 0)
                                {
                                    fdr[col.ColumnName] = dr[col];
                                }
                            }

                            var sdoGeom = dr[GeometryColumn] as SdoGeometry;
                            if (sdoGeom != null)
                            {
                                fdr.Geometry = sdoGeom.AsGeometry(Factory);
                            }

                            fdt.AddRow(fdr);
                        }
                        ds.Tables.Add(fdt);
                    }
                }
            }
        }
Пример #54
0
 void IMessageQueue.Enqueue(IActorRef receiver, Envelope envelope)
 {
     MessageQueue.Enqueue(receiver, envelope);
 }
Пример #55
0
        void BuildMap()
        {
            if (isloading)
            {
                return;
            }
            Cursor = Cursors.WaitCursor;
            clusters.Clear();
            dgFacts.DataSource = null;
            List <IDisplayFact> displayFacts            = new List <IDisplayFact>();
            List <Individual>   list                    = new List <Individual>();
            List <Tuple <FactLocation, int> > locations = new List <Tuple <FactLocation, int> >();

            foreach (TreeNode node in tvPlaces.SelectedNodes)
            {
                Tuple <FactLocation, int> location = new Tuple <FactLocation, int>((FactLocation)node.Tag, node.Level);
                list.AddRange(ft.GetIndividualsAtLocation(location.Item1, location.Item2));
                locations.Add(location);
            }
            if (list.Count == 0)
            {
                Cursor = Cursors.Default;
                RefreshClusters();
                return;
            }
            int count = 0;

            progressbar.Visible = true;
            progressbar.Maximum = list.Count;
            foreach (Individual ind in list)
            {
                foreach (DisplayFact dispfact in ind.AllGeocodedFacts)
                {
                    foreach (Tuple <FactLocation, int> location in locations)
                    {
                        if (dispfact.Location.CompareTo(location.Item1, location.Item2) == 0)
                        {
                            displayFacts.Add(dispfact);
                            MapLocation loc = new MapLocation(ind, dispfact.Fact, dispfact.FactDate);
                            loc.AddFeatureDataRow(clusters.FactLocations);
                            break;
                        }
                    }
                }
                progressbar.Value = ++count;
                txtCount.Text     = "Processed " + count + " Individuals from list of " + list.Count;
                Application.DoEvents();
            }
            progressbar.Visible = false;
            txtCount.Text       = "Downloading map tiles and computing clusters for " + displayFacts.Count + " facts. Please wait";
            Application.DoEvents();
            dgFacts.DataSource = new SortableBindingList <IDisplayFact>(displayFacts);

            Envelope expand = mh.GetExtents(clusters.FactLocations);

            mapBox1.Map.ZoomToBox(expand);
            mapBox1.ActiveTool = SharpMap.Forms.MapBox.Tools.Pan;
            RefreshClusters();
            txtCount.Text = dgFacts.RowCount + " Geolocated fact(s) displayed";
            Cursor        = Cursors.Default;
        }
Пример #56
0
 public void GetFeaturesInView(Envelope bbox, FeatureDataSet ds)
 {
     ExecuteIntersectionQuery(bbox, ds);
 }
Пример #57
0
        /// <inheritdoc />
        public override bool UnSelect(Envelope tolerant, Envelope strict, SelectionMode mode, out Envelope affectedArea)
        {
            affectedArea = new Envelope();
            if (!_selectionEnabled)
            {
                return(false);
            }
            bool somethingChanged = false;

            SuspendEvents();
            foreach (ILayer s in GetLayers())
            {
                Envelope layerArea;
                if (s.UnSelect(tolerant, strict, mode, out layerArea))
                {
                    somethingChanged = true;
                    affectedArea.ExpandToInclude(layerArea);
                }
            }
            ResumeEvents();
            OnSelectionChanged(); // fires only AFTER the individual layers have fired their events.
            return(somethingChanged);
        }
Пример #58
0
 public bool Matches(Envelope envelope, Exception ex)
 {
     return(true);
 }
Пример #59
0
        /// <inheritdoc />
        public override bool Select(Envelope tolerant, Envelope strict, SelectionMode mode, out Envelope affectedArea)
        {
            affectedArea = new Envelope();
            if (!_selectionEnabled)
            {
                return(false);
            }
            bool somethingChanged = false;

            MapFrame.SuspendEvents();

            foreach (var s in GetLayers()
                     .Reverse()
                     .Where(_ => _.SelectionEnabled && _.IsVisible))
            {
                Envelope layerArea;
                if (s.Select(tolerant, strict, mode, out layerArea))
                {
                    somethingChanged = true;
                    affectedArea.ExpandToInclude(layerArea);
                }
                // removed by jany_: this selected only features of the first layer with features in the selected area, if user wanted to select features of another layer too they get ignored
                // added SelectPlugin enables user to choose the layers in which he wants to select features
                //if (somethingChanged)
                //{
                //    MapFrame.ResumeEvents();
                //    OnSelectionChanged(); // fires only AFTER the individual layers have fired their events.
                //    return somethingChanged;
                //}
            }
            MapFrame.ResumeEvents();
            OnSelectionChanged(); // fires only AFTER the individual layers have fired their events.
            return(somethingChanged);
        }
        private void Initialize()
        {
            // Create a new map using the WebMercator spatial reference.
            Map newMap = new Map(SpatialReferences.WebMercator)
            {
                // Set the basemap of the map to be a topographic layer.
                Basemap = Basemap.CreateTopographic()
            };

            // Create a graphics overlay to hold the input geometries for the clip operation.
            _inputGeometriesGraphicsOverlay = new GraphicsOverlay();

            // Add the input geometries graphics overlay to the MapView.
            MyMapView.GraphicsOverlays.Add(_inputGeometriesGraphicsOverlay);

            // Create a graphics overlay to hold the resulting geometries from the three GeometryEngine.Clip operations.
            _clipAreasGraphicsOverlay = new GraphicsOverlay();

            // Add the resulting geometries graphics overlay to the MapView.
            MyMapView.GraphicsOverlays.Add(_clipAreasGraphicsOverlay);

            // Create a simple line symbol for the 1st parameter of the GeometryEngine.Clip operation - it follows the
            // boundary of Colorado.
            SimpleLineSymbol coloradoSimpleLineSymbol = new SimpleLineSymbol(
                SimpleLineSymbolStyle.Solid, Colors.Blue, 4);

            // Create the color that will be used as the fill for the Colorado graphic. It will be a semi-transparent, blue color.
            Colors coloradoFillColor = Colors.FromArgb(34, 0, 0, 255);

            // Create the simple fill symbol for the Colorado graphic - comprised of a fill style, fill color and outline.
            SimpleFillSymbol coloradoSimpleFillSymbol = new SimpleFillSymbol(
                SimpleFillSymbolStyle.Solid, coloradoFillColor, coloradoSimpleLineSymbol);

            // Create the geometry of the Colorado graphic.
            Envelope colorado = new Envelope(
                new MapPoint(-11362327.128340, 5012861.290274, SpatialReferences.WebMercator),
                new MapPoint(-12138232.018408, 4441198.773776, SpatialReferences.WebMercator));

            // Create the graphic for Colorado - comprised of a polygon shape and fill symbol.
            _coloradoGraphic = new Graphic(colorado, coloradoSimpleFillSymbol);

            // Add the Colorado graphic to the input geometries graphics overlay collection.
            _inputGeometriesGraphicsOverlay.Graphics.Add(_coloradoGraphic);

            // Create a simple line symbol for the three different clip geometries.
            SimpleLineSymbol clipGeomtriesSimpleLineSymbol = new SimpleLineSymbol(
                SimpleLineSymbolStyle.Dot, Colors.Red, 5);

            // Create an envelope outside Colorado.
            Envelope outsideEnvelope = new Envelope(
                new MapPoint(-11858344.321294, 5147942.225174, SpatialReferences.WebMercator),
                new MapPoint(-12201990.219681, 5297071.577304, SpatialReferences.WebMercator));

            // Create the graphic for an envelope outside Colorado - comprised of a polyline shape and line symbol.
            _outsideGraphic = new Graphic(outsideEnvelope, clipGeomtriesSimpleLineSymbol);

            // Add the envelope outside Colorado graphic to the graphics overlay collection.
            _inputGeometriesGraphicsOverlay.Graphics.Add(_outsideGraphic);

            // Create an envelope intersecting Colorado.
            Envelope intersectingEnvelope = new Envelope(
                new MapPoint(-11962086.479298, 4566553.881363, SpatialReferences.WebMercator),
                new MapPoint(-12260345.183558, 4332053.378376, SpatialReferences.WebMercator));

            // Create the graphic for an envelope intersecting Colorado - comprised of a polyline shape and line symbol.
            _intersectingGraphic = new Graphic(intersectingEnvelope, clipGeomtriesSimpleLineSymbol);

            // Add the envelope intersecting Colorado graphic to the graphics overlay collection.
            _inputGeometriesGraphicsOverlay.Graphics.Add(_intersectingGraphic);

            // Create a envelope inside Colorado.
            Envelope containedEnvelope = new Envelope(
                new MapPoint(-11655182.595204, 4741618.772994, SpatialReferences.WebMercator),
                new MapPoint(-11431488.567009, 4593570.068343, SpatialReferences.WebMercator));

            // Create the graphic for an envelope inside Colorado - comprised of a polyline shape and line symbol.
            _containedGraphic = new Graphic(containedEnvelope, clipGeomtriesSimpleLineSymbol);

            // Add the envelope inside Colorado graphic to the graphics overlay collection.
            _inputGeometriesGraphicsOverlay.Graphics.Add(_containedGraphic);

            // Get the extent of all of the graphics in the graphics overlay with a little padding to used as the initial zoom extent of the map.
            Geometry visibleExtent = GetExtentOfGraphicsOverlay(_inputGeometriesGraphicsOverlay, 1.3, SpatialReferences.WebMercator);

            // Set the initial visual extent of the map view to the extent of the graphics overlay.
            newMap.InitialViewpoint = new Viewpoint(visibleExtent);

            // Assign the map to the MapView.
            MyMapView.Map = newMap;
        }