public async Task Line_SanPedroTwoTrackFileLineToGeoJsonAndBack()
        {
            var testFile = new FileInfo(Path.Combine(Directory.GetCurrentDirectory(), "TestMedia",
                                                     "TwoTrackGpxNearTheSanPedro.gpx"));

            Assert.True(testFile.Exists, "Test File Found");

            var tracks = await SpatialHelpers.TracksFromGpxFile(testFile, DebugTrackers.DebugProgressTracker());

            Assert.AreEqual(2, tracks.Count, "Should find 2 tracks");
            Assert.True(tracks.All(x => !string.IsNullOrWhiteSpace(x.description)),
                        "Found Tracks with Blank Description?");

            var shortTrack = tracks.OrderBy(x => x.track.Count).First().track;
            var geoJson    =
                await SpatialHelpers.GeoJsonWithLineStringFromCoordinateList(shortTrack, false,
                                                                             DebugTrackers.DebugProgressTracker());

            var shortTrackFromGeoJson =
                SpatialHelpers.CoordinateListFromGeoJsonFeatureCollectionWithLinestring(geoJson);

            Assert.AreEqual(shortTrack.Count, shortTrackFromGeoJson.Count, "Count of Track Points does not match");

            for (var i = 0; i < shortTrack.Count; i++)
            {
                Assert.AreEqual(shortTrack[i].X, shortTrackFromGeoJson[i].X, $"Point {i} X Values don't match");
                Assert.AreEqual(shortTrack[i].Y, shortTrackFromGeoJson[i].Y, $"Point {i} Y Values don't match");
                Assert.AreEqual(shortTrack[i].Z, shortTrackFromGeoJson[i].Z, $"Point {i} Z Values don't match");
            }
        }
        public async Task Line_GpxLineFromHorseshoeMesaFileWithMeasurements()
        {
            var testFile = new FileInfo(Path.Combine(Directory.GetCurrentDirectory(), "TestMedia",
                                                     "GrandCanyonHorseShoeMesaEastSideLoop.gpx"));

            Assert.True(testFile.Exists, "Test File Found");

            var tracks = await SpatialHelpers.TracksFromGpxFile(testFile, DebugTrackers.DebugProgressTracker());

            Assert.AreEqual(1, tracks.Count, "Should find 1 track");

            var coordinateList = tracks.First().track;

            var metricStats   = SpatialHelpers.LineStatsInMetricFromCoordinateList(coordinateList);
            var imperialStats = SpatialHelpers.LineStatsInImperialFromMetricStats(metricStats);

            Assert.IsTrue(imperialStats.Length.IsApproximatelyEqualTo(13, .3),
                          $"ExpertGPS Length 13.03, Measured {imperialStats.Length}");
            Assert.IsTrue(imperialStats.ElevationClimb.IsApproximatelyEqualTo(9000, 100),
                          $"ExpertGPS Climb 9023, Measured {imperialStats.ElevationClimb}");
            Assert.IsTrue(imperialStats.ElevationDescent.IsApproximatelyEqualTo(8932, 100),
                          $"ExpertGPS Descent 8932, Measured {imperialStats.ElevationDescent}");
            Assert.IsTrue(imperialStats.MinimumElevation.IsApproximatelyEqualTo(3591, 30),
                          $"ExpertGPS Min Elevation 13.03, Measured {imperialStats.MinimumElevation}");
            Assert.IsTrue(imperialStats.MaximumElevation.IsApproximatelyEqualTo(7384, 30),
                          $"ExpertGPS Max Elevation 13.03, Measured {imperialStats.MaximumElevation}");
        }
예제 #3
0
        private void RunTest(TPVector vector, TurnDirection expected)
        {
            // Execute the test
            var result = SpatialHelpers.DetermineTurnDirection(vector);

            // Assert
            Assert.AreEqual(expected, result);
        }
예제 #4
0
        public void GeometryParameterShouldParseCorrectly()
        {
            var point = GeometryPoint.Create(1.0, 2.0);
            ICollection <OperationSegmentParameter> parsedParameters;

            TryParseOperationParameters("GetColorAtPosition", "position=geometry'" + SpatialHelpers.WriteSpatial(point) + "',includeAlpha=true", null, HardCodedTestModel.GetColorAtPositionFunction(), out parsedParameters).Should().BeTrue();
            parsedParameters.Should().HaveCount(2);
            parsedParameters.First().ShouldBeConstantParameterWithValueType("position", point);
        }
        public async Task Line_SanPedroTwoTrackFile()
        {
            var testFile = new FileInfo(Path.Combine(Directory.GetCurrentDirectory(), "TestMedia",
                                                     "TwoTrackGpxNearTheSanPedro.gpx"));

            Assert.True(testFile.Exists, "Test File Found");

            var tracks = await SpatialHelpers.TracksFromGpxFile(testFile, DebugTrackers.DebugProgressTracker());

            Assert.AreEqual(2, tracks.Count, "Should find 2 tracks");
            Assert.True(tracks.All(x => !string.IsNullOrWhiteSpace(x.description)),
                        "Found Tracks with Blank Description?");

            var shortTrack = tracks.OrderBy(x => x.track.Count).First().track;

            Assert.AreEqual(214, shortTrack.Count, "Unexpected Point Count");

            var preElevationReplacementStats = SpatialHelpers.LineStatsInImperialFromCoordinateList(shortTrack);

            Assert.IsTrue(preElevationReplacementStats.Length.IsApproximatelyEqualTo(2.8, .05),
                          $"ExpertGPS Length 2.79, Measured {preElevationReplacementStats.Length}");
            Assert.IsTrue(preElevationReplacementStats.ElevationClimb.IsApproximatelyEqualTo(158, 1),
                          $"ExpertGPS Climb 158.4, Measured {preElevationReplacementStats.ElevationClimb}");
            Assert.IsTrue(preElevationReplacementStats.ElevationDescent.IsApproximatelyEqualTo(285, 1),
                          $"ExpertGPS Descent 285.6, Measured {preElevationReplacementStats.ElevationDescent}");
            Assert.IsTrue(preElevationReplacementStats.MinimumElevation.IsApproximatelyEqualTo(3795, 1),
                          $"ExpertGPS Min Elevation 3795.25, Measured {preElevationReplacementStats.MinimumElevation}");
            Assert.IsTrue(preElevationReplacementStats.MaximumElevation.IsApproximatelyEqualTo(3944, 1),
                          $"ExpertGPS Max Elevation 3944.76, Measured {preElevationReplacementStats.MaximumElevation}");

            await ElevationService.OpenTopoMapZenElevation(new HttpClient(), shortTrack,
                                                           DebugTrackers.DebugProgressTracker());

            Assert.True(shortTrack.All(x => x.Z > 0), "After Elevation replacement some 0 values found");

            var postElevationReplacementStats = SpatialHelpers.LineStatsInImperialFromCoordinateList(shortTrack);

            Assert.IsTrue(postElevationReplacementStats.Length.IsApproximatelyEqualTo(2.8, .05),
                          $"ExpertGPS Length 2.79, Measured {preElevationReplacementStats.Length}");
            Assert.IsTrue(postElevationReplacementStats.ElevationClimb.IsApproximatelyEqualTo(36.08, 1),
                          $"Expected 36.08, Measured {preElevationReplacementStats.ElevationClimb}");
            Assert.IsTrue(postElevationReplacementStats.ElevationDescent.IsApproximatelyEqualTo(187, 1),
                          $"Expected 187, Measured {preElevationReplacementStats.ElevationDescent}");
            Assert.IsTrue(postElevationReplacementStats.MinimumElevation.IsApproximatelyEqualTo(3891.07, 1),
                          $"Expected 3891, Measured {preElevationReplacementStats.MinimumElevation}");
            Assert.IsTrue(postElevationReplacementStats.MaximumElevation.IsApproximatelyEqualTo(4041.99, 1),
                          $"Expected 4041, Measured {preElevationReplacementStats.MaximumElevation}");
        }
        public async Task L01_HorseshoeMesaLineContent()
        {
            var testFile = new FileInfo(Path.Combine(Directory.GetCurrentDirectory(), "TestMedia",
                                                     "GrandCanyonHorseShoeMesaEastSideLoop.gpx"));

            Assert.True(testFile.Exists, "GPX Test File Found");

            var lineTest = new LineContent
            {
                ContentId         = Guid.NewGuid(),
                BodyContent       = "Horseshoe Mesa East Side Loop",
                BodyContentFormat = ContentFormatDefaults.Content.ToString(),
                CreatedOn         = DateTime.Now,
                CreatedBy         = "GPX Import Test",
                Folder            = "GrandCanyon",
                Title             = "Horseshoe Mesa East Side Loop",
                Slug = "horseshoe-mesa-east-side-loop",
                ShowInMainSiteFeed = true,
                Summary            = "Horseshoe Mesa East Side Loop",
                Tags = "grand-canyon, horse-shoe-mesa",
                UpdateNotesFormat = ContentFormatDefaults.Content.ToString()
            };

            var track = (await SpatialHelpers.TracksFromGpxFile(testFile, DebugTrackers.DebugProgressTracker()))
                        .First();

            var stats = SpatialHelpers.LineStatsInMetricFromCoordinateList(track.track);

            lineTest.ClimbElevation   = stats.ElevationClimb;
            lineTest.DescentElevation = stats.ElevationDescent;
            lineTest.MinimumElevation = stats.MinimumElevation;
            lineTest.MaximumElevation = stats.MaximumElevation;
            lineTest.LineDistance     = stats.Length;

            lineTest.Line =
                await SpatialHelpers.GeoJsonWithLineStringFromCoordinateList(track.track, false,
                                                                             DebugTrackers.DebugProgressTracker());

            var validationResult = await LineGenerator.Validate(lineTest);

            Assert.IsFalse(validationResult.HasError);

            var saveResult =
                await LineGenerator.SaveAndGenerateHtml(lineTest, null, DebugTrackers.DebugProgressTracker());

            Assert.IsFalse(saveResult.generationReturn.HasError);
        }
예제 #7
0
        public static async Task <string> GenerateGeoJson(string geoJsonContent, string pageUrl)
        {
            var serializer = GeoJsonSerializer.Create(SpatialHelpers.Wgs84GeometryFactory());

            using var stringReader = new StringReader(geoJsonContent);
            using var jsonReader   = new JsonTextReader(stringReader);
            var contentFeatureCollection = serializer.Deserialize <FeatureCollection>(jsonReader);

            var bounds = SpatialConverters.GeometryBoundingBox(SpatialConverters.GeoJsonToGeometries(geoJsonContent));

            var jsonDto = new GeoJsonSiteJsonData(pageUrl,
                                                  new SpatialBounds(bounds.MaxY, bounds.MaxX, bounds.MinY, bounds.MinX), contentFeatureCollection);

            await using var stringWriter = new StringWriter();
            using var jsonWriter         = new JsonTextWriter(stringWriter);
            serializer.Serialize(jsonWriter, jsonDto);

            return(stringWriter.ToString());
        }
예제 #8
0
        internal override async Task <long> ExecuteAsync(
            Dictionary <int, object> identifierValues,
            List <KeyValuePair <PropagatorResult, object> > generatedValues,
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            EntityConnection connection = this.Translator.Connection;

            this._dbCommand.Transaction = connection.CurrentTransaction == null ? (DbTransaction)null : connection.CurrentTransaction.StoreTransaction;
            this._dbCommand.Connection  = connection.StoreConnection;
            if (this.Translator.CommandTimeout.HasValue)
            {
                this._dbCommand.CommandTimeout = this.Translator.CommandTimeout.Value;
            }
            this.SetInputIdentifiers(identifierValues);
            long rowsAffected;

            if (this.ResultColumns != null)
            {
                rowsAffected = 0L;
                IBaseList <EdmMember> members = TypeHelpers.GetAllStructuralMembers((EdmType)this.CurrentValues.StructuralType);
                using (DbDataReader reader = await this._dbCommand.ExecuteReaderAsync(CommandBehavior.SequentialAccess, cancellationToken).WithCurrentCulture <DbDataReader>())
                {
                    if (await reader.ReadAsync(cancellationToken).WithCurrentCulture <bool>())
                    {
                        ++rowsAffected;
                        foreach (KeyValuePair <int, PropagatorResult> keyValuePair in (IEnumerable <KeyValuePair <int, PropagatorResult> >) this.ResultColumns.Select <KeyValuePair <string, PropagatorResult>, KeyValuePair <int, PropagatorResult> >((Func <KeyValuePair <string, PropagatorResult>, KeyValuePair <int, PropagatorResult> >)(r => new KeyValuePair <int, PropagatorResult>(this.GetColumnOrdinal(this.Translator, reader, r.Key), r.Value))).OrderBy <KeyValuePair <int, PropagatorResult>, int>((Func <KeyValuePair <int, PropagatorResult>, int>)(r => r.Key)))
                        {
                            int       columnOrdinal = keyValuePair.Key;
                            TypeUsage columnType    = members[keyValuePair.Value.RecordOrdinal].TypeUsage;
                            object    value;
                            if (Helper.IsSpatialType(columnType))
                            {
                                if (!await reader.IsDBNullAsync(columnOrdinal, cancellationToken).WithCurrentCulture <bool>())
                                {
                                    value = await SpatialHelpers.GetSpatialValueAsync(this.Translator.MetadataWorkspace, reader, columnType, columnOrdinal, cancellationToken).WithCurrentCulture <object>();

                                    goto label_14;
                                }
                            }
                            value = await reader.GetFieldValueAsync <object>(columnOrdinal, cancellationToken).WithCurrentCulture <object>();

label_14:
                            PropagatorResult result = keyValuePair.Value;
                            generatedValues.Add(new KeyValuePair <PropagatorResult, object>(result, value));
                            int identifier = result.Identifier;
                            if (-1 != identifier)
                            {
                                identifierValues.Add(identifier, value);
                            }
                        }
                    }
                    await CommandHelper.ConsumeReaderAsync(reader, cancellationToken).WithCurrentCulture();
                }
            }
            else
            {
                rowsAffected = (long)await this._dbCommand.ExecuteNonQueryAsync(cancellationToken).WithCurrentCulture <int>();
            }
            return(this.GetRowsAffected(rowsAffected, this.Translator));
        }
예제 #9
0
        public void GeometryAndNullParameterValuesShouldWorkInPath()
        {
            var point     = GeometryPoint.Create(1, 2);
            Uri queryUri  = new Uri("Paintings(0)/Fully.Qualified.Namespace.GetColorAtPosition(position=geometry'" + SpatialHelpers.WriteSpatial(point) + "',includeAlpha=null)", UriKind.Relative);
            Uri actualUri = UriBuilder(queryUri, ODataUrlConventions.Default, settings);

            Assert.AreEqual(new Uri("http://gobbledygook/Paintings(0)/Fully.Qualified.Namespace.GetColorAtPosition(position=geometry'" + SpatialHelpers.WriteSpatial(point) + "',includeAlpha=null)"), actualUri);
        }
예제 #10
0
        public void GeographyParameterShouldParseCorrectly()
        {
            var point = GeographyPoint.Create(1.0, 2.0);
            ICollection <OperationSegmentParameter> parsedParameters;

            TryParseOperationParameters("GetNearbyPriorAddresses", "currentLocation=geography'" + SpatialHelpers.WriteSpatial(point) + "',limit=50", null, HardCodedTestModel.GetNearbyPriorAddressesFunction(), out parsedParameters).Should().BeTrue();
            parsedParameters.Should().HaveCount(2);
            parsedParameters.First().ShouldBeConstantParameterWithValueType("currentLocation", point);
            parsedParameters.Last().ShouldBeConstantParameterWithValueType("limit", 50);
        }
예제 #11
0
        internal override long Execute(
            Dictionary <int, object> identifierValues,
            List <KeyValuePair <PropagatorResult, object> > generatedValues)
        {
            EntityConnection connection = this.Translator.Connection;

            this._dbCommand.Transaction = connection.CurrentTransaction == null ? (DbTransaction)null : connection.CurrentTransaction.StoreTransaction;
            this._dbCommand.Connection  = connection.StoreConnection;
            if (this.Translator.CommandTimeout.HasValue)
            {
                this._dbCommand.CommandTimeout = this.Translator.CommandTimeout.Value;
            }
            this.SetInputIdentifiers(identifierValues);
            long rowsAffected;

            if (this.ResultColumns != null)
            {
                rowsAffected = 0L;
                IBaseList <EdmMember> structuralMembers = TypeHelpers.GetAllStructuralMembers((EdmType)this.CurrentValues.StructuralType);
                using (DbDataReader reader = this._dbCommand.ExecuteReader(CommandBehavior.SequentialAccess))
                {
                    if (reader.Read())
                    {
                        ++rowsAffected;
                        foreach (KeyValuePair <int, PropagatorResult> keyValuePair in (IEnumerable <KeyValuePair <int, PropagatorResult> >) this.ResultColumns.Select <KeyValuePair <string, PropagatorResult>, KeyValuePair <int, PropagatorResult> >((Func <KeyValuePair <string, PropagatorResult>, KeyValuePair <int, PropagatorResult> >)(r => new KeyValuePair <int, PropagatorResult>(this.GetColumnOrdinal(this.Translator, reader, r.Key), r.Value))).OrderBy <KeyValuePair <int, PropagatorResult>, int>((Func <KeyValuePair <int, PropagatorResult>, int>)(r => r.Key)))
                        {
                            int key1 = keyValuePair.Key;
                            if (key1 != -1)
                            {
                                TypeUsage        typeUsage = structuralMembers[keyValuePair.Value.RecordOrdinal].TypeUsage;
                                object           obj       = !Helper.IsSpatialType(typeUsage) || reader.IsDBNull(key1) ? reader.GetValue(key1) : SpatialHelpers.GetSpatialValue(this.Translator.MetadataWorkspace, reader, typeUsage, key1);
                                PropagatorResult key2      = keyValuePair.Value;
                                generatedValues.Add(new KeyValuePair <PropagatorResult, object>(key2, obj));
                                int identifier = key2.Identifier;
                                if (-1 != identifier)
                                {
                                    identifierValues.Add(identifier, obj);
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                    CommandHelper.ConsumeReader(reader);
                }
            }
            else
            {
                rowsAffected = (long)this._dbCommand.ExecuteNonQuery();
            }
            return(this.GetRowsAffected(rowsAffected, this.Translator));
        }
예제 #12
0
 protected virtual DbSpatialDataReader CreateSpatialDataReader()
 {
     return(SpatialHelpers.CreateSpatialDataReader(Workspace, Reader));
 }
예제 #13
0
        public static async Task <GenerationReturn> Validate(LineContent lineContent)
        {
            var rootDirectoryCheck = UserSettingsUtilities.ValidateLocalSiteRootDirectory();

            if (!rootDirectoryCheck.Item1)
            {
                return(await GenerationReturn.Error($"Problem with Root Directory: {rootDirectoryCheck.Item2}",
                                                    lineContent.ContentId));
            }

            var commonContentCheck = await CommonContentValidation.ValidateContentCommon(lineContent);

            if (!commonContentCheck.valid)
            {
                return(await GenerationReturn.Error(commonContentCheck.explanation, lineContent.ContentId));
            }

            var updateFormatCheck = CommonContentValidation.ValidateUpdateContentFormat(lineContent.UpdateNotesFormat);

            if (!updateFormatCheck.isValid)
            {
                return(await GenerationReturn.Error(updateFormatCheck.explanation, lineContent.ContentId));
            }

            try
            {
                var serializer = GeoJsonSerializer.Create(SpatialHelpers.Wgs84GeometryFactory(), 3);

                using var stringReader = new StringReader(lineContent.Line);
                using var jsonReader   = new JsonTextReader(stringReader);
                var featureCollection = serializer.Deserialize <FeatureCollection>(jsonReader);
                if (featureCollection.Count < 1)
                {
                    return(await GenerationReturn.Error(
                               "The GeoJson for the line appears to have an empty Feature Collection?", lineContent.ContentId));
                }
                if (featureCollection.Count > 1)
                {
                    return(await GenerationReturn.Error(
                               "The GeoJson for the line appears to contain multiple elements? It should only contain 1 line...",
                               lineContent.ContentId));
                }
                if (featureCollection[0].Geometry is not LineString)
                {
                    return(await GenerationReturn.Error(
                               "The GeoJson for the line has one element but it isn't a LineString?", lineContent.ContentId));
                }
                var lineString = featureCollection[0].Geometry as LineString;
                if (lineString == null || lineString.Count < 1 || lineString.Length == 0)
                {
                    return(await GenerationReturn.Error("The LineString doesn't have any points or is zero length?",
                                                        lineContent.ContentId));
                }
            }
            catch (Exception e)
            {
                return(await GenerationReturn.Error(
                           $"Error parsing the FeatureCollection and/or problems checking the LineString {e.Message}",
                           lineContent.ContentId));
            }

            return(await GenerationReturn.Success("Line Content Validation Successful"));
        }
예제 #14
0
        // <summary>
        // See comments in <see cref="UpdateCommand" />.
        // </summary>
        internal override async Task <long> ExecuteAsync(
            Dictionary <int, object> identifierValues,
            List <KeyValuePair <PropagatorResult, object> > generatedValues, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            // Compile command
            using (var command = CreateCommand(identifierValues))
            {
                var connection = Translator.Connection;
                // configure command to use the connection and transaction for this session
                command.Transaction = ((null == connection.CurrentTransaction)
                                           ? null
                                           : connection.CurrentTransaction.StoreTransaction);
                command.Connection = connection.StoreConnection;

                // FIX Klaus 12/09/2018: Prevents the previously assigned transaction from being deleted due to collateral effects during connection assignment.
                command.Transaction = command.Transaction
                                      ?? (connection.CurrentTransaction == null ? null : connection.CurrentTransaction.StoreTransaction);

                if (Translator.CommandTimeout.HasValue)
                {
                    command.CommandTimeout = Translator.CommandTimeout.Value;
                }

                // Execute the query
                int rowsAffected;
                if (_modificationCommandTree.HasReader)
                {
                    // retrieve server gen results
                    rowsAffected = 0;
                    using (
                        var reader =
                            await
                            command.ExecuteReaderAsync(CommandBehavior.SequentialAccess, cancellationToken).WithCurrentCulture())
                    {
                        if (await reader.ReadAsync(cancellationToken).WithCurrentCulture())
                        {
                            rowsAffected++;

                            var members = TypeHelpers.GetAllStructuralMembers(CurrentValues.StructuralType);

                            for (var ordinal = 0; ordinal < reader.FieldCount; ordinal++)
                            {
                                // column name of result corresponds to column name of table
                                var    columnName = reader.GetName(ordinal);
                                var    member     = members[columnName];
                                object value;
                                if (Helper.IsSpatialType(member.TypeUsage)
                                    &&
                                    !await reader.IsDBNullAsync(ordinal, cancellationToken).WithCurrentCulture())
                                {
                                    value =
                                        await
                                        SpatialHelpers.GetSpatialValueAsync(
                                            Translator.MetadataWorkspace, reader, member.TypeUsage, ordinal, cancellationToken).
                                        WithCurrentCulture();
                                }
                                else
                                {
                                    value =
                                        await reader.GetFieldValueAsync <object>(ordinal, cancellationToken).WithCurrentCulture();
                                }

                                // retrieve result which includes the context for back-propagation
                                var columnOrdinal = members.IndexOf(member);
                                var result        = CurrentValues.GetMemberValue(columnOrdinal);

                                // register for back-propagation
                                generatedValues.Add(new KeyValuePair <PropagatorResult, object>(result, value));

                                // register identifier if it exists
                                var identifier = result.Identifier;
                                if (PropagatorResult.NullIdentifier != identifier)
                                {
                                    identifierValues.Add(identifier, value);
                                }
                            }
                        }

                        // Consume the current reader (and subsequent result sets) so that any errors
                        // executing the command can be intercepted
                        await CommandHelper.ConsumeReaderAsync(reader, cancellationToken).WithCurrentCulture();
                    }
                }
                else
                {
                    rowsAffected = await command.ExecuteNonQueryAsync(cancellationToken).WithCurrentCulture();
                }

                return(rowsAffected);
            }
        }
예제 #15
0
        public void ParseCountAfterNonComposableFunctionShouldFail()
        {
            var    point     = GeographyPoint.Create(1, 2);
            Action parsePath = () => this.testSubject.ParsePath(new[] { "People(1)", "Fully.Qualified.Namespace.GetNearbyPriorAddresses(currentLocation=geography'" + SpatialHelpers.WriteSpatial(point) + "',limit=null)", "$count" });

            parsePath.ShouldThrow <ODataException>().WithMessage(ErrorStrings.RequestUriProcessor_MustBeLeafSegment("Fully.Qualified.Namespace.GetNearbyPriorAddresses"));
        }
예제 #16
0
파일: shaper.cs 프로젝트: jwanagel/jjwtest
 private DbSpatialDataReader CreateSpatialDataReader()
 {
     return(SpatialHelpers.CreateSpatialDataReader(Workspace, Reader));
 }
예제 #17
0
        // efects: Executes the current function command in the given transaction and connection context.
        // All server-generated values are added to the generatedValues list. If those values are identifiers, they are
        // also added to the identifierValues dictionary, which associates proxy identifiers for keys in the session
        // with their actual values, permitting fix-up of identifiers across relationships.
        internal override long Execute(UpdateTranslator translator, EntityConnection connection, Dictionary <int, object> identifierValues,
                                       List <KeyValuePair <PropagatorResult, object> > generatedValues)
        {
            // configure command to use the connection and transaction for this session
            m_dbCommand.Transaction = ((null != connection.CurrentTransaction) ? connection.CurrentTransaction.StoreTransaction : null);
            m_dbCommand.Connection  = connection.StoreConnection;
            if (translator.CommandTimeout.HasValue)
            {
                m_dbCommand.CommandTimeout = translator.CommandTimeout.Value;
            }

            // set all identifier inputs (to support propagation of identifier values across relationship
            // boundaries)
            if (null != m_inputIdentifiers)
            {
                foreach (KeyValuePair <int, DbParameter> inputIdentifier in m_inputIdentifiers)
                {
                    object value;
                    if (identifierValues.TryGetValue(inputIdentifier.Key, out value))
                    {
                        // set the actual value for the identifier if it has been produced by some
                        // other command
                        inputIdentifier.Value.Value = value;
                    }
                }
            }

            // Execute the query
            long rowsAffected;

            if (null != m_resultColumns)
            {
                // If there are result columns, read the server gen results
                rowsAffected = 0;
                IBaseList <EdmMember> members = TypeHelpers.GetAllStructuralMembers(this.CurrentValues.StructuralType);
                using (DbDataReader reader = m_dbCommand.ExecuteReader(CommandBehavior.SequentialAccess))
                {
                    // Retrieve only the first row from the first result set
                    if (reader.Read())
                    {
                        rowsAffected++;

                        foreach (var resultColumn in m_resultColumns
                                 .Select(r => new KeyValuePair <int, PropagatorResult>(GetColumnOrdinal(translator, reader, r.Key), r.Value))
                                 .OrderBy(r => r.Key)) // order by column ordinal to avoid breaking SequentialAccess readers
                        {
                            int       columnOrdinal = resultColumn.Key;
                            TypeUsage columnType    = members[resultColumn.Value.RecordOrdinal].TypeUsage;
                            object    value;

                            if (Helper.IsSpatialType(columnType) && !reader.IsDBNull(columnOrdinal))
                            {
                                value = SpatialHelpers.GetSpatialValue(translator.MetadataWorkspace, reader, columnType, columnOrdinal);
                            }
                            else
                            {
                                value = reader.GetValue(columnOrdinal);
                            }

                            // register for back-propagation
                            PropagatorResult result = resultColumn.Value;
                            generatedValues.Add(new KeyValuePair <PropagatorResult, object>(result, value));

                            // register identifier if it exists
                            int identifier = result.Identifier;
                            if (PropagatorResult.NullIdentifier != identifier)
                            {
                                identifierValues.Add(identifier, value);
                            }
                        }
                    }

                    // Consume the current reader (and subsequent result sets) so that any errors
                    // executing the function can be intercepted
                    CommandHelper.ConsumeReader(reader);
                }
            }
            else
            {
                rowsAffected = m_dbCommand.ExecuteNonQuery();
            }

            // if an explicit rows affected parameter exists, use this value instead
            if (null != m_rowsAffectedParameter)
            {
                // by design, negative row counts indicate failure iff. an explicit rows
                // affected parameter is used
                if (DBNull.Value.Equals(m_rowsAffectedParameter.Value))
                {
                    rowsAffected = 0;
                }
                else
                {
                    try
                    {
                        rowsAffected = Convert.ToInt64(m_rowsAffectedParameter.Value, CultureInfo.InvariantCulture);
                    }
                    catch (Exception e)
                    {
                        if (UpdateTranslator.RequiresContext(e))
                        {
                            // wrap the exception
                            throw EntityUtil.Update(System.Data.Entity.Strings.Update_UnableToConvertRowsAffectedParameterToInt32(
                                                        m_rowsAffectedParameter.ParameterName, typeof(int).FullName), e, this.GetStateEntries(translator));
                        }
                        throw;
                    }
                }
            }

            return(rowsAffected);
        }
예제 #18
0
        public void GeographyAndNullParameterValuesShouldWorkInPath()
        {
            var point     = GeographyPoint.Create(1, 2);
            Uri queryUri  = new Uri("People(0)/Fully.Qualified.Namespace.GetNearbyPriorAddresses(currentLocation=geography'" + SpatialHelpers.WriteSpatial(point) + "',limit=null)", UriKind.Relative);
            Uri actualUri = UriBuilder(queryUri, ODataUrlConventions.Default, settings);

            Assert.AreEqual(new Uri("http://gobbledygook/People(0)/Fully.Qualified.Namespace.GetNearbyPriorAddresses(currentLocation=geography'" + SpatialHelpers.WriteSpatial(point) + "',limit=null)"), actualUri);
        }
예제 #19
0
        /// <summary>
        ///     See comments in <see cref="UpdateCommand" />.
        /// </summary>
        internal override long Execute(
            Dictionary <int, object> identifierValues,
            List <KeyValuePair <PropagatorResult, object> > generatedValues,
            IDbCommandInterceptor commandInterceptor)
        {
            // Compile command
            using (var command = CreateCommand(identifierValues))
            {
                var connection = Translator.Connection;
                // configure command to use the connection and transaction for this session
                command.Transaction = ((null == connection.CurrentTransaction)
                                           ? null
                                           : connection.CurrentTransaction.StoreTransaction);
                command.Connection = connection.StoreConnection;
                if (Translator.CommandTimeout.HasValue)
                {
                    command.CommandTimeout = Translator.CommandTimeout.Value;
                }

                // Execute the query
                int rowsAffected;
                if (_modificationCommandTree.HasReader)
                {
                    // retrieve server gen results
                    rowsAffected = 0;
                    using (var reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
                    {
                        if (reader.Read())
                        {
                            rowsAffected++;

                            var members = TypeHelpers.GetAllStructuralMembers(CurrentValues.StructuralType);

                            for (var ordinal = 0; ordinal < reader.FieldCount; ordinal++)
                            {
                                // column name of result corresponds to column name of table
                                var    columnName = reader.GetName(ordinal);
                                var    member     = members[columnName];
                                object value;
                                if (Helper.IsSpatialType(member.TypeUsage) &&
                                    !reader.IsDBNull(ordinal))
                                {
                                    value = SpatialHelpers.GetSpatialValue(Translator.MetadataWorkspace, reader, member.TypeUsage, ordinal);
                                }
                                else
                                {
                                    value = reader.GetValue(ordinal);
                                }

                                // retrieve result which includes the context for back-propagation
                                var columnOrdinal = members.IndexOf(member);
                                var result        = CurrentValues.GetMemberValue(columnOrdinal);

                                // register for back-propagation
                                generatedValues.Add(new KeyValuePair <PropagatorResult, object>(result, value));

                                // register identifier if it exists
                                var identifier = result.Identifier;
                                if (PropagatorResult.NullIdentifier != identifier)
                                {
                                    identifierValues.Add(identifier, value);
                                }
                            }
                        }

                        // Consume the current reader (and subsequent result sets) so that any errors
                        // executing the command can be intercepted
                        CommandHelper.ConsumeReader(reader);
                    }
                }
                else
                {
                    // We currently only intercept commands on this code path.

                    var executeCommand = true;

                    if (commandInterceptor != null)
                    {
                        executeCommand = commandInterceptor.Intercept(command);
                    }

                    rowsAffected = executeCommand ? command.ExecuteNonQuery() : 1;
                }

                return(rowsAffected);
            }
        }
예제 #20
0
        internal override async Task <long> ExecuteAsync(
            Dictionary <int, object> identifierValues,
            List <KeyValuePair <PropagatorResult, object> > generatedValues,
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            long num;

            using (DbCommand command = this.CreateCommand(identifierValues))
            {
                EntityConnection connection = this.Translator.Connection;
                command.Transaction = connection.CurrentTransaction == null ? (DbTransaction)null : connection.CurrentTransaction.StoreTransaction;
                command.Connection  = connection.StoreConnection;
                if (this.Translator.CommandTimeout.HasValue)
                {
                    command.CommandTimeout = this.Translator.CommandTimeout.Value;
                }
                int rowsAffected;
                if (this._modificationCommandTree.HasReader)
                {
                    rowsAffected = 0;
                    using (DbDataReader reader = await command.ExecuteReaderAsync(CommandBehavior.SequentialAccess, cancellationToken).WithCurrentCulture <DbDataReader>())
                    {
                        if (await reader.ReadAsync(cancellationToken).WithCurrentCulture <bool>())
                        {
                            ++rowsAffected;
                            IBaseList <EdmMember> members = TypeHelpers.GetAllStructuralMembers((EdmType)this.CurrentValues.StructuralType);
                            for (int ordinal = 0; ordinal < reader.FieldCount; ++ordinal)
                            {
                                string    columnName = reader.GetName(ordinal);
                                EdmMember member     = members[columnName];
                                object    value;
                                if (Helper.IsSpatialType(member.TypeUsage))
                                {
                                    if (!await reader.IsDBNullAsync(ordinal, cancellationToken).WithCurrentCulture <bool>())
                                    {
                                        value = await SpatialHelpers.GetSpatialValueAsync(this.Translator.MetadataWorkspace, reader, member.TypeUsage, ordinal, cancellationToken).WithCurrentCulture <object>();

                                        goto label_14;
                                    }
                                }
                                value = await reader.GetFieldValueAsync <object>(ordinal, cancellationToken).WithCurrentCulture <object>();

label_14:
                                int columnOrdinal = members.IndexOf(member);
                                PropagatorResult result = this.CurrentValues.GetMemberValue(columnOrdinal);
                                generatedValues.Add(new KeyValuePair <PropagatorResult, object>(result, value));
                                int identifier = result.Identifier;
                                if (-1 != identifier)
                                {
                                    identifierValues.Add(identifier, value);
                                }
                            }
                        }
                        await CommandHelper.ConsumeReaderAsync(reader, cancellationToken).WithCurrentCulture();
                    }
                }
                else
                {
                    rowsAffected = await command.ExecuteNonQueryAsync(cancellationToken).WithCurrentCulture <int>();
                }
                num = (long)rowsAffected;
            }
            return(num);
        }
예제 #21
0
 internal override long Execute(
     Dictionary <int, object> identifierValues,
     List <KeyValuePair <PropagatorResult, object> > generatedValues)
 {
     using (DbCommand command = this.CreateCommand(identifierValues))
     {
         EntityConnection connection = this.Translator.Connection;
         command.Transaction = connection.CurrentTransaction == null ? (DbTransaction)null : connection.CurrentTransaction.StoreTransaction;
         command.Connection  = connection.StoreConnection;
         if (this.Translator.CommandTimeout.HasValue)
         {
             command.CommandTimeout = this.Translator.CommandTimeout.Value;
         }
         int num;
         if (this._modificationCommandTree.HasReader)
         {
             num = 0;
             using (DbDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
             {
                 if (reader.Read())
                 {
                     ++num;
                     IBaseList <EdmMember> structuralMembers = TypeHelpers.GetAllStructuralMembers((EdmType)this.CurrentValues.StructuralType);
                     for (int index = 0; index < reader.FieldCount; ++index)
                     {
                         string           name        = reader.GetName(index);
                         EdmMember        edmMember   = structuralMembers[name];
                         object           obj         = !Helper.IsSpatialType(edmMember.TypeUsage) || reader.IsDBNull(index) ? reader.GetValue(index) : SpatialHelpers.GetSpatialValue(this.Translator.MetadataWorkspace, reader, edmMember.TypeUsage, index);
                         PropagatorResult memberValue = this.CurrentValues.GetMemberValue(structuralMembers.IndexOf(edmMember));
                         generatedValues.Add(new KeyValuePair <PropagatorResult, object>(memberValue, obj));
                         int identifier = memberValue.Identifier;
                         if (-1 != identifier)
                         {
                             identifierValues.Add(identifier, obj);
                         }
                     }
                 }
                 CommandHelper.ConsumeReader(reader);
             }
         }
         else
         {
             num = command.ExecuteNonQuery();
         }
         return((long)num);
     }
 }
예제 #22
0
        /// <summary>
        ///     See comments in <see cref="UpdateCommand" />.
        /// </summary>
        internal override async Task <long> ExecuteAsync(
            Dictionary <int, object> identifierValues,
            List <KeyValuePair <PropagatorResult, object> > generatedValues, CancellationToken cancellationToken)
        {
            var connection = Translator.Connection;

            // configure command to use the connection and transaction for this session
            _dbCommand.Transaction = ((null == connection.CurrentTransaction)
                                          ? null
                                          : connection.CurrentTransaction.StoreTransaction);
            _dbCommand.Connection = connection.StoreConnection;
            if (Translator.CommandTimeout.HasValue)
            {
                _dbCommand.CommandTimeout = Translator.CommandTimeout.Value;
            }

            SetInputIdentifiers(identifierValues);

            // Execute the query
            long rowsAffected;

            if (null != ResultColumns)
            {
                // If there are result columns, read the server gen results
                rowsAffected = 0;
                var members = TypeHelpers.GetAllStructuralMembers(CurrentValues.StructuralType);
                using (
                    var reader =
                        await
                        _dbCommand.ExecuteReaderAsync(CommandBehavior.SequentialAccess, cancellationToken).ConfigureAwait(
                            continueOnCapturedContext: false))
                {
                    // Retrieve only the first row from the first result set
                    if (await reader.ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
                    {
                        rowsAffected++;

                        foreach (var resultColumn in ResultColumns
                                 .Select(r => new KeyValuePair <int, PropagatorResult>(GetColumnOrdinal(Translator, reader, r.Key), r.Value))
                                 .OrderBy(r => r.Key)) // order by column ordinal to avoid breaking SequentialAccess readers
                        {
                            var    columnOrdinal = resultColumn.Key;
                            var    columnType    = members[resultColumn.Value.RecordOrdinal].TypeUsage;
                            object value;

                            if (Helper.IsSpatialType(columnType)
                                &&
                                !await
                                reader.IsDBNullAsync(columnOrdinal, cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
                            {
                                value =
                                    await
                                    SpatialHelpers.GetSpatialValueAsync(
                                        Translator.MetadataWorkspace, reader, columnType, columnOrdinal, cancellationToken).ConfigureAwait(
                                        continueOnCapturedContext: false);
                            }
                            else
                            {
                                value =
                                    await
                                    reader.GetFieldValueAsync <object>(columnOrdinal, cancellationToken).ConfigureAwait(
                                        continueOnCapturedContext: false);
                            }

                            // register for back-propagation
                            var result = resultColumn.Value;
                            generatedValues.Add(new KeyValuePair <PropagatorResult, object>(result, value));

                            // register identifier if it exists
                            var identifier = result.Identifier;
                            if (PropagatorResult.NullIdentifier != identifier)
                            {
                                identifierValues.Add(identifier, value);
                            }
                        }
                    }

                    // Consume the current reader (and subsequent result sets) so that any errors
                    // executing the function can be intercepted
                    await CommandHelper.ConsumeReaderAsync(reader, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
                }
            }
            else
            {
                rowsAffected = await _dbCommand.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
            }

            return(GetRowsAffected(rowsAffected, Translator));
        }