/// <summary>
 /// Throws if collation value is not null and collations are not supported.
 /// </summary>
 /// <param name="serverVersion">The server version.</param>
 /// <param name="value">The value.</param>
 public void ThrowIfNotSupported(SemanticVersion serverVersion, Collation value)
 {
     if (value != null && !base.IsSupported(serverVersion))
     {
         throw new NotSupportedException($"Server version {serverVersion} does not support collations.");
     }
 }
        public void Collation_get_and_set_should_work()
        {
            var subject = new AggregateExplainOperation(_collectionNamespace, __pipeline, _messageEncoderSettings);
            var value = new Collation("en_US");

            subject.Collation = value;
            var result = subject.Collation;

            result.Should().BeSameAs(value);
        }
Exemplo n.º 3
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void btnCollation_Click(object sender, EventArgs e)
 {
     var frm = new frmCreateCollation();
     UIAssistant.OpenModalForm(frm, false, true);
     if (frm.mCollation != null)
     {
         mCollation = frm.mCollation;
         UiHelper.FillDataToTreeView("Collation", trvCollation, mCollation.ToBsonDocument());
     }
 }
Exemplo n.º 4
0
 private void cmdOK_Click(object sender, System.EventArgs e)
 {
     if (string.IsNullOrEmpty(txtLocale.Text))
     {
         MessageBox.Show("Please Input Locale!");
         return;
     }
     mCollation = new Collation(locale: txtLocale.Text,
                                caseLevel: chkCaseLevel.Checked,
                                numericOrdering: chkNumbericOrdering.Checked,
                                backwards: chkBackwards.Checked,
                                strength: ((CollationStrength)cmbStrength.SelectedIndex + 1),
                                maxVariable: (CollationMaxVariable)cmbMaxVariable.SelectedIndex,
                                alternate: (CollationAlternate)cmbAlternate.SelectedIndex,
                                caseFirst: (CollationCaseFirst)cmbCaseFirst.SelectedIndex);
     Close();
 }
Exemplo n.º 5
0
        ICollationPolicy.Collate(
            Collation sender,
            Bam.Core.ExecutionContext context)
        {
            var meta = new MakeFileBuilder.MakeFileMeta(sender);
            var rule = meta.AddRule();
            rule.AddTarget(Bam.Core.TokenizedString.CreateVerbatim("publish"), isPhony: true);

            foreach (var required in sender.Requirements)
            {
                var requiredMeta = required.MetaData as MakeFileBuilder.MakeFileMeta;
                if (null == requiredMeta)
                {
                    continue;
                }
                foreach (var rules in requiredMeta.Rules)
                {
                    // TODO: only the first?
                    rule.AddPrerequisite(rules.Targets[0]);
                }
            }
        }
        protected override bool TrySetArgument(string name, BsonValue value)
        {
            switch (name)
            {
            case "filter":
                _filter = (BsonDocument)value;
                return(true);

            case "replacement":
                _replacement = (BsonDocument)value;
                return(true);

            case "projection":
                _options.Projection = (BsonDocument)value;
                return(true);

            case "sort":
                _options.Sort = (BsonDocument)value;
                return(true);

            case "upsert":
                _options.IsUpsert = value.ToBoolean();
                return(true);

            case "returnDocument":
                _options.ReturnDocument = (ReturnDocument)Enum.Parse(typeof(ReturnDocument), value.ToString());
                return(true);

            case "collation":
                _options.Collation = Collation.FromBsonDocument(value.AsBsonDocument);
                return(true);

            case "hint":
                _options.Hint = value;
                return(true);
            }

            return(false);
        }
Exemplo n.º 7
0
        public void CreateCommand_should_return_expected_result_when_Collation_is_set(
            [Values("en_US", "fr_CA")]
            string locale)
        {
            var collation = new Collation(locale);
            var subject   = new AggregateExplainOperation(_collectionNamespace, __pipeline, _messageEncoderSettings)
            {
                Collation = collation
            };

            var result = subject.CreateCommand();

            var expectedResult = new BsonDocument
            {
                { "aggregate", _collectionNamespace.CollectionName },
                { "explain", true },
                { "pipeline", new BsonArray(__pipeline) },
                { "collation", collation.ToBsonDocument() }
            };

            result.Should().Be(expectedResult);
        }
Exemplo n.º 8
0
        private void DrawCollation(Dims parentDimensions, Collation collation, double height)
        {
            var x = collation.PosX;

            for (var kdx = 0; kdx < collation.CountX; ++kdx)
            {
                var y = collation.PosY;
                for (var ldx = 0; ldx < collation.CountY; ++ldx)
                {
                    var shape = new Shape3D(FormType.Box)
                    {
                        Length  = parentDimensions.Width,
                        Breadth = parentDimensions.Depth,
                        Height  = parentDimensions.Height,
                        X       = x,
                        Y       = y,
                        Z       = height
                    };
                    this.drawing.Shapes.Add(shape);
                }
            }
        }
Exemplo n.º 9
0
        private void ParseDeleteArguments(BsonDocument value, out FilterDefinition <BsonDocument> filter, out Collation collation)
        {
            filter    = null;
            collation = null;

            foreach (BsonElement argument in value["arguments"].AsBsonDocument)
            {
                switch (argument.Name)
                {
                case "collation":
                    collation = Collation.FromBsonDocument(argument.Value.AsBsonDocument);
                    break;

                case "filter":
                    filter = ParseFilter(argument.Value.AsBsonDocument);
                    break;

                default:
                    throw new FormatException($"Unexpected argument: {argument.Name}.");
                }
            }
        }
Exemplo n.º 10
0
        public void Execute_should_work_when_Collation_has_value(
            [Values("en_US", "fr_CA")]
            string locale,
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().Supports(Feature.Collation);
            DropCollection();
            var collation = new Collation(locale);
            var requests  = new[] { new CreateIndexRequest(new BsonDocument("x", 1))
                                    {
                                        Collation = collation
                                    } };
            var subject = new CreateIndexesUsingCommandOperation(_collectionNamespace, requests, _messageEncoderSettings);

            ExecuteOperation(subject, async);

            var indexes = ListIndexes();
            var index   = indexes.Single(i => i["name"].AsString == "x_1");

            index["collation"]["locale"].AsString.Should().Be(locale);
        }
        public void Execute_should_return_expected_results_when_Collation_is_set(
            [Values(false, true)]
            bool caseSensitive,
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().Supports(Feature.Collation);
            EnsureTestData();
            var collation = new Collation("en_US", caseLevel: caseSensitive, strength: CollationStrength.Primary);
            var filter    = BsonDocument.Parse("{ y : 'a' }");
            var subject   = new MapReduceOperation <BsonDocument>(_collectionNamespace, _mapFunction, _reduceFunction, _resultSerializer, _messageEncoderSettings)
            {
                Collation = collation,
                Filter    = filter
            };

            var cursor  = ExecuteOperation(subject, async);
            var results = ReadCursorToEnd(cursor, async);

            BsonDocument[] expectedResults;
            if (caseSensitive)
            {
                expectedResults = new[]
                {
                    BsonDocument.Parse("{ _id : 1, value : 1 }"),
                    BsonDocument.Parse("{ _id : 2, value : 4 }")
                };
            }
            else
            {
                expectedResults = new[]
                {
                    BsonDocument.Parse("{ _id : 1, value : 3 }"),
                    BsonDocument.Parse("{ _id : 2, value : 4 }")
                };
            }
            results.Should().Equal(expectedResults);
        }
Exemplo n.º 12
0
        protected override bool TrySetArgument(string name, BsonValue value)
        {
            switch (name)
            {
            case "filter":
                _filter = (BsonDocument)value;
                return(true);

            case "skip":
                _options.Skip = value.ToInt64();
                return(true);

            case "limit":
                _options.Limit = value.ToInt64();
                return(true);

            case "collation":
                _options.Collation = Collation.FromBsonDocument(value.AsBsonDocument);
                return(true);
            }

            return(false);
        }
Exemplo n.º 13
0
        protected override bool TrySetArgument(string name, BsonValue value)
        {
            switch (name)
            {
            case "filter":
                _filter = (BsonDocument)value;
                return(true);

            case "projection":
                _options.Projection = (BsonDocument)value;
                return(true);

            case "sort":
                _options.Sort = (BsonDocument)value;
                return(true);

            case "collation":
                _options.Collation = Collation.FromBsonDocument(value.AsBsonDocument);
                return(true);
            }

            return(false);
        }
Exemplo n.º 14
0
        ICollationPolicy.Collate(
            Collation sender,
            Bam.Core.ExecutionContext context)
        {
            var meta = new MakeFileBuilder.MakeFileMeta(sender);
            var rule = meta.AddRule();

            rule.AddTarget(Bam.Core.TokenizedString.CreateVerbatim("publish"), isPhony: true);

            foreach (var required in sender.Requirements)
            {
                var requiredMeta = required.MetaData as MakeFileBuilder.MakeFileMeta;
                if (null == requiredMeta)
                {
                    continue;
                }
                foreach (var rules in requiredMeta.Rules)
                {
                    // TODO: only the first?
                    rule.AddPrerequisite(rules.Targets[0]);
                }
            }
        }
Exemplo n.º 15
0
        protected override bool TrySetArgument(string name, BsonValue value)
        {
            switch (name)
            {
            case "pipeline":
                _stages = ((BsonArray)value).Cast <BsonDocument>().ToList();
                return(true);

            case "allowDiskUse":
                _options.AllowDiskUse = value.ToBoolean();
                return(true);

            case "batchSize":
                _options.BatchSize = (int)value;
                return(true);

            case "collation":
                _options.Collation = Collation.FromBsonDocument(value.AsBsonDocument);
                return(true);
            }

            return(false);
        }
Exemplo n.º 16
0
        protected override bool TrySetArgument(string name, BsonValue value)
        {
            switch (name)
            {
            case "filter":
                _filter = (BsonDocument)value;
                return(true);

            case "update":
                _update = (BsonDocument)value;
                return(true);

            case "upsert":
                _options.IsUpsert = value.ToBoolean();
                return(true);

            case "collation":
                _options.Collation = Collation.FromBsonDocument(value.AsBsonDocument);
                return(true);
            }

            return(false);
        }
        private void ParseReplaceArguments(
            BsonDocument value,
            out FilterDefinition <BsonDocument> filter,
            out BsonDocument replacement,
            out Collation collation,
            out bool isUpsert)
        {
            filter      = null;
            replacement = null;
            collation   = null;
            isUpsert    = false;

            foreach (BsonElement argument in value["arguments"].AsBsonDocument)
            {
                switch (argument.Name)
                {
                case "collation":
                    collation = Collation.FromBsonDocument(argument.Value.AsBsonDocument);
                    break;

                case "filter":
                    filter = ParseFilter(argument.Value.AsBsonDocument);
                    break;

                case "replacement":
                    replacement = argument.Value.AsBsonDocument;
                    break;

                case "upsert":
                    isUpsert = argument.Value.ToBoolean();
                    break;

                default:
                    throw new FormatException($"Unexpected argument: {argument.Name}.");
                }
            }
        }
Exemplo n.º 18
0
        protected override bool TrySetArgument(string name, BsonValue value)
        {
            switch (name)
            {
            case "filter":
                _filter = (BsonDocument)value;
                return(true);

            case "update":
                _update = value;
                return(true);

            case "upsert":
                _options.IsUpsert = value.ToBoolean();
                return(true);

            case "collation":
                _options.Collation = Collation.FromBsonDocument(value.AsBsonDocument);
                return(true);

            case "arrayFilters":
                var arrayFilters = new List <ArrayFilterDefinition>();
                foreach (BsonDocument arrayFilterDocument in value.AsBsonArray)
                {
                    var arrayFilter = new BsonDocumentArrayFilterDefinition <BsonDocument>(arrayFilterDocument);
                    arrayFilters.Add(arrayFilter);
                }
                _options.ArrayFilters = arrayFilters;
                return(true);

            case "hint":
                _options.Hint = value;
                return(true);
            }

            return(false);
        }
Exemplo n.º 19
0
        public void Execute_should_return_expected_results_when_Collation_is_set(
            [Values(false, true)]
            bool caseSensitive,
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().ClusterTypes(ClusterType.Standalone, ClusterType.ReplicaSet).Supports(Feature.Collation);
            EnsureTestData();
            var collation = new Collation("en_US", caseLevel: caseSensitive, strength: CollationStrength.Primary);
            var filter    = BsonDocument.Parse("{ y : 'a' }");
            var subject   = new MapReduceOutputToCollectionOperation(_collectionNamespace, _outputCollectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings)
            {
                Collation = collation,
                Filter    = filter
            };

            ExecuteOperation(subject, async);

            BsonDocument[] expectedResults;
            if (caseSensitive)
            {
                expectedResults = new[]
                {
                    BsonDocument.Parse("{ _id : 1, value : 1 }"),
                    BsonDocument.Parse("{ _id : 2, value : 4 }")
                };
            }
            else
            {
                expectedResults = new[]
                {
                    BsonDocument.Parse("{ _id : 1, value : 3 }"),
                    BsonDocument.Parse("{ _id : 2, value : 4 }")
                };
            }
            ReadAllFromCollection(_outputCollectionNamespace).Should().Equal(expectedResults);
        }
        public void Execute_should_return_expected_result_when_Collation_is_set(
            [Values(false, true)]
            bool caseSensitive,
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().Supports(Feature.Collation);
            EnsureTestData();
            var collation = new Collation("en_US", caseLevel: caseSensitive, strength: CollationStrength.Primary);
            var filter    = BsonDocument.Parse("{ y : 'a' }");
            var subject   = new GroupOperation <BsonDocument>(_collectionNamespace, _key, _initial, _reduceFunction, filter, _messageEncoderSettings)
            {
                Collation = collation
            };

            var result = ExecuteOperation(subject, async);

            BsonDocument[] expectedResult;
            if (caseSensitive)
            {
                expectedResult = new[]
                {
                    BsonDocument.Parse("{ x : 1, count : 2 }"),
                    BsonDocument.Parse("{ x : 3, count : 2 }")
                };
            }
            else
            {
                expectedResult = new[]
                {
                    BsonDocument.Parse("{ x : 1, count : 2 }"),
                    BsonDocument.Parse("{ x : 2, count : 1 }"),
                    BsonDocument.Parse("{ x : 3, count : 3 }")
                };
            }
            result.Should().Equal(expectedResult);
        }
Exemplo n.º 21
0
        // methods
        internal override BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescription connectionDescription, long?transactionNumber)
        {
            var serverVersion = connectionDescription.ServerVersion;

            Feature.Collation.ThrowIfNotSupported(serverVersion, Collation);

            var writeConcern = WriteConcernHelper.GetWriteConcernForCommand(session, WriteConcern, serverVersion, Feature.FindAndModifyWriteConcern);

            return(new BsonDocument
            {
                { "findAndModify", CollectionNamespace.CollectionName },
                { "query", _filter },
                { "update", _replacement },
                { "new", true, _returnDocument == ReturnDocument.After },
                { "sort", _sort, _sort != null },
                { "fields", _projection, _projection != null },
                { "upsert", true, _isUpsert },
                { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue },
                { "writeConcern", writeConcern, writeConcern != null },
                { "bypassDocumentValidation", () => _bypassDocumentValidation.Value, _bypassDocumentValidation.HasValue&& Feature.BypassDocumentValidation.IsSupported(serverVersion) },
                { "collation", () => Collation.ToBsonDocument(), Collation != null },
                { "txnNumber", () => transactionNumber, transactionNumber.HasValue }
            });
        }
        public void Equals_should_compare_normalization_fields(
            [Values(null, false, true)]
            bool? lhsNormalization,
            [Values(null, false, true)]
            bool? rhsNormalization)
        {
            var lhs = new Collation("en_US", normalization: lhsNormalization);
            var rhs = new Collation("en_US", normalization: rhsNormalization);

            Equals_Act_and_Assert(lhs, rhs, lhsNormalization == rhsNormalization);
        }
        public void With_should_return_expected_result(
            [Values("en_US", "fr_CA")]
            string locale)
        {
            var subject = new Collation(locale);

            var result = subject.With();

            result.Should().Be(subject);
        }
 internal SqlDropCollation(Collation collation) : base(SqlNodeType.Drop)
 {
     this.collation = collation;
 }
        public void With_should_return_expected_result_when_backwards_is_set(
            [Values(null, false, true)]
            bool? originalBackwards,
            [Values(null, false, true)]
            bool? backwards)
        {
            var subject = new Collation("en_US", backwards: originalBackwards);

            var result = subject.With(backwards: backwards);

            result.Backwards.Should().Be(backwards);
            result.With(backwards: originalBackwards).Should().Be(subject);
        }
Exemplo n.º 26
0
 /// <summary>
 /// Deletes matching entities with an expression
 /// <para>HINT: If the expression matches more than 100,000 entities, they will be deleted in batches of 100k.</para>
 /// <para>HINT: If these entities are referenced by one-to-many/many-to-many relationships, those references are also deleted.</para>
 /// </summary>
 /// <typeparam name="T">Any class that implements IEntity</typeparam>
 /// <param name="expression">A lambda expression for matching entities to delete.</param>
 /// <param name = "session" >An optional session if using within a transaction</param>
 /// <param name="cancellation">An optional cancellation token</param>
 /// <param name="collation">An optional collation object</param>
 public static Task <DeleteResult> DeleteAsync <T>(Expression <Func <T, bool> > expression, IClientSessionHandle session = null, CancellationToken cancellation = default, Collation collation = null) where T : IEntity
 {
     return(DeleteAsync(Builders <T> .Filter.Where(expression), session, cancellation, collation));
 }
Exemplo n.º 27
0
        /// <summary>
        /// Deletes matching entities with a filter definition
        /// <para>HINT: If the expression matches more than 100,000 entities, they will be deleted in batches of 100k.</para>
        /// <para>HINT: If these entities are referenced by one-to-many/many-to-many relationships, those references are also deleted.</para>
        /// </summary>
        /// <typeparam name="T">Any class that implements IEntity</typeparam>
        /// <param name="filter">A filter definition for matching entities to delete.</param>
        /// <param name = "session" >An optional session if using within a transaction</param>
        /// <param name="cancellation">An optional cancellation token</param>
        /// <param name="collation">An optional collation object</param>
        public static async Task <DeleteResult> DeleteAsync <T>(FilterDefinition <T> filter, IClientSessionHandle session = null, CancellationToken cancellation = default, Collation collation = null) where T : IEntity
        {
            ThrowIfCancellationNotSupported(session, cancellation);

            var cursor = await new Find <T, string>(session, null)
                         .Match(_ => filter)
                         .Project(e => e.ID)
                         .Option(o => o.BatchSize = deleteBatchSize)
                         .Option(o => o.Collation = collation)
                         .ExecuteCursorAsync(cancellation)
                         .ConfigureAwait(false);

            long         deletedCount = 0;
            DeleteResult res          = null;

            using (cursor)
            {
                while (await cursor.MoveNextAsync(cancellation).ConfigureAwait(false))
                {
                    if (cursor.Current.Any())
                    {
                        res = await DeleteCascadingAsync <T>(cursor.Current, session, cancellation).ConfigureAwait(false);

                        deletedCount += res.DeletedCount;
                    }
                }
            }

            if (res?.IsAcknowledged == false)
            {
                return(DeleteResult.Unacknowledged.Instance);
            }

            return(new DeleteResult.Acknowledged(deletedCount));
        }
        public void ToBsonDocument_should_return_expected_result_when_caseFirst_is_set(
            [Values("en_US", "fr_CA")]
            string locale,
            [Values(null, CollationCaseFirst.Lower, CollationCaseFirst.Upper)]
            CollationCaseFirst? caseFirst)
        {
            var subject = new Collation(locale, caseFirst: caseFirst);

            var result = subject.ToBsonDocument();
            var json = subject.ToString();

            var expectedResult = new BsonDocument
            {
                { "locale", locale },
                { "caseFirst", () => Collation.ToString(caseFirst.Value), caseFirst.HasValue }
            };
            result.Should().Be(expectedResult);
            json.Should().Be(expectedResult.ToJson());
        }
 /// <inheritdoc/>
 /// <exception cref="NotSupportedException">Method is not supported.</exception>
 protected override IPathNode VisitCollation(Collation collation)
 {
     throw new NotSupportedException();
 }
        public void With_should_return_expected_result_when_maxVariable_is_set(
            [Values(null, CollationMaxVariable.Punctuation, CollationMaxVariable.Space)]
            CollationMaxVariable? originalMaxVariable,
            [Values(null, CollationMaxVariable.Punctuation, CollationMaxVariable.Space)]
            CollationMaxVariable? maxVariable)
        {
            var subject = new Collation("en_US", maxVariable: originalMaxVariable);

            var result = subject.With(maxVariable: maxVariable);

            result.MaxVariable.Should().Be(maxVariable);
            result.With(maxVariable: originalMaxVariable).Should().Be(subject);
        }
        public void ToBsonDocument_should_return_expected_result_when_caseLevel_is_set(
            [Values("en_US", "fr_CA")]
            string locale,
            [Values(null, false, true)]
            bool? caseLevel)
        {
            var subject = new Collation(locale, caseLevel: caseLevel);

            var result = subject.ToBsonDocument();
            var json = subject.ToString();

            var expectedResult = new BsonDocument
            {
                { "locale", locale },
                { "caseLevel", () => caseLevel.Value, caseLevel.HasValue }
            };
            result.Should().Be(expectedResult);
            json.Should().Be(expectedResult.ToJson());
        }
        public void With_should_return_expected_result_when_locale_is_set(
            [Values("en_US", "fr_CA")]
            string originalLocale,
            [Values("en_US", "fr_CA")]
            string locale)
        {
            var subject = new Collation(originalLocale);

            var result = subject.With(locale: locale);

            result.Locale.Should().Be(locale);
            result.With(locale: originalLocale).Should().Be(subject);
        }
        public void With_should_return_expected_result_when_caseLevel_is_set(
            [Values(null, false, true)]
            bool? originalCaseLevel,
            [Values(null, false, true)]
            bool? caseLevel)
        {
            var subject = new Collation("en_US", caseLevel: originalCaseLevel);

            var result = subject.With(caseLevel: caseLevel);

            result.CaseLevel.Should().Be(caseLevel);
            result.With(caseLevel: originalCaseLevel).Should().Be(subject);
        }
        public void With_should_return_expected_result_when_caseFirst_is_set(
            [Values(null, CollationCaseFirst.Lower, CollationCaseFirst.Upper)]
            CollationCaseFirst? originalCaseFirst,
            [Values(null, CollationCaseFirst.Lower, CollationCaseFirst.Upper)]
            CollationCaseFirst? caseFirst)
        {
            var subject = new Collation("en_US", caseFirst: originalCaseFirst);

            var result = subject.With(caseFirst: caseFirst);

            result.CaseFirst.Should().Be(caseFirst);
            result.With(caseFirst: originalCaseFirst).Should().Be(subject);
        }
Exemplo n.º 35
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void btnClearCollation_Click(object sender, EventArgs e)
 {
     mCollation = null;
     trvCollation.Clear();
 }
Exemplo n.º 36
0
 /// <summary>
 /// Create a new TypeSpecification object.
 /// </summary>
 /// <param name="typeName">Initial value of TypeName.</param>
 /// <param name="collation">Initial value of Collation.</param>
 /// <param name="characterSet">Initial value of CharacterSet.</param>
 /// <param name="isMultiSet">Initial value of IsMultiSet.</param>
 public static TypeSpecification CreateTypeSpecification(string typeName, Collation collation, CharacterSet characterSet, bool isMultiSet)
 {
   TypeSpecification typeSpecification = new TypeSpecification();
   typeSpecification.TypeName = typeName;
   typeSpecification.Collation = global::System.Data.Objects.DataClasses.StructuralObject.VerifyComplexObjectIsNotNull(collation, "Collation");
   typeSpecification.CharacterSet = global::System.Data.Objects.DataClasses.StructuralObject.VerifyComplexObjectIsNotNull(characterSet, "CharacterSet");
   typeSpecification.IsMultiSet = isMultiSet;
   return typeSpecification;
 }
        public void ToBsonDocument_should_return_expected_result_when_numericOrdering_is_set(
            [Values("en_US", "fr_CA")]
            string locale,
            [Values(null, false, true)]
            bool? numericOrdering)
        {
            var subject = new Collation(locale, numericOrdering: numericOrdering);

            var result = subject.ToBsonDocument();
            var json = subject.ToString();

            var expectedResult = new BsonDocument
            {
                { "locale", locale },
                { "numericOrdering", () => numericOrdering.Value, numericOrdering.HasValue }
            };
            result.Should().Be(expectedResult);
            json.Should().Be(expectedResult.ToJson());
        }
        public void ToBsonDocument_should_return_expected_result_when_backwards_is_set(
            [Values("en_US", "fr_CA")]
            string locale,
            [Values(null, false, true)]
            bool? backwards)
        {
            var subject = new Collation(locale, backwards: backwards);

            var result = subject.ToBsonDocument();
            var json = subject.ToString();

            var expectedResult = new BsonDocument
            {
                { "locale", locale },
                { "backwards", () => backwards.Value, backwards.HasValue }
            };
            result.Should().Be(expectedResult);
            json.Should().Be(expectedResult.ToJson());
        }
        public void Equals_should_compare_strenght_fields(
            [Values(null, CollationStrength.Primary, CollationStrength.Identical)]
            CollationStrength? lhsStrength,
            [Values(null, CollationStrength.Primary, CollationStrength.Identical)]
            CollationStrength? rhsStrength)
        {
            var lhs = new Collation("en_US", strength: lhsStrength);
            var rhs = new Collation("en_US", strength: rhsStrength);

            Equals_Act_and_Assert(lhs, rhs, lhsStrength == rhsStrength);
        }
        public void Execute_should_return_expected_result_when_Collation_is_set(
            [Values(false, true)]
            bool caseSensitive,
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().Supports(Feature.Aggregate, Feature.Collation);
            EnsureTestData();
            var collation = new Collation("en_US", caseLevel: caseSensitive, strength: CollationStrength.Primary);
            var subject = new AggregateOperation<BsonDocument>(_collectionNamespace, __pipeline, __resultSerializer, _messageEncoderSettings)
            {
                Collation = collation
            };

            var cursor = ExecuteOperation(subject, async);
            var result = ReadCursorToEnd(cursor, async);

            result.Should().NotBeNull();
            result.Should().HaveCount(caseSensitive ? 1 : 2);
        }
Exemplo n.º 41
0
 /// <summary>
 /// Deletes matching entities with a filter expression
 /// <para>HINT: If the expression matches more than 100,000 entities, they will be deleted in batches of 100k.</para>
 /// <para>HINT: If these entities are referenced by one-to-many/many-to-many relationships, those references are also deleted.</para>
 /// </summary>
 /// <typeparam name="T">Any class that implements IEntity</typeparam>
 /// <param name="filter">f => f.Eq(x => x.Prop, Value) &amp; f.Gt(x => x.Prop, Value)</param>
 /// <param name = "session" >An optional session if using within a transaction</param>
 /// <param name="cancellation">An optional cancellation token</param>
 /// <param name="collation">An optional collation object</param>
 public static Task <DeleteResult> DeleteAsync <T>(Func <FilterDefinitionBuilder <T>, FilterDefinition <T> > filter, IClientSessionHandle session = null, CancellationToken cancellation = default, Collation collation = null) where T : IEntity
 {
     return(DeleteAsync(filter(Builders <T> .Filter), session, cancellation, collation));
 }
Exemplo n.º 42
0
 /// <summary>
 /// Deletes matching entities from MongoDB
 /// <para>HINT: If these entities are referenced by one-to-many/many-to-many relationships, those references are also deleted.</para>
 /// <para>TIP: Try to keep the number of entities to delete under 100 in a single call</para>
 /// </summary>
 /// <typeparam name="T">The type of entity</typeparam>
 /// <param name="expression">A lambda expression for matching entities to delete.</param>
 /// <param name="cancellation">An optional cancellation token</param>
 /// <param name="collation">An optional collation object</param>
 /// <param name="ignoreGlobalFilters">Set to true if you'd like to ignore any global filters for this operation</param>
 public Task <DeleteResult> DeleteAsync <T>(Expression <Func <T, bool> > expression, CancellationToken cancellation = default, Collation collation = null, bool ignoreGlobalFilters = false) where T : IEntity
 {
     return(DB.DeleteAsync(
                Logic.MergeWithGlobalFilter(ignoreGlobalFilters, globalFilters, Builders <T> .Filter.Where(expression)),
                Session,
                cancellation,
                collation));
 }
Exemplo n.º 43
0
        /// <summary>
        /// 构造方法会自动建立所需要的索引
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="colname">mongodb里article集合的名称</param>
        /// <param name="mapper"></param>
        /// <param name="logService">用来获取点赞、收藏信息的LogService</param>
        /// <param name="esClient">如果不用es,手动传入null</param>
        /// <param name="userService"></param>
        /// <param name="imageService">imageservice只有word上传用到了,不准备使用word上传功能的话可以设为null</param>
        /// <param name="readlogService">用来获得用户阅读信息的logservice,可以和之前的logservice相同</param>
        /// <param name="getSearchFromArticle">把article映射到articlesearch的函数</param>
        /// <param name="mapArticleToBrief">把article映射成brief的函数</param>
        public IntergratedArticleService(IBaseDbSettings settings, string colname, IMapper mapper,
                                         ILogService <TUserBrief> logService, IElasticClient esClient, IUserService <TUser> userService
                                         , IImageService imageService, ILogService <TUserBrief> readlogService
                                         , Func <TArticle, TArticleSearch> getSearchFromArticle, Expression <Func <TArticle, TArticleFeed> > mapArticleToBrief)
            : base(settings.ConnectionString, settings.DatabaseName, colname)
        {
            this.getSearchFromArticle = getSearchFromArticle;
            this.mapArticleToBrief    = mapArticleToBrief;
            this.readlogService       = readlogService;
            enableEs    = esClient != null;
            client      = esClient;
            allowedTags = HtmlSanitizer.DefaultAllowedTags.ToList();
            allowedTags.Add("audio");
            allowedTags.Add("svg");
            allowedTags.Add("source");
            allowedTags.Add("style");
            allowedTags.Add("path");
            allowedTags.Add("iframe");
            allowedTags.Add("img");
            allowedTags.Add("blockquote");
            allowedTags.Add("span");
            allowedTags.Add("center");
            this.userService = userService;
            this.logService  = logService;
            pipeline         = new MarkdownPipelineBuilder()
                               .UseAdvancedExtensions()
                               .UseDiagrams()
                               .UseEmphasisExtras()
                               .UseEmojiAndSmiley()
                               .UseGridTables()
                               .UsePipeTables()
                               //.UseMathematics()
                               .UseMediaLinks()
                               .UseAutoLinks()
                               .UseFigures()
                               .UseFooters()
                               .UseFootnotes()
                               .Build();
            Collation _caseInsensitiveCollation = new Collation("en", strength: CollationStrength.Primary);

            this.imageService = imageService;
            this.mapper       = mapper;
createIndex:
            try
            {
                collection.Indexes.CreateOne(new CreateIndexModel <TArticle>(Builders <TArticle> .IndexKeys.Ascending(l => l.Stars)));
                collection.Indexes.CreateOne(new CreateIndexModel <TArticle>(Builders <TArticle> .IndexKeys.Ascending(l => l.Awesomes)));
                collection.Indexes.CreateOne(new CreateIndexModel <TArticle>(Builders <TArticle> .IndexKeys.Ascending(l => l.IsDraft)));
                collection.Indexes.CreateOne(new CreateIndexModel <TArticle>(Builders <TArticle> .IndexKeys.Ascending(l => l.AuthorBrief.Id)));
                collection.Indexes.CreateOne(new CreateIndexModel <TArticle>(Builders <TArticle> .IndexKeys.Ascending(l => l.Visibility)));
                collection.Indexes.CreateOne(new CreateIndexModel <TArticle>(Builders <TArticle> .IndexKeys.Ascending(l => l.KeyWords),
                                                                             new CreateIndexOptions()
                {
                    Collation = _caseInsensitiveCollation
                }));
                collection.Indexes.CreateOne(new CreateIndexModel <TArticle>(Builders <TArticle> .IndexKeys.Ascending(l => l.ProjectId)));
                collection.Indexes.CreateOne(new CreateIndexModel <TArticle>(Builders <TArticle> .IndexKeys.Ascending(l => l.Saved)));
                collection.Indexes.CreateOne(new CreateIndexModel <TArticle>(Builders <TArticle> .IndexKeys.Ascending(l => l.ArticleId)));
                collection.Indexes.CreateOne(new CreateIndexModel <TArticle>(Builders <TArticle> .IndexKeys.Ascending(l => l.Score)));
                collection.Indexes.CreateOne(new CreateIndexModel <TArticle>(Builders <TArticle> .IndexKeys.Ascending(l => l.Examined)));
                collection.Indexes.CreateOne(new CreateIndexModel <TArticle>(Builders <TArticle> .IndexKeys.Ascending(l => l.Tokens),
                                                                             new CreateIndexOptions()
                {
                    Collation = _caseInsensitiveCollation
                }));
                collection.Indexes.CreateOne(new CreateIndexModel <TArticle>(Builders <TArticle> .IndexKeys.Ascending(l => l.ManagedId)));
            }
            catch (Exception)
            {
                collection.Indexes.DropAll();
                goto createIndex;
            }
            Config config = new Config();

            // 设置上传区域
            config.Zone = Zone.ZONE_CN_East;
            // 设置 http 或者 https 上传
            config.UseHttps      = true;
            config.UseCdnDomains = true;
            config.ChunkSize     = ChunkUnit.U512K;
            target = new ResumableUploader(config);
            var attrs = new[]
            {
                "style",
                "class",
                "href",
                "alt",
                "src",
                "controls",
                "id",
                "preserveAspectRatio",
                "d",
                "viewBox",
                "width",
                "height",
                "title",
                "data-formula",
                "aria-hidden",
            };

            foreach (var item in attrs)
            {
                HtmlSanitizer.DefaultAllowedAttributes.Add(item);
            }
            sanitizer = new HtmlSanitizer(allowedTags, allowedAttributes: HtmlSanitizer.DefaultAllowedAttributes);
            //StartReportService();
            //StartElastic();
        }
        public void Equals_should_compare_numericOrdering_fields(
            [Values(null, false, true)]
            bool? lhsNumericOrdering,
            [Values(null, false, true)]
            bool? rhsNumericOrdering)
        {
            var lhs = new Collation("en_US", numericOrdering: lhsNumericOrdering);
            var rhs = new Collation("en_US", numericOrdering: rhsNumericOrdering);

            Equals_Act_and_Assert(lhs, rhs, lhsNumericOrdering == rhsNumericOrdering);
        }
        public void Execute_should_throw_when_Collation_is_set_but_not_supported(
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().Supports(Feature.Aggregate).DoesNotSupport(Feature.Collation);
            var collation = new Collation("en_US");
            var subject = new AggregateOperation<BsonDocument>(_collectionNamespace, __pipeline, __resultSerializer, _messageEncoderSettings)
            {
                Collation = collation
            };

            var exception = Record.Exception(() => ExecuteOperation(subject, async));

            exception.Should().BeOfType<NotSupportedException>();
        }
        public void With_should_return_expected_result_when_alternate_is_set(
            [Values(null, CollationAlternate.NonIgnorable, CollationAlternate.Shifted)]
            CollationAlternate? originalAlternate,
            [Values(null, CollationAlternate.NonIgnorable, CollationAlternate.Shifted)]
            CollationAlternate? alternate)
        {
            var subject = new Collation("en_US", alternate: originalAlternate);

            var result = subject.With(alternate: alternate);

            result.Alternate.Should().Be(alternate);
            result.With(alternate: originalAlternate).Should().Be(subject);
        }
Exemplo n.º 47
0
 /// <summary>
 /// Deletes matching entities with a filter definition
 /// <para>HINT: If the expression matches more than 100,000 entities, they will be deleted in batches of 100k.</para>
 /// <para>HINT: If these entities are referenced by one-to-many/many-to-many relationships, those references are also deleted.</para>
 /// </summary>
 /// <typeparam name="T">Any class that implements IEntity</typeparam>
 /// <param name="filter">A filter definition for matching entities to delete.</param>
 /// <param name="cancellation">An optional cancellation token</param>
 /// <param name="collation">An optional collation object</param>
 /// <param name="ignoreGlobalFilters">Set to true if you'd like to ignore any global filters for this operation</param>
 public Task <DeleteResult> DeleteAsync <T>(FilterDefinition <T> filter, CancellationToken cancellation = default, Collation collation = null, bool ignoreGlobalFilters = false) where T : IEntity
 {
     return(DB.DeleteAsync(
                Logic.MergeWithGlobalFilter(ignoreGlobalFilters, globalFilters, filter),
                Session,
                cancellation,
                collation));
 }
        public void ToBsonDocument_should_return_expected_result_when_alternate_is_set(
            [Values("en_US", "fr_CA")]
            string locale,
            [Values(null, CollationAlternate.NonIgnorable, CollationAlternate.Shifted)]
            CollationAlternate? alternate)
        {
            var subject = new Collation(locale, alternate: alternate);

            var result = subject.ToBsonDocument();
            var json = subject.ToString();

            var expectedResult = new BsonDocument
            {
                { "locale", locale },
                { "alternate", () => Collation.ToString(alternate.Value), alternate.HasValue }
            };
            result.Should().Be(expectedResult);
            json.Should().Be(expectedResult.ToJson());
        }
Exemplo n.º 49
0
        public QueryOptimization(Snapshot snapshot, Query query, IEnumerable<BsonDocument> source, Collation collation)
        {
            if (query.Select == null) throw new ArgumentNullException(nameof(query.Select));

            _snapshot = snapshot;
            _query = query;
            _collation = collation;

            _queryPlan = new QueryPlan(snapshot.CollectionName)
            {
                // define index only if source are external collection
                Index = source != null ? new IndexVirtual(source) : null,
                Select = new Select(_query.Select, _query.Select.UseSource),
                ForUpdate = query.ForUpdate,
                Limit = query.Limit,
                Offset = query.Offset
            };
        }
Exemplo n.º 50
0
 public SortContainer(Collation collation, int size)
 {
     _collation = collation;
     _size      = size;
 }
        public void ToBsonDocument_should_return_expected_result(
            [Values("en_US", "fr_CA")]
            string locale)
        {
            var subject = new Collation(locale);

            var result = subject.ToBsonDocument();
            var json = subject.ToString();

            var expectedResult = new BsonDocument("locale", locale);
            result.Should().Be(expectedResult);
            json.Should().Be(expectedResult.ToJson());
        }
        public void ToBsonDocument_should_return_expected_result_when_strength_is_set(
            [Values("en_US", "fr_CA")]
            string locale,
            [Values(null, CollationStrength.Primary, CollationStrength.Identical)]
            CollationStrength? strength)
        {
            var subject = new Collation(locale, strength: strength);

            var result = subject.ToBsonDocument();
            var json = subject.ToString();

            var expectedResult = new BsonDocument
            {
                { "locale", locale },
                { "strength", () => Collation.ToInt32(strength.Value), strength.HasValue }
            };
            result.Should().Be(expectedResult);
            json.Should().Be(expectedResult.ToJson());
        }
Exemplo n.º 53
0
 /// <inheritdoc/>
 public override string Translate(Collation collation)
 {
     return(collation.DbName);
 }
 /// <summary>
 /// Sets the collation.
 /// </summary>
 /// <param name="value">The collation.</param>
 /// <returns>The builder (so method calls can be chained).</returns>
 public CollectionOptionsBuilder SetCollation(Collation value)
 {
     _document["collation"] = value.ToBsonDocument();
     return(this);
 }
Exemplo n.º 55
0
        public void Culture_Ordinal_Sort()
        {
            // 1046 = pt-BR
            var collation = new Collation(1046, CompareOptions.IgnoreCase);

            var s = new EngineSettings
            {
                DataStream = new MemoryStream()
            };

            var names = new string[] { "Ze", "Ana", "Ána", "Ánã", "Ana Paula", "ana lucia" };

            var sortByLinq = names.OrderBy(x => x, collation).ToArray();
            var findByLinq = names.Where(x => collation.Compare(x, "ANA") == 0).ToArray();

            using (var e = new LiteEngine(s))
            {
                //e.Rebuild(new RebuildOptions { Collation = collation });

                e.Insert("col1", names.Select(x => new BsonDocument {
                    ["name"] = x
                }), BsonAutoId.Int32);

                // sort by merge sort
                var sortByOrderByName = e.Query("col1", new Query {
                    OrderBy = "name"
                })
                                        .ToEnumerable()
                                        .Select(x => x["name"].AsString)
                                        .ToArray();

                var query = new Query();
                query.Where.Add("name = 'ANA'");

                // find by expression
                var findByExpr = e.Query("col1", query)
                                 .ToEnumerable()
                                 .Select(x => x["name"].AsString)
                                 .ToArray();

                sortByOrderByName.Should().BeEquivalentTo(sortByLinq);
                findByExpr.Should().BeEquivalentTo(findByLinq);

                // index test
                e.EnsureIndex("col1", "idx_name", "name", false);

                // sort by index
                var sortByIndexName = e.Query("col1", new Query {
                    OrderBy = "name"
                })
                                      .ToEnumerable()
                                      .Select(x => x["name"].AsString)
                                      .ToArray();

                // find by index
                var findByIndex = e.Query("col1", query)
                                  .ToEnumerable()
                                  .Select(x => x["name"].AsString)
                                  .ToArray();

                sortByIndexName.Should().BeEquivalentTo(sortByLinq);
                findByIndex.Should().BeEquivalentTo(findByLinq);
            }
        }
 /// <summary>
 /// Sets the collation.
 /// </summary>
 /// <param name="value">The collation.</param>
 /// <returns>The builder (so method calls can be chained).</returns>
 public static CollectionOptionsBuilder SetCollation(Collation value)
 {
     return(new CollectionOptionsBuilder().SetCollation(value));
 }
        public void CreateCollation(string name, Collation collation)
        {
            name = name.ToUpperInvariant();

            var nativeCollation = new CollationNative((applicationData, firstLength, firstString, secondLength, secondString) =>
            {
                var first = this.platformMarshal.MarshalStringNativeUTF8ToManaged(firstString);
                var second = this.platformMarshal.MarshalStringNativeUTF8ToManaged(secondString);

                try
                {
                    return collation.Invoke(first, second);
                }
                catch
                {
                    return 0;
                }
            });

            var collationDelegate = this.platformMarshal.ApplyNativeCallingConventionToCollation(nativeCollation);
            this.collationDelegates[name] = collationDelegate;

            var collPtr = this.platformMarshal.MarshalDelegateToNativeFunctionPointer(collationDelegate);

            int nameLength;
            var namePtr = this.platformMarshal.MarshalStringManagedToNativeUTF8(name, out nameLength);

            try
            {
                this.sqlite3Provider.Sqlite3CreateCollation(this.db, namePtr, collPtr);
            }
            finally
            {
                if (namePtr != IntPtr.Zero)
                {
                    this.platformMarshal.CleanUpStringNativeUTF8(namePtr);
                }
            }
        }
        public void ToBsonDocument_should_return_expected_result_when_maxVariable_is_set(
            [Values("en_US", "fr_CA")]
            string locale,
            [Values(null, CollationMaxVariable.Punctuation, CollationMaxVariable.Space)]
            CollationMaxVariable? maxVariable)
        {
            var subject = new Collation(locale, maxVariable: maxVariable);

            var result = subject.ToBsonDocument();
            var json = subject.ToString();

            var expectedResult = new BsonDocument
            {
                { "locale", locale },
                { "maxVariable", () => Collation.ToString(maxVariable.Value), maxVariable.HasValue }
            };
            result.Should().Be(expectedResult);
            json.Should().Be(expectedResult.ToJson());
        }
Exemplo n.º 59
0
 partial void OnCollationChanging(Collation value);
        public void Collation_get_and_set_should_work()
        {
            var subject = new AggregateOperation<BsonDocument>(_collectionNamespace, __pipeline, __resultSerializer, _messageEncoderSettings);
            var collation = new Collation("en_US");

            subject.Collation = collation;
            var result = subject.Collation;

            result.Should().BeSameAs(collation);
        }