diff --git a/ChangeLog/7.3.0-Beta-1-dev.txt b/ChangeLog/7.3.0-Beta-1-dev.txt index 7c0a4336d2..5b3466d73c 100644 --- a/ChangeLog/7.3.0-Beta-1-dev.txt +++ b/ChangeLog/7.3.0-Beta-1-dev.txt @@ -1,4 +1,11 @@ [main] Switch to .NET8/.NET10-only support, nuget packages actualized +[main] SerializableExpressions API moved to Xtensive.Orm.SerializableExpressions extension +[main] Operations API moved to Xtensive.Orm.Operations extension, which is functionally the same. Only base types left in main library +[main] Session.Operations property type changed to interface, real implementor of which is in Xtensive.Orm.Operations extension +[main] By default, no operations registered nor registration scopes created, during Entity lifetime, which made Entites work faster +[main] Entity, Persistent, EntitySet{T} types no longer support binary serialization. If serialization needed use DTOs as modern approach recommends +[main] Removed all signs of obsolete binary serialization, like ISerializable or IDeserializationCallback usage +[main] No type marked [Serializable] exists in the entire assembly typeset, due to no need for the types to be truly serializable and binary serialization obsolete [main] Removed obsolete member Values of SqlInsert type [main] Removed obsolete methods GetSingleConstructor/GetSingleConstructorOrDefault of TypeHelper type [main] Removed obsolete constant WellKnown.MaxNumberOfConditions, use DefaultMaxNumberOfConditions instead @@ -6,6 +13,13 @@ [main] Collection FixedList3 is removed [main] Xtensive.Orm.Rse.Providers.Provider descendants no longer build RecordSetHeader on initialization via virtual method [main] Many compilable providers build headers more easily with static methods +[main] Collections.Deque collection as well as Collections.Interfaces.IDeque interface marked obsolete because there is no internal use +[main] TupleUpdater is obsolete because it is not in use so will be removed +[main] IntegrityException is obsolete +[main] ReferenceInfo struct became readonly, properties replaced with readonly fields +[main] ColumnInfoRef properties replaced with readonly fields +[main] Improve domain model validation speed +[main] Fixed Tuple.Format() method, which correctly works with DateOnly, TimeOnly, DateTimeOffset and byte[] values now [firebird] Switch to .NET8/.NET10-only support, nuget packages actualized [firebird] Support for Firebird 2.5 ended due to end-of-life state [mysql] Switch to .NET8/.NET10-only support, nuget packages actualized @@ -18,12 +32,19 @@ [bulkoperations] Switch to .NET8/.NET10-only support [localization] Switch to .NET8/.NET10-only support, nuget packages actualized [localization] Removed obsolete member of ConfigurationSection type +[localization] All [Serializable] attribute usages eliminated because no reason for them to exist [logging.log4net] Switch to .NET8/.NET10-only support, nuget packages actualize [logging.NLog] Switch to .NET8/.NET10-only support, nuget packages actualized +[operations] Made operations be JsonSerializer compatible. +[operations] Created json-converters which can be added by calling AddOperationsConverters() extension method [reprocessing] Switch to .NET8/.NET10-only support, nuget packages actualized [reprocessing] Removed obsolete member of ConfigurationSection type +[reprocessing] All [Serializable] attribute usages eliminated because no reason for them to exist [security] Switch to .NET8/.NET10-only support, nuget packages actualized [security] Removed obsolete member of ConfigurationSection type +[security] All [Serializable] attribute usages eliminated because no reason for them to exist +[serializable expressions] Made expressions JsonSerializer- and DataContractSerializer-compatible. [tracking] Switch to .NET8/.NET10-only support, nuget packages actualized +[tracking] All [Serializable] attribute usages eliminated because no reason for them to exist [web] Switch to .NET8/.NET10-only support, nuget packages actualized [web] Project references actual shared libraries of the framework instead of stand-alone outdated packages \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.Localization.Tests/Model/Page.cs b/Extensions/Xtensive.Orm.Localization.Tests/Model/Page.cs index b6c774f609..defa880b00 100644 --- a/Extensions/Xtensive.Orm.Localization.Tests/Model/Page.cs +++ b/Extensions/Xtensive.Orm.Localization.Tests/Model/Page.cs @@ -9,7 +9,6 @@ namespace Xtensive.Orm.Localization.Tests.Model { - [Serializable] [HierarchyRoot] public class Page : Entity, ILocalizable { diff --git a/Extensions/Xtensive.Orm.Localization.Tests/Model/PageLocalization.cs b/Extensions/Xtensive.Orm.Localization.Tests/Model/PageLocalization.cs index a4c51e3c13..d3e116cb67 100644 --- a/Extensions/Xtensive.Orm.Localization.Tests/Model/PageLocalization.cs +++ b/Extensions/Xtensive.Orm.Localization.Tests/Model/PageLocalization.cs @@ -10,7 +10,6 @@ namespace Xtensive.Orm.Localization.Tests.Model { - [Serializable] [HierarchyRoot] public class PageLocalization : Localization { diff --git a/Extensions/Xtensive.Orm.Localization/Configuration/LocalizationConfiguration.cs b/Extensions/Xtensive.Orm.Localization/Configuration/LocalizationConfiguration.cs index a9b4d70be3..766afd1b37 100644 --- a/Extensions/Xtensive.Orm.Localization/Configuration/LocalizationConfiguration.cs +++ b/Extensions/Xtensive.Orm.Localization/Configuration/LocalizationConfiguration.cs @@ -17,8 +17,7 @@ namespace Xtensive.Orm.Localization.Configuration { /// /// The configuration of the localization extension. - /// - [Serializable] + /// public class LocalizationConfiguration : ConfigurationBase { /// diff --git a/Extensions/Xtensive.Orm.Localization/Localization.cs b/Extensions/Xtensive.Orm.Localization/Localization.cs index 8fdbc9757e..6defad62f8 100644 --- a/Extensions/Xtensive.Orm.Localization/Localization.cs +++ b/Extensions/Xtensive.Orm.Localization/Localization.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Localization /// /// Base localization class. /// - [Serializable] public abstract class Localization : Entity { /// @@ -41,7 +40,6 @@ protected Localization(Session session, CultureInfo culture, Entity target) /// Base localization class with typed reference to localizable one. /// /// - [Serializable] [KeyGenerator(KeyGeneratorKind.None)] public abstract class Localization : Localization where T : Entity { diff --git a/Extensions/Xtensive.Orm.Localization/LocalizationPolicy.cs b/Extensions/Xtensive.Orm.Localization/LocalizationPolicy.cs index e56f46984c..f9f0b8986b 100644 --- a/Extensions/Xtensive.Orm.Localization/LocalizationPolicy.cs +++ b/Extensions/Xtensive.Orm.Localization/LocalizationPolicy.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Localization /// /// Localization policy. /// - [Serializable] public enum LocalizationPolicy { /// diff --git a/Extensions/Xtensive.Orm.Operations.Tests/OperationCaptureTest.cs b/Extensions/Xtensive.Orm.Operations.Tests/OperationCaptureTest.cs new file mode 100644 index 0000000000..b05410e8b8 --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations.Tests/OperationCaptureTest.cs @@ -0,0 +1,681 @@ +// Copyright (C) 2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System; +using System.Linq; +using NUnit.Framework; +using Xtensive.Orm.Configuration; +using Xtensive.Core; +using Xtensive.Orm.Tests; +using Xtensive.Orm.Operations.Tests.OperationCapturingTestModel; + + +namespace Xtensive.Orm.Operations.Tests.OperationCapturingTestModel +{ + [HierarchyRoot] + public class Line2d : Entity + { + [Field, Key] + public int Id { get; private set; } + + [Field] + public Point A { get; set; } + + [Field] + public Point B { get; set; } + + public Line2d(Session session, Point a, Point b) + : base(session) + { + A = a; + B = b; + } + } + + public class Point : Structure + { + [Field] + public double X { get; set; } + + [Field] + public double Y { get; set; } + + public Point(Session session, double x, double y) + : base(session) + { + X = x; + Y = y; + } + } + + [HierarchyRoot] + public class Book : Entity + { + [Key, Field] + public int Id { get; private set; } + + [Field(Length = 120)] + public string Title { get; set; } + + [Field] + public int NumberOfPages { get; set; } + + [Field] + [Association(PairTo = nameof(Author.Books))] + public Author Author { get; set; } + + public override string ToString() + { + return Title; + } + + public Book(Session session) + : base(session) + { + } + + public Book(Session session, int numberOfPages) + : base(session) + { + NumberOfPages = numberOfPages; + } + } + + [HierarchyRoot] + public class Author : Entity + { + [Key, Field] + public int Id { get; private set; } + + [Field(Length = 50)] + public string FirstName { get; set; } + + [Field(Length = 50)] + public string LastName { get; set; } + + [Field] + public DateTime? DateOfBirth { get; set; } + + [Field] + public EntitySet Books { get; private set; } + + public override string ToString() + { + return FirstName + " " + LastName; + } + + public Author(Session session, string firstName, string lastName) + : base(session) + { + FirstName = firstName; + LastName = lastName; + } + } +} + +namespace Xtensive.Orm.Operations.Tests +{ + [TestFixture] + public class OperationCaptureTest : AutoBuildTest + { + protected override DomainConfiguration BuildConfiguration() + { + var configuration = base.BuildConfiguration(); + configuration.Types.RegisterCaching(typeof(Book).Assembly, typeof(Book).Namespace); + configuration.Types.Register(typeof(OperationRegistry)); + configuration.Types.Register(typeof(OperationFactory)); + return configuration; + } + + [TearDown] + public void TearDown() + { + using (var session = Domain.OpenSession()) + using (var tx = session.OpenTransaction()) { + using (session.Operations.DisableSystemOperationRegistration()) { + var lines = session.Query.All().ToList(); + session.Remove(lines); + + var books = session.Query.All().ToList(); + var authors = session.Query.All().ToList(); + foreach (var book in books) + book.Author = null; + session.Remove(books); + session.Remove(authors); + } + tx.Complete(); + } + } + + [Test] + [TestCase(OperationLogType.SystemOperationLog)] + [TestCase(OperationLogType.OutermostOperationLog)] + public void EntityCreationCaptureTest(OperationLogType logType) + { + var operationLog = new OperationLog(logType); + using(var session = Domain.OpenSession()) + using (var capturer = OperationCapturer.Attach(session,operationLog)) { + using(var tx = session.OpenTransaction()) { + var book = new Book(session); + tx.Complete(); + } + } + + Assert.That(operationLog.Count, Is.EqualTo(2)); + var operations = operationLog.ToList(); + Assert.That(operations[0], Is.InstanceOf()); + var keyGenerateOperation = (KeyGenerateOperation)operations[0]; + Assert.That(keyGenerateOperation.Key.IsTemporary(Domain), Is.False); + + Assert.That(operations[1], Is.InstanceOf()); + var createEntityOperation = (EntityCreateOperation) operations[1]; + Assert.That(createEntityOperation.TypeName, Is.EqualTo(nameof(Book))); + Assert.That(createEntityOperation.Key, Is.EqualTo(keyGenerateOperation.Key)); + + + operationLog = new OperationLog(logType); + using (var session = Domain.OpenSession()) + using (var capturer = OperationCapturer.Attach(session, operationLog)) { + using (var tx = session.OpenTransaction()) { + var book = new Book(session, 111); + tx.Complete(); + } + } + + Assert.That(operationLog.Count, Is.EqualTo(3)); + operations = operationLog.ToList(); + Assert.That(operations[0], Is.InstanceOf()); + keyGenerateOperation = (KeyGenerateOperation) operations[0]; + Assert.That(keyGenerateOperation.Key.IsTemporary(Domain), Is.False); + + Assert.That(operations[1], Is.InstanceOf()); + createEntityOperation = (EntityCreateOperation) operations[1]; + Assert.That(createEntityOperation.TypeName, Is.EqualTo(nameof(Book))); + Assert.That(createEntityOperation.Key, Is.EqualTo(keyGenerateOperation.Key)); + + Assert.That(operations[2], Is.InstanceOf()); + var numberOfPagesSet = (EntityFieldSetOperation) operations[2]; + Assert.That(numberOfPagesSet.Key, Is.EqualTo(keyGenerateOperation.Key)); + Assert.That(numberOfPagesSet.Field, Is.EqualTo(Domain.Model.Types[nameof(Book)].Fields[nameof(Book.NumberOfPages)])); + Assert.That(numberOfPagesSet.Value, Is.EqualTo(111)); + } + + [Test] + [TestCase(OperationLogType.SystemOperationLog)] + [TestCase(OperationLogType.OutermostOperationLog)] + public void EntityCreationCaptureInClientProfileTest(OperationLogType logType) + { + var operationLog = new OperationLog(logType); + using (var session = Domain.OpenSession(new SessionConfiguration(SessionOptions.ClientProfile))) + using (var capturer = OperationCapturer.Attach(session, operationLog)) { + using (var tx = session.OpenTransaction()) { + var book = new Book(session); + tx.Complete(); + } + } + + Assert.That(operationLog.Count, Is.EqualTo(2)); + var operations = operationLog.ToList(); + Assert.That(operations[0], Is.InstanceOf()); + var keyGenerateOperation = (KeyGenerateOperation) operations[0]; + Assert.That(keyGenerateOperation.Key.IsTemporary(Domain), Is.True); + + Assert.That(operations[1], Is.InstanceOf()); + var createEntityOperation = (EntityCreateOperation) operations[1]; + Assert.That(createEntityOperation.TypeName, Is.EqualTo(nameof(Book))); + Assert.That(createEntityOperation.Key, Is.EqualTo(keyGenerateOperation.Key)); + + operationLog = new OperationLog(logType); + using (var session = Domain.OpenSession(new SessionConfiguration(SessionOptions.ClientProfile))) + using (var capturer = OperationCapturer.Attach(session, operationLog)) { + using (var tx = session.OpenTransaction()) { + var book = new Book(session, 111); + tx.Complete(); + } + } + + Assert.That(operationLog.Count, Is.EqualTo(3)); + operations = operationLog.ToList(); + Assert.That(operations[0], Is.InstanceOf()); + keyGenerateOperation = (KeyGenerateOperation) operations[0]; + Assert.That(keyGenerateOperation.Key.IsTemporary(Domain), Is.True); + + Assert.That(operations[1], Is.InstanceOf()); + createEntityOperation = (EntityCreateOperation) operations[1]; + Assert.That(createEntityOperation.TypeName, Is.EqualTo(nameof(Book))); + Assert.That(createEntityOperation.Key, Is.EqualTo(keyGenerateOperation.Key)); + + Assert.That(operations[2], Is.InstanceOf()); + var numberOfPagesSet = (EntityFieldSetOperation) operations[2]; + Assert.That(numberOfPagesSet.Key, Is.EqualTo(keyGenerateOperation.Key)); + Assert.That(numberOfPagesSet.Field, Is.EqualTo(Domain.Model.Types[nameof(Book)].Fields[nameof(Book.NumberOfPages)])); + Assert.That(numberOfPagesSet.Value, Is.EqualTo(111)); + } + + [Test] + [TestCase(OperationLogType.SystemOperationLog)] + [TestCase(OperationLogType.OutermostOperationLog)] + public void ChangePrimitiveFieldTest(OperationLogType logType) + { + using (var session = Domain.OpenSession()) + using (var tx = session.OpenTransaction()) { + Book book; + Author timelessAuthor; + Author justAuthor; + using (session.Operations.DisableSystemOperationRegistration()) { + book = new Book(session, 100) { Title = "100 white pages" }; + timelessAuthor = new Author(session, "The timeless", "Author") { DateOfBirth = null }; + justAuthor = new Author(session, "The 60s", "Author") { DateOfBirth = new DateTime(1952, 8, 22) }; + } + + var booksOperationLog = new OperationLog(logType); + using (var capturer = OperationCapturer.Attach(session, booksOperationLog)) { + book.NumberOfPages = book.NumberOfPages; + book.Title = book.Title; + } + + Assert.That(booksOperationLog.Count, Is.EqualTo(2)); + var operations = booksOperationLog.ToList(); + + Assert.That(operations[0], Is.InstanceOf()); + var numberOfPagesSet = (EntityFieldSetOperation) operations[0]; + Assert.That(numberOfPagesSet.Key, Is.EqualTo(book.Key)); + Assert.That(numberOfPagesSet.Field, Is.EqualTo(book.TypeInfo.Fields[nameof(Book.NumberOfPages)])); + Assert.That(numberOfPagesSet.Value, Is.EqualTo(100)); + + Assert.That(operations[1], Is.InstanceOf()); + var titleSet = (EntityFieldSetOperation) operations[1]; + Assert.That(titleSet.Key, Is.EqualTo(book.Key)); + Assert.That(titleSet.Field, Is.EqualTo(book.TypeInfo.Fields[nameof(Book.Title)])); + Assert.That(titleSet.Value, Is.EqualTo("100 white pages")); + + booksOperationLog = new OperationLog(logType); + using(var capturer = OperationCapturer.Attach(session, booksOperationLog)) { + book.NumberOfPages = 999; + book.Title = "Not only 100 white pages"; + } + + Assert.That(booksOperationLog.Count, Is.EqualTo(2)); + operations = booksOperationLog.ToList(); + + Assert.That(operations[0], Is.InstanceOf()); + numberOfPagesSet = (EntityFieldSetOperation) operations[0]; + Assert.That(numberOfPagesSet.Key, Is.EqualTo(book.Key)); + Assert.That(numberOfPagesSet.Field, Is.EqualTo(book.TypeInfo.Fields[nameof(Book.NumberOfPages)])); + Assert.That(numberOfPagesSet.Value, Is.EqualTo(999)); + + Assert.That(operations[1], Is.InstanceOf()); + titleSet = (EntityFieldSetOperation) operations[1]; + Assert.That(titleSet.Key, Is.EqualTo(book.Key)); + Assert.That(titleSet.Field, Is.EqualTo(book.TypeInfo.Fields[nameof(Book.Title)])); + Assert.That(titleSet.Value, Is.EqualTo("Not only 100 white pages")); + + + var authorsOperationLog = new OperationLog(logType); + using (var capturer = OperationCapturer.Attach(session, authorsOperationLog)) { + timelessAuthor.DateOfBirth = null; + } + + Assert.That(authorsOperationLog.Count, Is.EqualTo(1)); + operations = authorsOperationLog.ToList(); + + Assert.That(operations[0], Is.InstanceOf()); + var dateOfBirthSet = (EntityFieldSetOperation) operations[0]; + Assert.That(dateOfBirthSet.Key, Is.EqualTo(timelessAuthor.Key)); + Assert.That(dateOfBirthSet.Field, Is.EqualTo(timelessAuthor.TypeInfo.Fields[nameof(Author.DateOfBirth)])); + Assert.That(dateOfBirthSet.Value, Is.Null); + + authorsOperationLog = new OperationLog(logType); + using (var capturer = OperationCapturer.Attach(session, authorsOperationLog)) { + timelessAuthor.DateOfBirth = new DateTime(1961,5,12); + } + + Assert.That(authorsOperationLog.Count, Is.EqualTo(1)); + operations = authorsOperationLog.ToList(); + + Assert.That(operations[0], Is.InstanceOf()); + dateOfBirthSet = (EntityFieldSetOperation) operations[0]; + Assert.That(dateOfBirthSet.Key, Is.EqualTo(timelessAuthor.Key)); + Assert.That(dateOfBirthSet.Field, Is.EqualTo(timelessAuthor.TypeInfo.Fields[nameof(Author.DateOfBirth)])); + Assert.That(dateOfBirthSet.Value, Is.EqualTo(new DateTime(1961, 5, 12))); + + + authorsOperationLog = new OperationLog(logType); + using (var capturer = OperationCapturer.Attach(session, authorsOperationLog)) { + timelessAuthor.DateOfBirth = null; + } + + Assert.That(authorsOperationLog.Count, Is.EqualTo(1)); + operations = authorsOperationLog.ToList(); + + Assert.That(operations[0], Is.InstanceOf()); + dateOfBirthSet = (EntityFieldSetOperation) operations[0]; + Assert.That(dateOfBirthSet.Key, Is.EqualTo(timelessAuthor.Key)); + Assert.That(dateOfBirthSet.Field, Is.EqualTo(timelessAuthor.TypeInfo.Fields[nameof(Author.DateOfBirth)])); + Assert.That(dateOfBirthSet.Value, Is.Null); + + tx.Complete(); + } + } + + [Test] + [TestCase(OperationLogType.SystemOperationLog)] + [TestCase(OperationLogType.OutermostOperationLog)] + public void ChangePrimitiveFieldComplexTest(OperationLogType logType) + { + using (var session = Domain.OpenSession()) + using (var tx = session.OpenTransaction()) { + Book book; + Author timelessAuthor; + using (session.Operations.DisableSystemOperationRegistration()) { + book = new Book(session, 100) { Title = "100 white pages" }; + timelessAuthor = new Author(session, "The timeless", "Author") { DateOfBirth = null }; + } + + var complexOperationLog = new OperationLog(logType); + using (var capturer = OperationCapturer.Attach(session, complexOperationLog)) { + book.NumberOfPages = book.NumberOfPages; + book.Title = book.Title; + + timelessAuthor.DateOfBirth = null; + timelessAuthor.DateOfBirth = new DateTime(1961, 5, 12); + + book.NumberOfPages = 999; + book.Title = "Not only 100 white pages"; + } + + Assert.That(complexOperationLog.Count, Is.EqualTo(6)); + var operations = complexOperationLog.ToList(); + + Assert.That(operations[0], Is.InstanceOf()); + var numberOfPagesSet = (EntityFieldSetOperation) operations[0]; + Assert.That(numberOfPagesSet.Key, Is.EqualTo(book.Key)); + Assert.That(numberOfPagesSet.Field, Is.EqualTo(book.TypeInfo.Fields[nameof(Book.NumberOfPages)])); + Assert.That(numberOfPagesSet.Value, Is.EqualTo(100)); + + Assert.That(operations[1], Is.InstanceOf()); + var titleSet = (EntityFieldSetOperation) operations[1]; + Assert.That(titleSet.Key, Is.EqualTo(book.Key)); + Assert.That(titleSet.Field, Is.EqualTo(book.TypeInfo.Fields[nameof(Book.Title)])); + Assert.That(titleSet.Value, Is.EqualTo("100 white pages")); + + Assert.That(operations[2], Is.InstanceOf()); + var dateOfBirthSet = (EntityFieldSetOperation) operations[2]; + Assert.That(dateOfBirthSet.Key, Is.EqualTo(timelessAuthor.Key)); + Assert.That(dateOfBirthSet.Field, Is.EqualTo(timelessAuthor.TypeInfo.Fields[nameof(Author.DateOfBirth)])); + Assert.That(dateOfBirthSet.Value, Is.Null); + + Assert.That(operations[3], Is.InstanceOf()); + dateOfBirthSet = (EntityFieldSetOperation) operations[3]; + Assert.That(dateOfBirthSet.Key, Is.EqualTo(timelessAuthor.Key)); + Assert.That(dateOfBirthSet.Field, Is.EqualTo(timelessAuthor.TypeInfo.Fields[nameof(Author.DateOfBirth)])); + Assert.That(dateOfBirthSet.Value, Is.EqualTo(new DateTime(1961, 5, 12))); + + Assert.That(operations[4], Is.InstanceOf()); + numberOfPagesSet = (EntityFieldSetOperation) operations[4]; + Assert.That(numberOfPagesSet.Key, Is.EqualTo(book.Key)); + Assert.That(numberOfPagesSet.Field, Is.EqualTo(book.TypeInfo.Fields[nameof(Book.NumberOfPages)])); + Assert.That(numberOfPagesSet.Value, Is.EqualTo(999)); + + Assert.That(operations[5], Is.InstanceOf()); + titleSet = (EntityFieldSetOperation) operations[5]; + Assert.That(titleSet.Key, Is.EqualTo(book.Key)); + Assert.That(titleSet.Field, Is.EqualTo(book.TypeInfo.Fields[nameof(Book.Title)])); + Assert.That(titleSet.Value, Is.EqualTo("Not only 100 white pages")); + + tx.Complete(); + } + } + + [Test] + [TestCase(OperationLogType.SystemOperationLog)] + [TestCase(OperationLogType.OutermostOperationLog)] + public void ChangeReferenceFieldTest(OperationLogType logType) + { + using (var session = Domain.OpenSession()) + using (var tx = session.OpenTransaction()) { + Book book; + Author timelessAuthor; + Author justAuthor; + using (session.Operations.DisableSystemOperationRegistration()) { + book = new Book(session, 100) { Title = "100 white pages" }; + timelessAuthor = new Author(session, "The timeless", "Author") { DateOfBirth = null }; + justAuthor = new Author(session, "The 60s", "Author") { DateOfBirth = new DateTime(1952, 8, 22) }; + } + + var referenceSetLog = new OperationLog(logType); + using(var capturer = OperationCapturer.Attach(session, referenceSetLog)) { + book.Author = null; + } + + Assert.That(referenceSetLog.Count, Is.EqualTo(1)); + var operation = referenceSetLog.First(); + Assert.That(operation, Is.InstanceOf()); + var refSet = (EntityFieldSetOperation) operation; + Assert.That(refSet.Key, Is.EqualTo(book.Key)); + Assert.That(refSet.Field, Is.EqualTo(book.TypeInfo.Fields[nameof(Book.Author)])); + Assert.That(refSet.ValueKey, Is.Null); + + referenceSetLog = new OperationLog(logType); + using (var capturer = OperationCapturer.Attach(session, referenceSetLog)) { + book.Author = timelessAuthor; + } + + Assert.That(referenceSetLog.Count, Is.EqualTo(1)); + operation = referenceSetLog.First(); + Assert.That(operation, Is.InstanceOf()); + refSet = (EntityFieldSetOperation) operation; + Assert.That(refSet.Key, Is.EqualTo(book.Key)); + Assert.That(refSet.Field, Is.EqualTo(book.TypeInfo.Fields[nameof(Book.Author)])); + Assert.That(refSet.ValueKey, Is.EqualTo(timelessAuthor.Key)); + + referenceSetLog = new OperationLog(logType); + using (var capturer = OperationCapturer.Attach(session, referenceSetLog)) { + book.Author = justAuthor; + } + + Assert.That(referenceSetLog.Count, Is.EqualTo(1)); + operation = referenceSetLog.First(); + Assert.That(operation, Is.InstanceOf()); + refSet = (EntityFieldSetOperation) operation; + Assert.That(refSet.Key, Is.EqualTo(book.Key)); + Assert.That(refSet.Field, Is.EqualTo(book.TypeInfo.Fields[nameof(Book.Author)])); + Assert.That(refSet.ValueKey, Is.EqualTo(justAuthor.Key)); + + referenceSetLog = new OperationLog(logType); + using (var capturer = OperationCapturer.Attach(session, referenceSetLog)) { + book.Author = null; + } + + Assert.That(referenceSetLog.Count, Is.EqualTo(1)); + operation = referenceSetLog.First(); + Assert.That(operation, Is.InstanceOf()); + refSet = (EntityFieldSetOperation) operation; + Assert.That(refSet.Key, Is.EqualTo(book.Key)); + Assert.That(refSet.Field, Is.EqualTo(book.TypeInfo.Fields[nameof(Book.Author)])); + Assert.That(refSet.ValueKey, Is.Null); + + tx.Complete(); + } + } + + [Test] + [TestCase(OperationLogType.SystemOperationLog)] + [TestCase(OperationLogType.OutermostOperationLog)] + public void ChangeStructureFieldTest(OperationLogType logType) + { + using (var session = Domain.OpenSession()) + using (var tx = session.OpenTransaction()) { + Line2d line; + using (session.Operations.DisableSystemOperationRegistration()) { + line = new Line2d(session, new Point(session, 1.0, 2.0), new Point(session, 3.0, 6.0)); + } + + var changeStructureObjectLog = new OperationLog(logType); + using(var capturer = OperationCapturer.Attach(session, changeStructureObjectLog)) { + var newA = new Point(session, 1.5, 1.6);// structure owner is null + line.A = newA; + } + + Assert.That(changeStructureObjectLog.Count, Is.EqualTo(1)); + Assert.That(changeStructureObjectLog.First(), Is.InstanceOf()); + + var operation = (EntityFieldSetOperation) changeStructureObjectLog.First(); + var nestedOperations = operation.NestedOperations; + Assert.That(nestedOperations.Count, Is.EqualTo(2)); + Assert.That(nestedOperations[0], Is.InstanceOf()); + var x = (EntityFieldSetOperation)nestedOperations[0]; + Assert.That(x.Value, Is.EqualTo(1.5)); + + Assert.That(nestedOperations[1], Is.InstanceOf()); + var y = (EntityFieldSetOperation) nestedOperations[1]; + Assert.That(y.Value, Is.EqualTo(1.6)); + + tx.Complete(); + } + } + + [Test] + [TestCase(OperationLogType.SystemOperationLog)] + [TestCase(OperationLogType.OutermostOperationLog)] + public void ChangeFieldOfStructureTest(OperationLogType logType) + { + using (var session = Domain.OpenSession()) + using (var tx = session.OpenTransaction()) { + Line2d line; + using (session.Operations.DisableSystemOperationRegistration()) { + line = new Line2d(session, new Point(session, 1.0, 2.0), new Point(session, 3.0, 6.0)); + } + + var changeStructureObjectLog = new OperationLog(logType); + using (var capturer = OperationCapturer.Attach(session, changeStructureObjectLog)) { + var newA = new Point(session, 1.0, 1.0);// structure owner is null + line.A.X = newA.X; + } + + Assert.That(changeStructureObjectLog.Count, Is.EqualTo(1)); + var operation = changeStructureObjectLog.First(); + Assert.That(operation, Is.InstanceOf()); + + tx.Complete(); + } + } + + [Test] + [TestCase(OperationLogType.SystemOperationLog)] + [TestCase(OperationLogType.OutermostOperationLog)] + public void EntitySetAddItemsTest(OperationLogType logType) + { + using (var session = Domain.OpenSession()) + using (var tx = session.OpenTransaction()) { + Book book1, book2; + Author author; + using (session.Operations.DisableSystemOperationRegistration()) { + book1 = new Book(session, 100) { Title = "100 white pages" }; + book2 = new Book(session, 200) { Title = "200 white pages" }; + author = new Author(session, "The 60s", "Author") { DateOfBirth = new DateTime(1952, 8, 22) }; + } + + var entitySetUpdateLog = new OperationLog(logType); + using(var capturer = OperationCapturer.Attach(session, entitySetUpdateLog)) { + _ = author.Books.Add(book1); + _ = author.Books.Add(book2); + } + + Assert.That(entitySetUpdateLog.Count, Is.EqualTo(2)); + var operations = entitySetUpdateLog.ToList(); + + Assert.That(operations[0], Is.InstanceOf()); + var addFirstBook = (EntitySetItemAddOperation) operations[0]; + Assert.That(addFirstBook.Key, Is.EqualTo(author.Key)); + Assert.That(addFirstBook.Field, Is.EqualTo(author.TypeInfo.Fields[nameof(Author.Books)])); + Assert.That(addFirstBook.ItemKey, Is.EqualTo(book1.Key)); + + Assert.That(operations[1], Is.InstanceOf()); + var addSecondBook = (EntitySetItemAddOperation) operations[1]; + Assert.That(addSecondBook.Key, Is.EqualTo(author.Key)); + Assert.That(addSecondBook.Field, Is.EqualTo(author.TypeInfo.Fields[nameof(Author.Books)])); + Assert.That(addSecondBook.ItemKey, Is.EqualTo(book2.Key)); + + tx.Complete(); + } + } + + [Test] + [TestCase(OperationLogType.SystemOperationLog)] + [TestCase(OperationLogType.OutermostOperationLog)] + public void EntitySetDeleteItemsTest(OperationLogType logType) + { + using (var session = Domain.OpenSession()) + using (var tx = session.OpenTransaction()) { + Book book1, book2; + Author author; + using (session.Operations.DisableSystemOperationRegistration()) { + book1 = new Book(session, 100) { Title = "100 white pages" }; + book2 = new Book(session, 200) { Title = "200 white pages" }; + author = new Author(session, "The 60s", "Author") { DateOfBirth = new DateTime(1952, 8, 22) }; + _ = author.Books.Add(book1); + _ = author.Books.Add(book2); + } + + var entitySetUpdateLog = new OperationLog(logType); + using (var capturer = OperationCapturer.Attach(session, entitySetUpdateLog)) { + _ = author.Books.Remove(book1); + _ = author.Books.Remove(book2); + } + + Assert.That(entitySetUpdateLog.Count, Is.EqualTo(2)); + var operations = entitySetUpdateLog.ToList(); + + Assert.That(operations[0], Is.InstanceOf()); + var delFirstBook = (EntitySetItemRemoveOperation) operations[0]; + Assert.That(delFirstBook.Key, Is.EqualTo(author.Key)); + Assert.That(delFirstBook.Field, Is.EqualTo(author.TypeInfo.Fields[nameof(Author.Books)])); + Assert.That(delFirstBook.ItemKey, Is.EqualTo(book1.Key)); + + Assert.That(operations[1], Is.InstanceOf()); + var delSecondBook = (EntitySetItemRemoveOperation) operations[1]; + Assert.That(delSecondBook.Key, Is.EqualTo(author.Key)); + Assert.That(delSecondBook.Field, Is.EqualTo(author.TypeInfo.Fields[nameof(Author.Books)])); + Assert.That(delSecondBook.ItemKey, Is.EqualTo(book2.Key)); + + tx.Complete(); + } + } + + [Test] + [TestCase(OperationLogType.SystemOperationLog)] + [TestCase(OperationLogType.OutermostOperationLog)] + public void EntitySetClearTest(OperationLogType logType) + { + using (var session = Domain.OpenSession()) + using (var tx = session.OpenTransaction()) { + Book book1, book2; + Author author; + using (session.Operations.DisableSystemOperationRegistration()) { + book1 = new Book(session, 100) { Title = "100 white pages" }; + book2 = new Book(session, 200) { Title = "200 white pages" }; + author = new Author(session, "The 60s", "Author") { DateOfBirth = new DateTime(1952, 8, 22) }; + _ = author.Books.Add(book1); + _ = author.Books.Add(book2); + } + + var entitySetUpdateLog = new OperationLog(logType); + using (var capturer = OperationCapturer.Attach(session, entitySetUpdateLog)) { + author.Books.Clear(); + } + + Assert.That(entitySetUpdateLog.Count, Is.EqualTo(1)); + var first = entitySetUpdateLog.First(); + + Assert.That(first, Is.InstanceOf()); + var clear = (EntitySetClearOperation) first; + Assert.That(clear.Key, Is.EqualTo(author.Key)); + Assert.That(clear.Field, Is.EqualTo(author.TypeInfo.Fields[nameof(Author.Books)])); + + tx.Complete(); + } + } + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.Operations.Tests/OperationLogReplay.cs b/Extensions/Xtensive.Orm.Operations.Tests/OperationLogReplay.cs new file mode 100644 index 0000000000..d3e59698cb --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations.Tests/OperationLogReplay.cs @@ -0,0 +1,154 @@ +// Copyright (C) 2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System; +using System.Linq; +using NUnit.Framework; +using Xtensive.Orm.Configuration; +using Xtensive.Core; +using Xtensive.Orm.Tests; +using Xtensive.Orm.Operations.Tests.OperationCapturingTestModel; + +namespace Xtensive.Orm.Operations.Tests +{ + [TestFixture] + public class OperationLogReplay : AutoBuildTest + { + protected override DomainConfiguration BuildConfiguration() + { + var configuration = base.BuildConfiguration(); + configuration.Types.RegisterCaching(typeof(Book).Assembly, typeof(Book).Namespace); + configuration.Types.Register(typeof(OperationRegistry)); + configuration.Types.Register(typeof(OperationFactory)); + return configuration; + } + + [Test] + public void ComplexTest() + { + var operationLog = new OperationLog(OperationLogType.SystemOperationLog); + using (var session = Domain.OpenSession()) + using (var capturer = OperationCapturer.Attach(session, operationLog)) { + using (var tx = session.OpenTransaction()) { + var author1 = new Author(session, "Unknown", "Author"); + author1.DateOfBirth = new DateTime(1985, 6, 12); + + var book11 = new Book(session); + book11.Title = "100 pages about something"; + book11.NumberOfPages = 100; + book11.Author = author1; + + var book12 = new Book(session); + book12.Title = "Even more pages abount something"; + book12.NumberOfPages = 200; + book12.Author = author1; + + var book13 = new Book(session); + book13.Title = "The biggest book ever"; + book13.NumberOfPages = 300; + book13.Author = author1; + + var author2 = new Author(session, "Even Less known", "Author"); + author2.DateOfBirth = new DateTime(1985, 6, 12); + _ = author2.Books.Add(new Book(session) { Title = "100 ways to not live", NumberOfPages = 111 }); + _ = author2.Books.Add(new Book(session) { Title = "50 ways of eating pizza", NumberOfPages = 25 }); + _ = author2.Books.Add(new Book(session) { Title = "Single way to eat banana", NumberOfPages = 3 }); + + _ = author1.Books.Remove(book12); + book12.Remove(); + + var book23 = author2.Books.AsEnumerable().Last(); + _ = author2.Books.Remove(book23); + + book23.Remove(); + + author2.DateOfBirth = null; + + var line1 = new Line2d(session, new Point(session, 0, 1), new Point(session, 0, 10)); + var line2 = new Line2d(session, new Point(session, 0, 1), new Point(session, 0, 10)); + var line3 = new Line2d(session, new Point(session, 0, 1), new Point(session, 0, 10)); + + line1.A.X = 1; + line1.B.Y = 12; + + line2.A = new Point(session, 1, 2); + + //rollback + } + + } + + using (var sessionForReplay = Domain.OpenSession()) + using (var tx = sessionForReplay.OpenTransaction()) { + var booksCount = sessionForReplay.Query.CreateDelayedQuery(q => q.All().Count()); + var authorsCount = sessionForReplay.Query.CreateDelayedQuery(q => q.All().Count()); + var linesCount = sessionForReplay.Query.CreateDelayedQuery(q => q.All().Count()); + + if (booksCount.Value + authorsCount.Value + linesCount.Value > 0) { + throw new NUnit.Framework.InconclusiveException("database should be empty."); + } + + var keys = operationLog.Replay(sessionForReplay); + + tx.Complete(); + } + + using (var sessionAfterReply = Domain.OpenSession()) + using (var tx = sessionAfterReply.OpenTransaction()) { + var booksCount = sessionAfterReply.Query.CreateDelayedQuery(q => q.All().Count()); + var authorsCount = sessionAfterReply.Query.CreateDelayedQuery(q => q.All().Count()); + var linesCount = sessionAfterReply.Query.CreateDelayedQuery(q => q.All().Count()); + + Assert.That(booksCount.Value, Is.EqualTo(4)); + Assert.That(authorsCount.Value, Is.EqualTo(2)); + Assert.That(linesCount.Value, Is.EqualTo(3)); + + var books = sessionAfterReply.Query.All().ToList(); + + var book11 = books.FirstOrDefault(b => b.Title == "100 pages about something"); + Assert.That(book11, Is.Not.Null); + Assert.That(book11.NumberOfPages, Is.EqualTo(100)); + + var book12 = books.FirstOrDefault(b => b.Title == "Even more pages abount something"); + Assert.That(book12, Is.Null); + + var book13 = books.FirstOrDefault(b => b.Title == "The biggest book ever"); + Assert.That(book13, Is.Not.Null); + Assert.That(book13.NumberOfPages, Is.EqualTo(300)); + + + var book21 = books.FirstOrDefault(b => b.Title == "100 ways to not live"); + Assert.That(book21, Is.Null); + + var book22 = books.FirstOrDefault(b => b.Title == "50 ways of eating pizza"); + Assert.That(book22, Is.Not.Null); + Assert.That(book22.NumberOfPages, Is.EqualTo(25)); + + var book23 = books.FirstOrDefault(b => b.Title == "Single way to eat banana"); + Assert.That(book23, Is.Not.Null); + Assert.That(book23.NumberOfPages, Is.EqualTo(3)); + + var authors = sessionAfterReply.Query.All().ToList(); + + var author1 = authors.FirstOrDefault(a => a.FirstName == "Unknown"); + Assert.That(author1, Is.Not.Null); + Assert.That(author1.DateOfBirth, Is.EqualTo(new DateTime(1985, 6, 12))); + Assert.That(author1.Books.Contains(book11), Is.True); + Assert.That(author1.Books.Contains(book13), Is.True); + + + var author2 = authors.FirstOrDefault(a => a.FirstName == "Even Less known"); + Assert.That(author2, Is.Not.Null); + Assert.That(author2.DateOfBirth, Is.Null); + Assert.That(author2.Books.Contains(book22), Is.True); + Assert.That(author2.Books.Contains(book23), Is.True); + + //var lines = sessionAfterReply.Query.All().ToList(); + + tx.Complete(); + } + + } + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.Operations.Tests/OperationOrderTest.cs b/Extensions/Xtensive.Orm.Operations.Tests/OperationOrderTest.cs new file mode 100644 index 0000000000..aaace86c85 --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations.Tests/OperationOrderTest.cs @@ -0,0 +1,260 @@ +// Copyright (C) 2003-2010 Xtensive LLC. +// All rights reserved. +// For conditions of distribution and use, see license. +// Created by: Alex Yakunin +// Created: 2010.08.12 + +using System; +using System.Linq; +using NUnit.Framework; +using Xtensive.Orm.Configuration; +using Xtensive.Orm.Operations; +using Xtensive.Core; +using Xtensive.Orm.Tests; +using Xtensive.Orm.Operations.Tests.OperationOrderTestModel; + +namespace Xtensive.Orm.Operations.Tests.OperationOrderTestModel +{ + [HierarchyRoot] + public class Book : Entity + { + [Key, Field] + public int Id { get; private set; } + + [Field] + public string Title { get; set; } + + [Field] + public EntitySet Referenecs { get; private set; } + + public override string ToString() + { + return Title; + } + + public Book(Session session) + : base(session) + { + } + } +} + +namespace Xtensive.Orm.Operations.Tests +{ + [TestFixture] + public class OperationOrderTest : AutoBuildTest + { + private static bool disabled = false; + private static object expectedTarget = null; + private static string[] expectedOperations = null; + private static int lastOperationIndex = -1; + private static int lastOperationState = -2; + + protected override DomainConfiguration BuildConfiguration() + { + var configuration = base.BuildConfiguration(); + configuration.Types.RegisterCaching(typeof(Book).Assembly, typeof(Book).Namespace); + configuration.Types.Register(typeof(OperationRegistry)); + configuration.Types.Register(typeof(OperationFactory)); + return configuration; + } + + [Test] + public void StandardTest() + { + Assert.That(Domain.Services.Get(), Is.Not.Null); + + using (var session = Domain.OpenSession()) { + Assert.That(session.Operations, Is.InstanceOf()); + BindEvents(session); + using (var tx = session.OpenTransaction()) { + Book b; + using (DisableEvents()) { + b = new Book(session); + } + + AssertOperations(b, new[] { "Entity.SetValue" }); + b.Title = "Book"; + + AssertOperations(b.Referenecs, new[] { "EntitySet.AddItem" }); + _ = b.Referenecs.Add(b); + + AssertOperations(b.Referenecs, new[] { "EntitySet.RemoveItem" }); + _ = b.Referenecs.Remove(b); + + AssertOperations(b.Referenecs, new[] { "EntitySet.Clear" }); + b.Referenecs.Clear(); + + AssertOperations(b, new[] { "Entity.Remove" }); + b.Remove(); + + // tx.Complete(); + } + } + } + + #region Helper methods + + private static void BindEvents(Session session) + { + var operations = session.Operations; + operations.OutermostOperationStarting += (s, ea) => InOperation(s, ea); + operations.NestedOperationStarting += (s, ea) => InOperation(s, ea); + + var events = session.Events; + + events.EntityFieldValueSetting += (s, ea) => BeforeOperation(ea.Entity, "Entity.SetValue"); + events.EntityFieldValueSet += (s, ea) => AfterOperation(ea.Entity, "Entity.SetValue"); + events.EntityFieldValueSetCompleted += (s, ea) => AfterOperation(ea.Entity, "Entity.SetValue"); + + events.EntityRemoving += (s, ea) => BeforeOperation(ea.Entity, "Entity.Remove"); + events.EntityRemove += (s, ea) => AfterOperation(ea.Entity, "Entity.Remove"); + events.EntityRemoveCompleted += (s, ea) => AfterOperation(ea.Entity, "Entity.Remove"); + + events.EntitySetItemAdding += (s, ea) => BeforeOperation(ea.EntitySet, "EntitySet.AddItem"); + events.EntitySetItemAdd += (s, ea) => AfterOperation(ea.EntitySet, "EntitySet.AddItem"); + events.EntitySetItemAddCompleted += (s, ea) => AfterOperation(ea.EntitySet, "EntitySet.AddItem"); + + events.EntitySetItemRemoving += (s, ea) => BeforeOperation(ea.EntitySet, "EntitySet.RemoveItem"); + events.EntitySetItemRemove += (s, ea) => AfterOperation(ea.EntitySet, "EntitySet.RemoveItem"); + events.EntitySetItemRemoveCompleted += (s, ea) => AfterOperation(ea.EntitySet, "EntitySet.RemoveItem"); + + events.EntitySetClearing += (s, ea) => BeforeOperation(ea.EntitySet, "EntitySet.Clear"); + events.EntitySetClear += (s, ea) => AfterOperation(ea.EntitySet, "EntitySet.Clear"); + events.EntitySetClearCompleted += (s, ea) => AfterOperation(ea.EntitySet, "EntitySet.Clear"); + } + + private static void InOperation(object sender, OperationEventArgs ea) + { + if (disabled) + return; + + object target = null; + if (ea.Operation is EntitySetOperation) { + var eso = (EntitySetOperation) ea.Operation; + var entity = Session.Demand().Query.Single(eso.Key); + target = entity.GetProperty(eso.Field.Name); + } + else if (ea.Operation is EntityOperation) { + var eo = (EntityOperation) ea.Operation; + target = Session.Demand().Query.Single(eo.Key); + } + else if (ea.Operation is EntitiesRemoveOperation) { + var ero = (EntitiesRemoveOperation) ea.Operation; + target = Session.Demand().Query.Single(ero.Keys.Single()); + } + else + return; + + if (target != expectedTarget) + return; + if ((ea.Operation.Type & OperationType.System) != OperationType.System) + return; + + string prefix = null; + if (target is Entity) + prefix = "Entity"; + else if (target is EntitySetBase) + prefix = "EntitySet"; + else + return; + + string suffix = null; + if (ea.Operation.GetType() == typeof(EntityFieldSetOperation)) + suffix = "SetValue"; + else if (ea.Operation.GetType() == typeof(EntitiesRemoveOperation)) + suffix = "Remove"; + + else if (ea.Operation.GetType() == typeof(EntitySetItemAddOperation)) + suffix = "AddItem"; + else if (ea.Operation.GetType() == typeof(EntitySetItemRemoveOperation)) + suffix = "RemoveItem"; + else if (ea.Operation.GetType() == typeof(EntitySetClearOperation)) + suffix = "Clear"; + else + return; + + string operation = $"{prefix}.{suffix}"; + InOperation(target, operation); + } + + public static IDisposable DisableEvents() + { + var oldDisabled = disabled; + disabled = true; + return new Disposable(disposing => disabled = oldDisabled); + } + + public static void AssertOperations(object target, string[] operations) + { + expectedTarget = target; + expectedOperations = operations; + lastOperationIndex = -1; + lastOperationState = -2; + } + + public static void BeforeOperation(object target, string operation) + { + if (disabled) + return; + if (target != expectedTarget) + return; + + Console.WriteLine($"Before '{operation}'"); + var lastOperation = (lastOperationIndex < 0) ? null : expectedOperations[lastOperationIndex]; + if (lastOperation != operation) { + if (lastOperationState != -2 && lastOperationState != 1) + Assert.Fail("Invalid notification order: no 'after' event."); + lastOperationIndex++; + lastOperation = expectedOperations[lastOperationIndex]; + if (lastOperation != operation) + Assert.Fail($"Invalid operation order: expected operation is '{lastOperation}'."); + lastOperationState = -1; + } + else { + if (lastOperationState >= 0) + Assert.Fail("Invalid notification order: 'before' event is unexpected here."); + } + } + + public static void InOperation(object target, string operation) + { + if (disabled) + return; + if (target != expectedTarget) + return; + + Console.WriteLine($"In '{operation}'"); + var lastOperation = (lastOperationIndex < 0) ? null : expectedOperations[lastOperationIndex]; + if (lastOperation != operation) + Assert.Fail("Invalid notification order: no 'before' event."); + else { + if (lastOperationState == -1) + lastOperationState = 0; + if (lastOperationState != 0) + Assert.Fail("Invalid notification order: 'in' event is unexpected here."); + } + } + + public static void AfterOperation(object target, string operation) + { + if (disabled) + return; + if (target != expectedTarget) + return; + + Console.WriteLine($"After '{operation}'"); + var lastOperation = (lastOperationIndex < 0) ? null : expectedOperations[lastOperationIndex]; + if (lastOperation != operation) + Assert.Fail("Invalid notification order: no 'before' event."); + else { + if (lastOperationState == 0) + lastOperationState = 1; + if (lastOperationState != 1) + Assert.Fail("Invalid notification order: 'after' event is unexpected here."); + } + } + + #endregion + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.Operations.Tests/SerializationTest.cs b/Extensions/Xtensive.Orm.Operations.Tests/SerializationTest.cs new file mode 100644 index 0000000000..73d75d2756 --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations.Tests/SerializationTest.cs @@ -0,0 +1,553 @@ +// Copyright (C) 2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using NUnit.Framework; +using Xtensive.Orm.Configuration; +using Xtensive.Orm.Tests; +using Xtensive.Orm.Operations.Serialization.Json; +using Xtensive.Orm.Operations.Tests.SerializationTestModel; + + +namespace Xtensive.Orm.Operations.Tests.SerializationTestModel +{ + [HierarchyRoot] + public class IntKeyDummy : Entity + { + [Field, Key] + public int Id { get; private set; } + + [Field] + public DateTime Value { get; set; } + + [Field] + public DummyReference Reference { get; set; } + + [Field] + public EntitySet Collection { get; private set; } + + [Field] + public DummyStructure DummyStructure { get; set; } + + public IntKeyDummy(Session session) + : base(session) + { + } + } + + public class DummyStructure : Structure + { + [Field] + public int Index { get; set; } + + [Field] + public string Value { get; set; } + + public DummyStructure(Session session) + : base(session) + { + } + } + + [HierarchyRoot] + public class DummyReference : Entity + { + [Field, Key] + public int Id { get; private set; } + + public DummyReference(Session session) + : base(session) + { + } + } + + [HierarchyRoot] + public class DummyEsItem : Entity + { + [Field, Key] + public int Id { get; private set; } + + [Field] + [Association(PairTo = nameof(IntKeyDummy.Collection))] + public IntKeyDummy Dummy { get; set; } + + public DummyEsItem(Session session) + : base(session) + { + } + } + + [HierarchyRoot] + [KeyGenerator(KeyGeneratorKind.None)] + public class Complex2FieldKeyDummy : Entity + { + [Field, Key(0)] + public int Id0 { get; private set; } + + [Field, Key(1)] + public int Id1 { get; private set; } + + public Complex2FieldKeyDummy(Session session, int id0, int id1) + : base(session, id0, id1) + { + } + } + + [HierarchyRoot] + [KeyGenerator(KeyGeneratorKind.None)] + public class Complex3FieldKeyDummy : Entity + { + [Field, Key(0)] + public int Id0 { get; private set; } + + [Field, Key(1)] + public int Id1 { get; private set; } + + [Field, Key(2)] + public int Id2 { get; private set; } + + public Complex3FieldKeyDummy(Session session, int id0, int id1, int id2) + : base(session, id0, id1, id2) + { + } + } + + [HierarchyRoot] + [KeyGenerator(KeyGeneratorKind.None)] + public class Complex5FieldKeyDummy : Entity + { + [Field, Key(0)] + public int Id0 { get; private set; } + + [Field, Key(1)] + public int Id1 { get; private set; } + + [Field, Key(2)] + public int Id2 { get; private set; } + + [Field, Key(3)] + public int Id3 { get; private set; } + + [Field, Key(4)] + public int Id4 { get; private set; } + + public Complex5FieldKeyDummy(Session session, int id0, int id1, int id2, int id3, int id4) + : base(session, id0, id1, id2, id3, id4) + { + } + } +} + +namespace Xtensive.Orm.Operations.Tests +{ + public class SerializationTest : AutoBuildTest + { + protected override DomainConfiguration BuildConfiguration() + { + var configuration = base.BuildConfiguration(); + configuration.Types.RegisterCaching(typeof(IntKeyDummy).Assembly, typeof(IntKeyDummy).Namespace); + configuration.Types.Register(typeof(OperationRegistry)); + configuration.Types.Register(typeof(OperationFactory)); + return configuration; + } + + [Test] + public void KeyGenerateOperationTest() + { + var jsonSerializerOptions = CreateJsonSettings(); + + var key1 = Key.Create(Domain, typeof(IntKeyDummy), 111); + var key2 = Key.Create(Domain, typeof(Complex2FieldKeyDummy), 111, 222); + var key3 = Key.Create(Domain, typeof(Complex3FieldKeyDummy), 111, 222, 333); + var key5 = Key.Create(Domain, typeof(Complex5FieldKeyDummy), 111, 222, 333, 444, 555); + + var operation = new KeyGenerateOperation(key1); + var clonedOperation = Cloner.CloneViaJsonSerialization(operation, jsonSerializerOptions); + Assert.That(clonedOperation.Key, Is.EqualTo(operation.Key)); + Assert.That(clonedOperation.Type, Is.EqualTo(operation.Type)); + Assert.That(clonedOperation.IdentifiedEntities, Is.Empty); + Assert.That(clonedOperation.PrecedingOperations, Is.Empty); + Assert.That(clonedOperation.FollowingOperations, Is.Empty); + Assert.That(clonedOperation.UndoOperations, Is.Empty); + + operation = new KeyGenerateOperation(key2); + clonedOperation = Cloner.CloneViaJsonSerialization(operation, jsonSerializerOptions); + Assert.That(clonedOperation.Key, Is.EqualTo(operation.Key)); + Assert.That(clonedOperation.Type, Is.EqualTo(operation.Type)); + Assert.That(clonedOperation.IdentifiedEntities, Is.Empty); + Assert.That(clonedOperation.PrecedingOperations, Is.Empty); + Assert.That(clonedOperation.FollowingOperations, Is.Empty); + Assert.That(clonedOperation.UndoOperations, Is.Empty); + + operation = new KeyGenerateOperation(key3); + clonedOperation = Cloner.CloneViaJsonSerialization(operation, jsonSerializerOptions); + Assert.That(clonedOperation.Key, Is.EqualTo(operation.Key)); + Assert.That(clonedOperation.Type, Is.EqualTo(operation.Type)); + Assert.That(clonedOperation.IdentifiedEntities, Is.Empty); + Assert.That(clonedOperation.PrecedingOperations, Is.Empty); + Assert.That(clonedOperation.FollowingOperations, Is.Empty); + Assert.That(clonedOperation.UndoOperations, Is.Empty); + + operation = new KeyGenerateOperation(key5); + clonedOperation = Cloner.CloneViaJsonSerialization(operation, jsonSerializerOptions); + Assert.That(clonedOperation.Key, Is.EqualTo(operation.Key)); + Assert.That(clonedOperation.Type, Is.EqualTo(operation.Type)); + Assert.That(clonedOperation.IdentifiedEntities, Is.Empty); + Assert.That(clonedOperation.PrecedingOperations, Is.Empty); + Assert.That(clonedOperation.FollowingOperations, Is.Empty); + Assert.That(clonedOperation.UndoOperations, Is.Empty); + } + + [Test] + public void EntityCreateOperationTest() + { + var jsonSerializerOptions = CreateJsonSettings(); + + var key1 = Key.Create(Domain, typeof(IntKeyDummy), 111); + var key2 = Key.Create(Domain, typeof(Complex2FieldKeyDummy), 111, 222); + var key3 = Key.Create(Domain, typeof(Complex3FieldKeyDummy), 111, 222, 333); + var key5 = Key.Create(Domain, typeof(Complex5FieldKeyDummy), 111, 222, 333, 444, 555); + + var operation = new EntityCreateOperation(key1); + var clonedOperation = Cloner.CloneViaJsonSerialization(operation, jsonSerializerOptions); + Assert.That(clonedOperation.Key, Is.EqualTo(operation.Key)); + Assert.That(clonedOperation.Type, Is.EqualTo(operation.Type)); + Assert.That(clonedOperation.IdentifiedEntities, Is.Empty); + Assert.That(clonedOperation.PrecedingOperations, Is.Empty); + Assert.That(clonedOperation.FollowingOperations, Is.Empty); + Assert.That(clonedOperation.UndoOperations, Is.Empty); + + operation = new EntityCreateOperation(key2); + clonedOperation = Cloner.CloneViaJsonSerialization(operation, jsonSerializerOptions); + Assert.That(clonedOperation.Key, Is.EqualTo(operation.Key)); + Assert.That(clonedOperation.Type, Is.EqualTo(operation.Type)); + Assert.That(clonedOperation.IdentifiedEntities, Is.Empty); + Assert.That(clonedOperation.PrecedingOperations, Is.Empty); + Assert.That(clonedOperation.FollowingOperations, Is.Empty); + Assert.That(clonedOperation.UndoOperations, Is.Empty); + + operation = new EntityCreateOperation(key3); + clonedOperation = Cloner.CloneViaJsonSerialization(operation, jsonSerializerOptions); + Assert.That(clonedOperation.Key, Is.EqualTo(operation.Key)); + Assert.That(clonedOperation.Type, Is.EqualTo(operation.Type)); + Assert.That(clonedOperation.IdentifiedEntities, Is.Empty); + Assert.That(clonedOperation.PrecedingOperations, Is.Empty); + Assert.That(clonedOperation.FollowingOperations, Is.Empty); + Assert.That(clonedOperation.UndoOperations, Is.Empty); + + operation = new EntityCreateOperation(key5); + clonedOperation = Cloner.CloneViaJsonSerialization(operation, jsonSerializerOptions); + Assert.That(clonedOperation.Key, Is.EqualTo(operation.Key)); + Assert.That(clonedOperation.Type, Is.EqualTo(operation.Type)); + Assert.That(clonedOperation.IdentifiedEntities, Is.Empty); + Assert.That(clonedOperation.PrecedingOperations, Is.Empty); + Assert.That(clonedOperation.FollowingOperations, Is.Empty); + Assert.That(clonedOperation.UndoOperations, Is.Empty); + } + + [Test] + public void EntityInitializeOperationTest() + { + var jsonSerializerOptions = CreateJsonSettings(); + + var key1 = Key.Create(Domain, typeof(IntKeyDummy), 111); + var key2 = Key.Create(Domain, typeof(Complex2FieldKeyDummy), 111, 222); + var key3 = Key.Create(Domain, typeof(Complex3FieldKeyDummy), 111, 222, 333); + var key5 = Key.Create(Domain, typeof(Complex5FieldKeyDummy), 111, 222, 333, 444, 555); + + var operation = new EntityInitializeOperation(key1); + var clonedOperation = Cloner.CloneViaJsonSerialization(operation, jsonSerializerOptions); + Assert.That(clonedOperation.Key, Is.EqualTo(operation.Key)); + Assert.That(clonedOperation.Type, Is.EqualTo(operation.Type)); + Assert.That(clonedOperation.IdentifiedEntities, Is.Empty); + Assert.That(clonedOperation.PrecedingOperations, Is.Empty); + Assert.That(clonedOperation.FollowingOperations, Is.Empty); + Assert.That(clonedOperation.UndoOperations, Is.Empty); + + operation = new EntityInitializeOperation(key2); + clonedOperation = Cloner.CloneViaJsonSerialization(operation, jsonSerializerOptions); + Assert.That(clonedOperation.Key, Is.EqualTo(operation.Key)); + Assert.That(clonedOperation.Type, Is.EqualTo(operation.Type)); + Assert.That(clonedOperation.IdentifiedEntities, Is.Empty); + Assert.That(clonedOperation.PrecedingOperations, Is.Empty); + Assert.That(clonedOperation.FollowingOperations, Is.Empty); + Assert.That(clonedOperation.UndoOperations, Is.Empty); + + operation = new EntityInitializeOperation(key3); + clonedOperation = Cloner.CloneViaJsonSerialization(operation, jsonSerializerOptions); + Assert.That(clonedOperation.Key, Is.EqualTo(operation.Key)); + Assert.That(clonedOperation.Type, Is.EqualTo(operation.Type)); + Assert.That(clonedOperation.IdentifiedEntities, Is.Empty); + Assert.That(clonedOperation.PrecedingOperations, Is.Empty); + Assert.That(clonedOperation.FollowingOperations, Is.Empty); + Assert.That(clonedOperation.UndoOperations, Is.Empty); + + operation = new EntityInitializeOperation(key5); + clonedOperation = Cloner.CloneViaJsonSerialization(operation, jsonSerializerOptions); + Assert.That(clonedOperation.Key, Is.EqualTo(operation.Key)); + Assert.That(clonedOperation.Type, Is.EqualTo(operation.Type)); + Assert.That(clonedOperation.IdentifiedEntities, Is.Empty); + Assert.That(clonedOperation.PrecedingOperations, Is.Empty); + Assert.That(clonedOperation.FollowingOperations, Is.Empty); + Assert.That(clonedOperation.UndoOperations, Is.Empty); + } + + [Test] + public void EntitesRemoveOperationTest() + { + var jsonSerializerOptions = CreateJsonSettings(); + + var key1 = Key.Create(Domain, typeof(IntKeyDummy), 111); + var key2 = Key.Create(Domain, typeof(Complex2FieldKeyDummy), 111, 222); + var key3 = Key.Create(Domain, typeof(Complex3FieldKeyDummy), 111, 222, 333); + var key5 = Key.Create(Domain, typeof(Complex5FieldKeyDummy), 111, 222, 333, 444, 555); + + var operation = new EntitiesRemoveOperation(key1); + var clonedOperation = Cloner.CloneViaJsonSerialization(operation, jsonSerializerOptions); + Assert.That(clonedOperation.Keys.SequenceEqual(operation.Keys), Is.True); + Assert.That(clonedOperation.Type, Is.EqualTo(operation.Type)); + Assert.That(clonedOperation.IdentifiedEntities, Is.Empty); + Assert.That(clonedOperation.PrecedingOperations, Is.Empty); + Assert.That(clonedOperation.FollowingOperations, Is.Empty); + Assert.That(clonedOperation.UndoOperations, Is.Empty); + + operation = new EntitiesRemoveOperation(key2); + clonedOperation = Cloner.CloneViaJsonSerialization(operation, jsonSerializerOptions); + Assert.That(clonedOperation.Keys.SequenceEqual(operation.Keys), Is.True); + Assert.That(clonedOperation.Type, Is.EqualTo(operation.Type)); + Assert.That(clonedOperation.IdentifiedEntities, Is.Empty); + Assert.That(clonedOperation.PrecedingOperations, Is.Empty); + Assert.That(clonedOperation.FollowingOperations, Is.Empty); + Assert.That(clonedOperation.UndoOperations, Is.Empty); + + operation = new EntitiesRemoveOperation(key3); + clonedOperation = Cloner.CloneViaJsonSerialization(operation, jsonSerializerOptions); + Assert.That(clonedOperation.Keys.SequenceEqual(operation.Keys), Is.True); + Assert.That(clonedOperation.Type, Is.EqualTo(operation.Type)); + Assert.That(clonedOperation.IdentifiedEntities, Is.Empty); + Assert.That(clonedOperation.PrecedingOperations, Is.Empty); + Assert.That(clonedOperation.FollowingOperations, Is.Empty); + Assert.That(clonedOperation.UndoOperations, Is.Empty); + + operation = new EntitiesRemoveOperation(key5); + clonedOperation = Cloner.CloneViaJsonSerialization(operation, jsonSerializerOptions); + Assert.That(clonedOperation.Keys.SequenceEqual(operation.Keys), Is.True); + Assert.That(clonedOperation.Type, Is.EqualTo(operation.Type)); + Assert.That(clonedOperation.IdentifiedEntities, Is.Empty); + Assert.That(clonedOperation.PrecedingOperations, Is.Empty); + Assert.That(clonedOperation.FollowingOperations, Is.Empty); + Assert.That(clonedOperation.UndoOperations, Is.Empty); + + operation = new EntitiesRemoveOperation(new List { key5, key3, key2, key1 }.AsReadOnly()); + clonedOperation = Cloner.CloneViaJsonSerialization(operation, jsonSerializerOptions); + Assert.That(clonedOperation.Keys.SequenceEqual(operation.Keys), Is.True); + Assert.That(clonedOperation.Type, Is.EqualTo(operation.Type)); + Assert.That(clonedOperation.IdentifiedEntities, Is.Empty); + Assert.That(clonedOperation.PrecedingOperations, Is.Empty); + Assert.That(clonedOperation.FollowingOperations, Is.Empty); + Assert.That(clonedOperation.UndoOperations, Is.Empty); + } + + [Test] + public void EntityFieldSetOperationTest() + { + var jsonSerializerOptions = CreateJsonSettings(); + + var dummyType = typeof(IntKeyDummy); + var dummyTypeInfo = Domain.Model.Types[dummyType]; + + var key = Key.Create(Domain, typeof(IntKeyDummy), 111); + var primitiveField = dummyTypeInfo.Fields[nameof(IntKeyDummy.Value)]; + var referenceField = dummyTypeInfo.Fields[nameof(IntKeyDummy.Reference)]; + var structureField = dummyTypeInfo.Fields[nameof(IntKeyDummy.DummyStructure)]; + + var primitiveFieldOperation = new EntityFieldSetOperation(key, primitiveField, new DateTime(2012, 08, 12)); + var cPrimitiveFieldOperation = Cloner.CloneViaJsonSerialization(primitiveFieldOperation, jsonSerializerOptions); + Assert.That(cPrimitiveFieldOperation.Key, Is.EqualTo(primitiveFieldOperation.Key)); + Assert.That(cPrimitiveFieldOperation.Field, Is.EqualTo(primitiveFieldOperation.Field)); + Assert.That(cPrimitiveFieldOperation.IsStructure, Is.EqualTo(primitiveFieldOperation.IsStructure)); + Assert.That(cPrimitiveFieldOperation.IsReference, Is.EqualTo(primitiveFieldOperation.IsReference)); + Assert.That(cPrimitiveFieldOperation.ValueKey, Is.Null); + Assert.That(cPrimitiveFieldOperation.Value, Is.Not.Null); + Assert.That(cPrimitiveFieldOperation.Value, Is.EqualTo(primitiveFieldOperation.Value)); + Assert.That(cPrimitiveFieldOperation.NestedOperations, Is.Empty); + Assert.That(cPrimitiveFieldOperation.Type, Is.EqualTo(primitiveFieldOperation.Type)); + Assert.That(cPrimitiveFieldOperation.IdentifiedEntities, Is.Empty); + Assert.That(cPrimitiveFieldOperation.PrecedingOperations, Is.Empty); + Assert.That(cPrimitiveFieldOperation.FollowingOperations, Is.Empty); + Assert.That(cPrimitiveFieldOperation.UndoOperations, Is.Empty); + + + var referenceKey = Key.Create(Domain, typeof(DummyReference), 321); + var referenceFieldOperation = new EntityFieldSetOperation(key, referenceField, referenceKey); + var cReferenceFieldOperation = Cloner.CloneViaJsonSerialization(referenceFieldOperation, jsonSerializerOptions); + Assert.That(cReferenceFieldOperation.Key, Is.EqualTo(referenceFieldOperation.Key)); + Assert.That(cReferenceFieldOperation.Field, Is.EqualTo(referenceFieldOperation.Field)); + Assert.That(cReferenceFieldOperation.IsStructure, Is.EqualTo(referenceFieldOperation.IsStructure)); + Assert.That(cReferenceFieldOperation.IsReference, Is.EqualTo(referenceFieldOperation.IsReference)); + Assert.That(cReferenceFieldOperation.ValueKey, Is.Not.Null); + Assert.That(cReferenceFieldOperation.ValueKey, Is.EqualTo(referenceFieldOperation.ValueKey)); + Assert.That(cReferenceFieldOperation.Value, Is.Null); + Assert.That(cReferenceFieldOperation.NestedOperations, Is.Empty); + Assert.That(cReferenceFieldOperation.Type, Is.EqualTo(referenceFieldOperation.Type)); + Assert.That(cReferenceFieldOperation.IdentifiedEntities, Is.Empty); + Assert.That(cReferenceFieldOperation.PrecedingOperations, Is.Empty); + Assert.That(cReferenceFieldOperation.FollowingOperations, Is.Empty); + Assert.That(cReferenceFieldOperation.UndoOperations, Is.Empty); + + + using (var session = Domain.OpenSession()) + using (var tx = session.OpenTransaction()) { + + var dummyStructure = new DummyStructure(session) {Index = 2, Value = "abc" }; + + var structureFieldSetOperation = new EntityFieldSetOperation(key, structureField, dummyStructure); + var cStructureFieldSetOperation = Cloner.CloneViaJsonSerialization(structureFieldSetOperation, jsonSerializerOptions); + + Assert.That(cStructureFieldSetOperation.Key, Is.EqualTo(structureFieldSetOperation.Key)); + Assert.That(cStructureFieldSetOperation.Field, Is.EqualTo(structureFieldSetOperation.Field)); + Assert.That(cStructureFieldSetOperation.IsStructure, Is.EqualTo(structureFieldSetOperation.IsStructure)); + Assert.That(cStructureFieldSetOperation.IsReference, Is.EqualTo(structureFieldSetOperation.IsReference)); + Assert.That(cStructureFieldSetOperation.ValueKey, Is.Null); + Assert.That(cStructureFieldSetOperation.Value, Is.Null); + Assert.That(cStructureFieldSetOperation.NestedOperations, Is.Not.Empty); + Assert.That(cStructureFieldSetOperation.NestedOperations.Count, Is.EqualTo(2)); + + var nestedOp1 = (EntityFieldSetOperation)cStructureFieldSetOperation.NestedOperations[0]; + Assert.That(nestedOp1, Is.Not.Null); + Assert.That(nestedOp1.Key, Is.EqualTo(structureFieldSetOperation.Key)); + Assert.That(nestedOp1.Field, Is.EqualTo(dummyTypeInfo.Fields[nameof(DummyStructure) + "." + nameof(DummyStructure.Index)])); + Assert.That(nestedOp1.IsStructure, Is.False); + Assert.That(nestedOp1.IsReference, Is.False); + Assert.That(nestedOp1.ValueKey, Is.Null); + Assert.That(nestedOp1.Value, Is.Not.Null); + Assert.That(nestedOp1.Value, Is.EqualTo(2)); + Assert.That(nestedOp1.NestedOperations, Is.Empty); + Assert.That(nestedOp1.IdentifiedEntities, Is.Empty); + Assert.That(nestedOp1.PrecedingOperations, Is.Empty); + Assert.That(nestedOp1.FollowingOperations, Is.Empty); + Assert.That(nestedOp1.UndoOperations, Is.Empty); + + var nestedOp2 = (EntityFieldSetOperation) cStructureFieldSetOperation.NestedOperations[1]; + Assert.That(nestedOp2, Is.Not.Null); + Assert.That(nestedOp2.Key, Is.EqualTo(structureFieldSetOperation.Key)); + Assert.That(nestedOp2.Field, Is.EqualTo(dummyTypeInfo.Fields[nameof(DummyStructure) + "." + nameof(DummyStructure.Value)])); + Assert.That(nestedOp2.IsStructure, Is.False); + Assert.That(nestedOp2.IsReference, Is.False); + Assert.That(nestedOp2.ValueKey, Is.Null); + Assert.That(nestedOp2.Value, Is.Not.Null); + Assert.That(nestedOp2.Value, Is.EqualTo("abc")); + Assert.That(nestedOp2.NestedOperations, Is.Empty); + Assert.That(nestedOp2.IdentifiedEntities, Is.Empty); + Assert.That(nestedOp2.PrecedingOperations, Is.Empty); + Assert.That(nestedOp2.FollowingOperations, Is.Empty); + Assert.That(nestedOp2.UndoOperations, Is.Empty); + + Assert.That(cStructureFieldSetOperation.Type, Is.EqualTo(structureFieldSetOperation.Type)); + Assert.That(cStructureFieldSetOperation.IdentifiedEntities, Is.Empty); + Assert.That(cStructureFieldSetOperation.PrecedingOperations, Is.Empty); + Assert.That(cStructureFieldSetOperation.FollowingOperations, Is.Empty); + Assert.That(cStructureFieldSetOperation.UndoOperations, Is.Empty); + } + } + + [Test] + public void EntitySetClearOperationTest() + { + var jsonSerializerOptions = CreateJsonSettings(); + + var dummyType = typeof(IntKeyDummy); + var dummyTypeInfo = Domain.Model.Types[dummyType]; + + var key = Key.Create(Domain, typeof(IntKeyDummy), 111); + var entitySetField = dummyTypeInfo.Fields[nameof(IntKeyDummy.Collection)]; + + var operation = new EntitySetClearOperation(key, entitySetField); + var clonedOperation = Cloner.CloneViaJsonSerialization(operation, jsonSerializerOptions); + Assert.That(clonedOperation.Key, Is.EqualTo(operation.Key)); + Assert.That(clonedOperation.Field, Is.EqualTo(operation.Field)); + Assert.That(clonedOperation.Type, Is.EqualTo(operation.Type)); + Assert.That(clonedOperation.IdentifiedEntities, Is.Empty); + Assert.That(clonedOperation.PrecedingOperations, Is.Empty); + Assert.That(clonedOperation.FollowingOperations, Is.Empty); + Assert.That(clonedOperation.UndoOperations, Is.Empty); + } + + [Test] + public void EntitySetItemAddOperationTest() + { + var jsonSerializerOptions = CreateJsonSettings(); + + var dummyType = typeof(IntKeyDummy); + var dummyTypeInfo = Domain.Model.Types[dummyType]; + + var key = Key.Create(Domain, typeof(IntKeyDummy), 111); + var entitySetField = dummyTypeInfo.Fields[nameof(IntKeyDummy.Collection)]; + var itemKey = Key.Create(Domain, typeof(DummyEsItem), 987); + + var operation = new EntitySetItemAddOperation(key, entitySetField, itemKey); + var clonedOperation = Cloner.CloneViaJsonSerialization(operation, jsonSerializerOptions); + Assert.That(clonedOperation.Key, Is.EqualTo(operation.Key)); + Assert.That(clonedOperation.Field, Is.EqualTo(operation.Field)); + Assert.That(clonedOperation.ItemKey, Is.EqualTo(operation.ItemKey)); + Assert.That(clonedOperation.Type, Is.EqualTo(operation.Type)); + Assert.That(clonedOperation.IdentifiedEntities, Is.Empty); + Assert.That(clonedOperation.PrecedingOperations, Is.Empty); + Assert.That(clonedOperation.FollowingOperations, Is.Empty); + Assert.That(clonedOperation.UndoOperations, Is.Empty); + } + + [Test] + public void EntitySetItemRemoveOperationTest() + { + var jsonSerializerOptions = CreateJsonSettings(); + + var dummyType = typeof(IntKeyDummy); + var dummyTypeInfo = Domain.Model.Types[dummyType]; + + var key = Key.Create(Domain, typeof(IntKeyDummy), 111); + var entitySetField = dummyTypeInfo.Fields[nameof(IntKeyDummy.Collection)]; + var itemKey = Key.Create(Domain, typeof(DummyEsItem), 987); + + var operation = new EntitySetItemRemoveOperation(key, entitySetField, itemKey); + var clonedOperation = Cloner.CloneViaJsonSerialization(operation, jsonSerializerOptions); + Assert.That(clonedOperation.Key, Is.EqualTo(operation.Key)); + Assert.That(clonedOperation.Field, Is.EqualTo(operation.Field)); + Assert.That(clonedOperation.ItemKey, Is.EqualTo(operation.ItemKey)); + Assert.That(clonedOperation.Type, Is.EqualTo(operation.Type)); + Assert.That(clonedOperation.IdentifiedEntities, Is.Empty); + Assert.That(clonedOperation.PrecedingOperations, Is.Empty); + Assert.That(clonedOperation.FollowingOperations, Is.Empty); + Assert.That(clonedOperation.UndoOperations, Is.Empty); + } + + [Test] + public void ValidateVersionOperationTest() + { + var jsonSerializerOptions = CreateJsonSettings(); + + var key = Key.Create(Domain, typeof(IntKeyDummy), 111); + var versionTuple = Xtensive.Tuples.Tuple.Create(222); + var versionInfo = new VersionInfo(versionTuple); + + var operation = new ValidateVersionOperation(key, versionInfo); + + var clonedOperation = Cloner.CloneViaJsonSerialization(operation, jsonSerializerOptions); + Assert.That(clonedOperation.Key, Is.EqualTo(key)); + Assert.That(clonedOperation.Version, Is.EqualTo(versionInfo)); + } + + private JsonSerializerOptions CreateJsonSettings() + { + var jsonSerializerOptions = new JsonSerializerOptions() { + WriteIndented = true, + }; + _ = jsonSerializerOptions.AddOperationsConverters(Domain); + return jsonSerializerOptions; + } + } +} diff --git a/Extensions/Xtensive.Orm.Operations.Tests/Xtensive.Orm.Operations.Tests.csproj b/Extensions/Xtensive.Orm.Operations.Tests/Xtensive.Orm.Operations.Tests.csproj new file mode 100644 index 0000000000..5a89fe10f3 --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations.Tests/Xtensive.Orm.Operations.Tests.csproj @@ -0,0 +1,26 @@ + + + + false + true + ..\Extensions.snk + Debug;Release;Debug-NET8;Release-NET8;Debug-NET10;Release-NET10 + + + + + + + + + + + + + + + + + + + diff --git a/Extensions/Xtensive.Orm.Operations/Collections/Deque.cs b/Extensions/Xtensive.Orm.Operations/Collections/Deque.cs new file mode 100644 index 0000000000..285613095b --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations/Collections/Deque.cs @@ -0,0 +1,611 @@ +// Copyright (C) 2003-2010 Xtensive LLC. +// All rights reserved. +// For conditions of distribution and use, see license. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using Xtensive.Comparison; +using Xtensive.Core; + +namespace Xtensive.Orm.Operations.Collections +{ + /// + /// Double-ended queue. + /// + /// The type of queued elements. + /// + /// + /// it is a sequence that supports random access to its elements, + /// constant time of insertion and removal of elements at the both ends of the sequence, + /// and linear time of insertion and removal of elements in the middle. + /// + /// + /// The capacity of a is the number of elements the can hold. + /// In this implementation, the default initial capacity for a is 16; + /// however, that default might change in future versions. + /// + /// + /// As elements are added to a , the capacity is automatically increased as required + /// by reallocating the internal array. The capacity can be decreased by calling . + /// + /// + /// The growth factor is the number by which the current capacity is multiplied when a greater capacity + /// is required. The growth factor is determined when the is constructed. + /// + /// + /// accepts a + /// as a valid value for reference types and allows duplicate elements. + /// + /// + [DebuggerDisplay("Count = {Count}")] + internal class Deque : ICloneable, IEnumerable + { + private const int minimalCapacity = 16; + private const float defaultGrowFactor = 1.4f; + private const float trimThresholdFactor = 0.9f; + + private T[] items; // Actual data buffer + private int headPos; // Heading free element position + private int tailPos; // Taililg free element position + private int count; // Actual number of stored elements + private int version; // Version to detect consistency while enumeration executes + private readonly float growFactor = defaultGrowFactor; + + /// + public int Count + { + [DebuggerStepThrough] + get { return count; } + } + + /// + public T this[int index] + { + get { + ArgumentValidator.EnsureArgumentIsInRange(index, 0, count - 1, "index"); + return items[ConvertToBufferIndex(index)]; + } + set { + ArgumentValidator.EnsureArgumentIsInRange(index, 0, count - 1, "index"); + items[ConvertToBufferIndex(index)] = value; + version++; + } + } + + #region Capacity, TrimExcess + + /// + public int Capacity + { + get { return items.Length; } + set { + if (value != items.Length) { + if (value < count) + throw new ArgumentOutOfRangeException(nameof(value), "Specified capacity is less then collection count."); + if (value > minimalCapacity) { + T[] newItems = new T[value]; + InnerCopyTo(newItems, 0); + headPos = value - 1; + tailPos = count; + items = newItems; + version++; + } + else { + items = new T[minimalCapacity]; + headPos = minimalCapacity - 1; + tailPos = 0; + } + } + } + } + + /// + public void TrimExcess() + { + int trimThreshold = (int) (items.Length * trimThresholdFactor); + if (count < trimThreshold) + Capacity = count; + } + + #endregion + + #region Head, Tail, Add\Extract Head\Tail + + /// + public T Head + { + get { + if (count == 0) + throw Exceptions.CollectionIsEmpty(null); + return items[(items.Length - headPos == 1 ? 0 : headPos + 1)]; + } + } + + /// + public T HeadOrDefault + { + get { + return count == 0 ? default(T) : items[(items.Length - headPos == 1 ? 0 : headPos + 1)]; + } + } + + /// + public T Tail + { + get { + if (count == 0) + throw Exceptions.CollectionIsEmpty(null); + return items[(tailPos == 0 ? items.Length : tailPos) - 1]; + } + } + + /// + public T TailOrDefault + { + get { + return count == 0 ? default(T) : items[(tailPos == 0 ? items.Length : tailPos) - 1]; + } + } + + /// + public void AddHead(T element) + { + if (count == items.Length) + EnsureCapacity(count + 1); + + count++; + items[headPos] = element; + + // Shift to the "previous free" position + if ((--headPos) == -1) { + // If count < buffer.Length then all elements in the interval + // [0 ... buffer.Length - count] are "free" + headPos += items.Length; + } + version++; + } + + /// + public void AddTail(T element) + { + if (count == items.Length) + EnsureCapacity(count + 1); + + count++; + items[tailPos] = element; + + // Shift to "previous free" position + if ((++tailPos) == items.Length) { + // If count < buffer.Length then all elements in the interval + // [count - 1 ... buffer.Length - 1] are "free" + tailPos = 0; + } + version++; + } + + /// + public T ExtractHead() + { + if (count == 0) + throw Exceptions.CollectionIsEmpty(null); + + // Shift to the "head element" position + if ((++headPos) == items.Length) + headPos = 0; + + // Extract element + T result = items[headPos]; + items[headPos] = default(T); + count--; + version++; + + return result; + } + + /// + public T ExtractTail() + { + if (count == 0) + throw Exceptions.CollectionIsEmpty(null); + + // Shift to the "tail element" position + if ((--tailPos) == -1) + tailPos += items.Length; + + // Extract element + T result = items[tailPos]; + items[tailPos] = default(T); + count--; + version++; + + return result; + } + + #endregion + + #region IndexOf, Contains + + /// + public int IndexOf(T item) + { + Predicate criterion = delegate (T innerItem) { + return AdvancedComparerStruct.System.Equals(innerItem, item); + }; + int headIndex = headPos + 1; + if (headIndex == items.Length) + headIndex = 0; + if (tailPos == 0 || tailPos - headIndex > 0) + return ConvertToListIndex(Array.FindIndex(items, headIndex, count, criterion)); + else { + int itemIndex = -1; + if (headIndex > 0) + itemIndex = Array.FindIndex(items, headIndex, criterion); + if (itemIndex < 0) + itemIndex = Array.FindIndex(items, 0, tailPos, criterion); + return ConvertToListIndex(itemIndex); + } + } + + /// + public bool Contains(T item) + { + Predicate criterion = delegate (T innerItem) { return AdvancedComparerStruct.System.Equals(innerItem, item); }; + int headIndex = headPos + 1; + if (tailPos - headIndex > 0) + return Array.FindIndex(items, headIndex, count, criterion) >= 0; + else + return (tailPos > 0 && Array.FindIndex(items, 0, tailPos, criterion) >= 0) || + (headIndex < items.Length && Array.FindIndex(items, headIndex, criterion) >= 0); + } + + #endregion + + #region CopyTo + + /// + public void CopyTo(T[] array, int arrayIndex) + { + ArgumentNullException.ThrowIfNull(array); + array.EnsureIndexIsValid(arrayIndex); + + if (arrayIndex + count > array.Length) + throw new ArgumentException("The destination array is too small.", nameof(array)); + InnerCopyTo(array, arrayIndex); + } + + /// + public void CopyTo(Array array, int index) + { + ArgumentNullException.ThrowIfNull(array); + array.EnsureIndexIsValid(index); + + if (array.Rank != 1) + throw new ArgumentException("The destination array is multi-dimentional", nameof(array)); + if (array.GetLowerBound(0) != 0) + throw new ArgumentException("The destination array does'nt have Zero-based indexing.", nameof(array)); + if (index + count > array.Length) + throw new ArgumentException("The destination array is too small.", nameof(array)); + InnerCopyTo(array, index); + } + + #endregion + + #region Insert, RemoveAt, Remove, RemoveRange, Clear + + /// + public void Insert(int index, T item) + { + ArgumentValidator.EnsureArgumentIsInRange(index, 0, count, "index"); + + if (count == items.Length) + EnsureCapacity(count + 1); + + int bufferIndex = ConvertToBufferIndex(index); + int headIndex = headPos + 1; + if (headIndex == items.Length) + headIndex = 0; + if (bufferIndex == tailPos) + AddTail(item); + else if (bufferIndex == headIndex) + AddHead(item); + else if (bufferIndex < tailPos) { + int dataToMoveLength = tailPos - bufferIndex; + Array.Copy(items, bufferIndex, items, bufferIndex + 1, dataToMoveLength); + items[bufferIndex] = item; + // Shift to "next free" position + if ((++tailPos) == items.Length) + tailPos = 0; + count++; + version++; + } + else if (bufferIndex > headIndex) { + int dataToMoveLength = bufferIndex - headIndex; + Array.Copy(items, headPos + 1, items, headPos, dataToMoveLength); + items[bufferIndex - 1] = item; + // Shift to "previous free" position + if ((--headPos) == -1) + headPos += items.Length; + count++; + version++; + } + else { + throw new InvalidOperationException("Deque.Insert: Wrong buffer index detected."); + } + } + + /// + public void RemoveAt(int index) + { + ArgumentValidator.EnsureArgumentIsInRange(index, 0, count - 1, "index"); + + int bufferIndex = ConvertToBufferIndex(index); + if (tailPos - bufferIndex == 1) + ExtractTail(); + else if (bufferIndex - headPos == 1) + ExtractHead(); + else if (bufferIndex > headPos) { + int dataToMoveLength = bufferIndex - headPos - 1; + // Shift to the "tail element" position + headPos++; + Array.Copy(items, headPos, items, headPos + 1, dataToMoveLength); + items[headPos] = default(T); + count--; + version++; + } + else if (bufferIndex < tailPos) { + int dataToMoveLength = tailPos - bufferIndex - 1; + // Shift to the "head element" position + tailPos--; + Array.Copy(items, bufferIndex + 1, items, bufferIndex, dataToMoveLength); + items[tailPos] = default(T); + count--; + version++; + } + else { + throw new InvalidOperationException("Deque.Insert: Wrong buffer index detected."); + } + } + + /// + public bool Remove(T item) + { + int itemIndex = IndexOf(item); + if (itemIndex < 0) + return false; + RemoveAt(itemIndex); + version++; + return true; + } + + /// + public void RemoveRange(int index, int count) + { + ArgumentValidator.EnsureArgumentIsInRange(index, 0, this.count - 1, "index"); + ArgumentValidator.EnsureArgumentIsInRange(count, 0, this.count - index, "count"); + + if (count < 0 || (count > this.count - index)) + throw new ArgumentOutOfRangeException("count"); + + int bufferIndex = ConvertToBufferIndex(index); + if (this.count > 0) { + int tailLength = this.count - count - index; + if (tailLength > 0) { + if (tailPos - bufferIndex > 0) { + Array.Copy(items, bufferIndex + count, items, bufferIndex, this.count - count - index); + } + else { + int endBufferIndex = ConvertToBufferIndex(index + count); + int firstChunkLength = Math.Min(count, items.Length - bufferIndex); + int secondChunkLength = Math.Max(0, count - firstChunkLength); + if (firstChunkLength > 0) { + Array.Copy(items, endBufferIndex, items, bufferIndex, Math.Min(firstChunkLength, tailLength)); + } + if (secondChunkLength > 0 && tailLength > firstChunkLength) { + Array.Copy(items, endBufferIndex + firstChunkLength, items, 0, tailLength - firstChunkLength); + } + } + } + int startFillPosition = ConvertToBufferIndex(this.count - count); + int newTail = startFillPosition; + if (tailPos < startFillPosition) { + for (int i = startFillPosition; i < items.Length; i++) + items[i] = default(T); + startFillPosition = 0; + } + for (int i = startFillPosition; i < tailPos; i++) + items[i] = default(T); + + tailPos = newTail; + this.count -= count; + } + } + + /// + public void Clear() + { + int capacity = items.Length; + Array.Clear(items, 0, capacity); + headPos = capacity - 1; + tailPos = 0; + count = 0; + version++; + } + + #endregion + + #region IEnumerable, IEnumerable members + + /// + [DebuggerStepThrough] + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + /// + public IEnumerator GetEnumerator() + { + int itemIndex = headPos; + int itemCount = count; + int length = items.Length; + int oldVersion = version; + while (itemCount-- > 0) { + if (version != oldVersion) + throw Exceptions.CollectionHasBeenChanged(null); + if ((++itemIndex) == length) + itemIndex = 0; + yield return items[itemIndex]; + } + } + + #endregion + + #region ICloneable members + + /// + /// Creates a shallow copy of the . + /// + /// A shallow copy of the . + /// + /// + /// A shallow copy of a collection copies only the elements of the collection, + /// whether they are reference types or value types, but it does not copy + /// the objects that the references refer to. The references in the new collection + /// point to the same objects that the references in the original collection point to. + /// + /// + /// In contrast, a deep copy of a collection copies the elements and + /// everything directly or indirectly referenced by the elements. + /// + /// + /// This method is an O(n) operation, where n is . + /// + /// + public virtual object Clone() + { + return new Deque(this); + } + + #endregion + + + #region Private \ internal methods + + private void InnerCopyTo(Array array, int arrayIndex) + { + int headIndex = headPos + 1; + if (count > 0) { + if (tailPos - headIndex > 0) + Array.Copy(items, headIndex, array, arrayIndex, count); + else { + int headPartLength = items.Length - headIndex; + if (headPartLength > 0) + Array.Copy(items, headIndex, array, arrayIndex, headPartLength); + Array.Copy(items, 0, array, arrayIndex + headPartLength, count - headPartLength); + } + } + } + + private int ConvertToListIndex(int bufferIndex) + { + if (bufferIndex < 0) + return bufferIndex; + return (bufferIndex > headPos ? 0 : items.Length) + bufferIndex - headPos - 1; + } + + private int ConvertToBufferIndex(int listIndex) + { + if (listIndex < 0) + return listIndex; + int bufferIndex = headPos + listIndex + 1; + return bufferIndex - (bufferIndex >= items.Length ? items.Length : 0); + } + + private void EnsureCapacity(int requiredCapacity) + { + int currentCapacity = items.Length; + if (currentCapacity < requiredCapacity) { + int newCapacity = currentCapacity == 0 + ? minimalCapacity + : Convert.ToInt32(currentCapacity * growFactor); + if (newCapacity < requiredCapacity) + newCapacity = requiredCapacity; + Capacity = newCapacity; + } + } + + #endregion + + + // Constructors + + private Deque(Deque source) + { + count = source.count; + items = new T[count]; + source.InnerCopyTo(items, 0); + headPos = count - 1; + tailPos = 0; + growFactor = source.growFactor; + } + + /// + /// Initializes a new instance of this type. + /// + public Deque() + : this(minimalCapacity) + { + } + + /// + /// Initializes a new instance of this type. + /// + /// The initial property value. + public Deque(int initialCapacity) + { + if (initialCapacity < minimalCapacity) + initialCapacity = minimalCapacity; + items = new T[initialCapacity]; + headPos = initialCapacity - 1; + tailPos = 0; + count = 0; + } + + /// + /// Initializes a new instance of this type. + /// + /// The initial property value. + /// The factor by which the capacity of the is expanded. + public Deque(int initialCapacity, float growFactor) + : this(initialCapacity) + { + this.growFactor = growFactor; + } + + /// + /// Initializes a new instance of this type. + /// + /// The initial contents of the . + public Deque(IEnumerable source) + { + items = new List(source).ToArray(); + headPos = -1; + tailPos = items.Length; + count = items.Length; + EnsureCapacity(Capacity); + } + + /// + /// Initializes a new instance of this type. + /// + /// The initial contents of the . + /// The factor by which the capacity of the is expanded. + public Deque(IEnumerable source, float growFactor) + : this(source) + { + this.growFactor = growFactor; + } + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.Operations/Collections/ReadOnlyHashSet{T}.cs b/Extensions/Xtensive.Orm.Operations/Collections/ReadOnlyHashSet{T}.cs new file mode 100644 index 0000000000..c9a054fb82 --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations/Collections/ReadOnlyHashSet{T}.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Xtensive.Orm.Operations.Collections +{ + /// + /// Read-only wrapper over the class instance. + /// + [DebuggerDisplay("Count = {Count}")] + internal class ReadOnlyHashSet : IReadOnlySet + { + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + private readonly HashSet innerSet; + + /// + /// Gets the number of elements that are contained in a set. + /// + public int Count => innerSet.Count; + + /// + /// Determines whether a object contains the specified element. + /// + /// + /// if the object contains + /// the specified ; otherwise, . + /// + public bool Contains(T item) => innerSet.Contains(item); + + /// + /// Returns an enumerator that iterates through a object. + /// + /// A object for the object. + public HashSet.Enumerator GetEnumerator() => innerSet.GetEnumerator(); + + /// + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + /// + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + /// + /// Determines whether a object is a proper subset of the specified collection. + /// + /// + /// if the object is a proper subset of + /// the specified collection; otherwise, . + /// + public bool IsProperSubsetOf(IEnumerable other) => innerSet.IsProperSubsetOf(other); + + /// + /// Determines whether a object is a proper superset of the specified collection. + /// + /// + /// if the object is a proper superset of + /// the specified collection; otherwise, . + /// + public bool IsProperSupersetOf(IEnumerable other) => innerSet.IsProperSupersetOf(other); + + /// + /// Determines whether a object is a subset of the specified collection. + /// + /// + /// if the object is a subset of + /// the specified collection; otherwise, . + /// + public bool IsSubsetOf(IEnumerable other) => innerSet.IsSubsetOf(other); + + /// + /// Determines whether a object is a superset of the specified collection. + /// + /// + /// if the object is a superset of + /// the specified collection; otherwise, . + /// + public bool IsSupersetOf(IEnumerable other) => innerSet.IsSupersetOf(other); + + /// + /// Determines whether the current object and a specified collection share common elements. + /// + /// + /// if the object object and collection + /// share at least one common element; otherwise, . + /// + public bool Overlaps(IEnumerable other) => innerSet.Overlaps(other); + + /// + /// Determines whether a object and the specified collection + /// contain the same elements. + /// + /// + /// if the object object is equal to the collection; + /// otherwise, . + /// + public bool SetEquals(IEnumerable other) => innerSet.SetEquals(other); + + /// + /// Copies the elements of a object to an , + /// starting at the specified . + /// + public void CopyTo(T[] array, int arrayIndex) => innerSet.CopyTo(array, arrayIndex); + + // Constructors + + /// + /// Initializes a new instance of this type. + /// + /// The set to wrap. + public ReadOnlyHashSet(HashSet set) + { + innerSet = set; + } + } +} diff --git a/Extensions/Xtensive.Orm.Operations/Interfaces/IExecutableOperation.cs b/Extensions/Xtensive.Orm.Operations/Interfaces/IExecutableOperation.cs new file mode 100644 index 0000000000..12bd6c3855 --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations/Interfaces/IExecutableOperation.cs @@ -0,0 +1,25 @@ +// Copyright (C) 2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +namespace Xtensive.Orm.Operations.Interfaces +{ + /// + /// Extension for contract of operation that + /// can be executed later. + /// + public interface IExecutableOperation : IOperation + { + /// + /// Prepares the operation using specified execution context. + /// + /// The operation execution context. + void Prepare(OperationExecutionContext context); + + /// + /// Executes the operation using specified execution context. + /// + /// The operation execution context. + void Execute(OperationExecutionContext context); + } +} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Interfaces/IOperationLogger.cs b/Extensions/Xtensive.Orm.Operations/Interfaces/IOperationLogger.cs similarity index 94% rename from Orm/Xtensive.Orm/Orm/Interfaces/IOperationLogger.cs rename to Extensions/Xtensive.Orm.Operations/Interfaces/IOperationLogger.cs index 37de632121..c17b208318 100644 --- a/Orm/Xtensive.Orm/Orm/Interfaces/IOperationLogger.cs +++ b/Extensions/Xtensive.Orm.Operations/Interfaces/IOperationLogger.cs @@ -6,7 +6,7 @@ using System.Collections.Generic; -namespace Xtensive.Orm +namespace Xtensive.Orm.Operations.Interfaces { /// /// logger contract. diff --git a/Orm/Xtensive.Orm/Orm/Interfaces/IOperationSequence.cs b/Extensions/Xtensive.Orm.Operations/Interfaces/IOperationSequence.cs similarity index 93% rename from Orm/Xtensive.Orm/Orm/Interfaces/IOperationSequence.cs rename to Extensions/Xtensive.Orm.Operations/Interfaces/IOperationSequence.cs index b841ef8215..5d379a0694 100644 --- a/Orm/Xtensive.Orm/Orm/Interfaces/IOperationSequence.cs +++ b/Extensions/Xtensive.Orm.Operations/Interfaces/IOperationSequence.cs @@ -7,7 +7,7 @@ using System; using System.Collections.Generic; -namespace Xtensive.Orm +namespace Xtensive.Orm.Operations.Interfaces { /// /// Operation sequence contract. diff --git a/Orm/Xtensive.Orm/Orm/Interfaces/IPrecondition.cs b/Extensions/Xtensive.Orm.Operations/Interfaces/IPrecondition.cs similarity index 89% rename from Orm/Xtensive.Orm/Orm/Interfaces/IPrecondition.cs rename to Extensions/Xtensive.Orm.Operations/Interfaces/IPrecondition.cs index c254e0b56c..b21079b749 100644 --- a/Orm/Xtensive.Orm/Orm/Interfaces/IPrecondition.cs +++ b/Extensions/Xtensive.Orm.Operations/Interfaces/IPrecondition.cs @@ -4,7 +4,7 @@ // Created by: Alex Yakunin // Created: 2010.02.24 -namespace Xtensive.Orm +namespace Xtensive.Orm.Operations.Interfaces { /// /// Precondition operation contract. Preconditions change nothing, diff --git a/Orm/Xtensive.Orm/Orm/Interfaces/IUniqueOperation.cs b/Extensions/Xtensive.Orm.Operations/Interfaces/IUniqueOperation.cs similarity index 93% rename from Orm/Xtensive.Orm/Orm/Interfaces/IUniqueOperation.cs rename to Extensions/Xtensive.Orm.Operations/Interfaces/IUniqueOperation.cs index 14ef72ad64..53f77c7f46 100644 --- a/Orm/Xtensive.Orm/Orm/Interfaces/IUniqueOperation.cs +++ b/Extensions/Xtensive.Orm.Operations/Interfaces/IUniqueOperation.cs @@ -7,7 +7,7 @@ using System; using Xtensive.Core; -namespace Xtensive.Orm +namespace Xtensive.Orm.Operations.Interfaces { /// /// Contract for an operation that must be logged only once diff --git a/Orm/Xtensive.Orm/Orm/Operations/Internals/BlockingOperationRegistrationScope.cs b/Extensions/Xtensive.Orm.Operations/Internals/BlockingOperationRegistrationScope.cs similarity index 86% rename from Orm/Xtensive.Orm/Orm/Operations/Internals/BlockingOperationRegistrationScope.cs rename to Extensions/Xtensive.Orm.Operations/Internals/BlockingOperationRegistrationScope.cs index 6f6d9be1de..582e563127 100644 --- a/Orm/Xtensive.Orm/Orm/Operations/Internals/BlockingOperationRegistrationScope.cs +++ b/Extensions/Xtensive.Orm.Operations/Internals/BlockingOperationRegistrationScope.cs @@ -4,11 +4,11 @@ // Created by: Alex Yakunin // Created: 2010.08.05 -namespace Xtensive.Orm.Operations +namespace Xtensive.Orm.Operations.Internal { internal sealed class BlockingOperationRegistrationScope : ICompletableScope { - private OperationRegistry owner; + private readonly OperationRegistry owner; public bool IsCompleted { get; private set; } diff --git a/Orm/Xtensive.Orm/Orm/Operations/Internals/OperationRegistrationScope.cs b/Extensions/Xtensive.Orm.Operations/Internals/OperationRegistrationScope.cs similarity index 92% rename from Orm/Xtensive.Orm/Orm/Operations/Internals/OperationRegistrationScope.cs rename to Extensions/Xtensive.Orm.Operations/Internals/OperationRegistrationScope.cs index d9ee028c25..574a61fcdd 100644 --- a/Orm/Xtensive.Orm/Orm/Operations/Internals/OperationRegistrationScope.cs +++ b/Extensions/Xtensive.Orm.Operations/Internals/OperationRegistrationScope.cs @@ -9,8 +9,7 @@ using Xtensive.Core; - -namespace Xtensive.Orm.Operations +namespace Xtensive.Orm.Operations.Internal { internal sealed class OperationRegistrationScope : ICompletableScope { @@ -65,9 +64,9 @@ public void RegisterEntityIdentifier(Key key, string identifier) KeyByIdentifier.Add(identifier, key); IdentifierByKey.Add(key, identifier); - if (Owner.Session.IsDebugEventLoggingEnabled) { - OrmLog.Debug(nameof(Strings.LogSessionXEntityWithKeyYIdentifiedAsZ), Owner.Session, key, identifier); - } + //if (Owner.Session.IsDebugEventLoggingEnabled) { + // OrmLog.Debug(nameof(Strings.LogSessionXEntityWithKeyYIdentifiedAsZ), Owner.Session, key, identifier); + //} } diff --git a/Extensions/Xtensive.Orm.Operations/NugetContent/ReadMe.md b/Extensions/Xtensive.Orm.Operations/NugetContent/ReadMe.md new file mode 100644 index 0000000000..d1b7e25f13 --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations/NugetContent/ReadMe.md @@ -0,0 +1,180 @@ +Xtensive.Orm.Operations +===================== + +Summary +------- +Provides ability to record chain of operations on persistent types and reply them later + +Prerequisites +------------- +DataObjects.Net 7.3.x or later (http://dataobjects.net) + +Implementation +-------------- + +1. Include types from Xtensive.Orm.Operations assembly into the domain: + +in xml configuration +```xml + + + + + + + + + + +``` + +or in code + +```csharp +var domainConfiguration = new DomainConfiguration("sqlserver://dotest:dotest@localhost/DO-Tests?MultipleActiveResultSets=True"); + +domainConfiguration.Types.Register(typeof(SomeTypeFromYourAssembly).Assembly); +domainConfiguration.Types.Register(typeof(Xtensive.Orm.Operations.Operation).Assembly); + +``` + + +2. To start logging changes, instanciate an ```OperationLog``` and declare region of capture by attaching to session by using ```OperationCapturer.Attach(Session, OperationLog)``` +3. Retrieve registered operations from the ```OperationLog``` instance you created and passed into ```OperationCapturer```. + + +Demo +---- + +First, create a log + +```csharp +var operationLog = new Xtensive.Orm.Operations.OperationLog(OperationLogType.SystemOperationLog); +``` + +Then, open session and attach capturer + +```csharp +var operationLog = new Xtensive.Orm.Operations.OperationLog(OperationLogType.SystemOperationLog); + +using (var session = Domain.OpenSession()) +using (var t = session.OpenTransaction()) + using (var capturer = Xtensive.Orm.Operations.OperationCapturer.Attach(session, operationLog)) { + var author1 = new Author(session, "Unknown", "Author"); //generate key operation + create entity operation + author1.DateOfBirth = new DateTime(1985, 6, 12); // set entity field operation + + var book11 = new Book(session); + book11.Title = "100 pages about something"; + book11.NumberOfPages = 100; + book11.Author = author1; // only set entity field operation, no operation for paired EntitySet + + var book12 = new Book(session); + book12.Title = "Even more pages abount something"; + book12.NumberOfPages = 200; + book12.Author = author1; + + var book13 = new Book(session); + book13.Title = "The biggest book ever"; + book13.NumberOfPages = 300; + book13.Author = author1; + + var author2 = new Author(session, "Even Less known", "Author"); + author2.DateOfBirth = new DateTime(1985, 6, 12); + + var book21 = new Book(session) { Title = "100 ways to not live", NumberOfPages = 111 }; + _ = author2.Books.Add(book21); // entity set item add operation + + var book22 = new Book(session) { Title = "50 ways of eating pizza", NumberOfPages = 25 }; + _ = author2.Books.Add(book22); + var book23 = new Book(session) { Title = "Single way to eat banana", NumberOfPages = 3 }; + _ = author2.Books.Add(book23); + + _ = author1.Books.Remove(book12); // entity set item remove operation + book12.Remove(); entity remove operation + + var book23 = author2.Books.AsEnumerable().Last(); + _ = author2.Books.Remove(book23); + t.Complete(); + } +} + +// do something with logged operations, if needed +foreach (var op in operationLog) { + // do something +} + +``` + +OperationLog can also replay collected operations, but since they will replay exactly, conflicts may occur if created by replay Entites already exist in the database. +Based on the previous example, replay example may look like + +```csharp +var operationLog = new Xtensive.Orm.Operations.OperationLog(OperationLogType.SystemOperationLog); + +using (var session = Domain.OpenSession()) +using (var t = session.OpenTransaction()) + using (var capturer = Xtensive.Orm.Operations.OperationCapturer.Attach(session, operationLog)) { + var author1 = new Author(session, "Unknown", "Author"); //generate key operation + create entity operation + author1.DateOfBirth = new DateTime(1985, 6, 12); // set entity field operation + + var book11 = new Book(session); + book11.Title = "100 pages about something"; + book11.NumberOfPages = 100; + book11.Author = author1; // only set entity field operation, no operation for paired EntitySet + + var book12 = new Book(session); + book12.Title = "Even more pages abount something"; + book12.NumberOfPages = 200; + book12.Author = author1; + + var book13 = new Book(session); + book13.Title = "The biggest book ever"; + book13.NumberOfPages = 300; + book13.Author = author1; + + var author2 = new Author(session, "Even Less known", "Author"); + author2.DateOfBirth = new DateTime(1985, 6, 12); + + var book21 = new Book(session) { Title = "100 ways to not live", NumberOfPages = 111 }; + _ = author2.Books.Add(book21); // entity set item add operation + + var book22 = new Book(session) { Title = "50 ways of eating pizza", NumberOfPages = 25 }; + _ = author2.Books.Add(book22); + var book23 = new Book(session) { Title = "Single way to eat banana", NumberOfPages = 3 }; + _ = author2.Books.Add(book23); + + _ = author1.Books.Remove(book12); // entity set item remove operation + book12.Remove(); entity remove operation + + var book23 = author2.Books.AsEnumerable().Last(); + _ = author2.Books.Remove(book23); + + //t.Complete(); // no complete means rollback + } +} + +using (var sessionForReplay = Domain.OpenSession()) +using (var tx = sessionForReplay.OpenTransaction()) { + + // replay + var keys = operationLog.Replay(sessionForReplay); + + tx.Complete(); +} + +``` + +If there is a need to disable registration for a while, it may be done like so + +```csharp +using (var session = Domain.OpenSession()) +using (var tx = session.OpenTransaction()) { + + using (var disableScope session.Operations.DisableSystemOperationRegistration()) { + // changes done here will not be registered + } + + tx.Complete(); +} + +``` \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Operations/OperationCapturer.cs b/Extensions/Xtensive.Orm.Operations/OperationCapturer.cs similarity index 97% rename from Orm/Xtensive.Orm/Orm/Operations/OperationCapturer.cs rename to Extensions/Xtensive.Orm.Operations/OperationCapturer.cs index 586f95ea49..47bca73b1e 100644 --- a/Orm/Xtensive.Orm/Orm/Operations/OperationCapturer.cs +++ b/Extensions/Xtensive.Orm.Operations/OperationCapturer.cs @@ -6,6 +6,7 @@ using System; using Xtensive.Core; +using Xtensive.Orm.Operations.Interfaces; namespace Xtensive.Orm.Operations { @@ -14,7 +15,7 @@ namespace Xtensive.Orm.Operations /// and writing their sequence to instance /// (). /// - public sealed class OperationCapturer : SessionBound, + public sealed class OperationCapturer : SessionBound, IDisposable { /// diff --git a/Orm/Xtensive.Orm/Orm/Operations/OperationExecutionContext.cs b/Extensions/Xtensive.Orm.Operations/OperationExecutionContext.cs similarity index 53% rename from Orm/Xtensive.Orm/Orm/Operations/OperationExecutionContext.cs rename to Extensions/Xtensive.Orm.Operations/OperationExecutionContext.cs index 7ed4bd4b4a..63a5faf3b0 100644 --- a/Orm/Xtensive.Orm/Orm/Operations/OperationExecutionContext.cs +++ b/Extensions/Xtensive.Orm.Operations/OperationExecutionContext.cs @@ -6,19 +6,21 @@ using System.Collections.Generic; using System.Collections.ObjectModel; +using Xtensive.Orm.Services; +using Xtensive.Orm.Operations.Interfaces; namespace Xtensive.Orm.Operations { /// - /// Operation context for and - /// methods executed for a set of operations. + /// Operation context for and + /// methods executed for a set of operations. /// public sealed class OperationExecutionContext { - private readonly HashSet prefetchKeys; - private readonly HashSet excludedKeys; - private readonly Dictionary keyMapping = new Dictionary(); + private readonly HashSet prefetchKeys = new(); + private readonly HashSet excludedKeys = new(); + private readonly Dictionary keyMapping = new(); /// /// The session this instance is bound to. @@ -30,6 +32,21 @@ public sealed class OperationExecutionContext /// public readonly ReadOnlyDictionary KeyMapping; + /// + /// The persistent accessor service, accessed from of the context. + /// + public readonly DirectPersistentAccessor PersistentAccessor; + + /// + /// The entity accessor service, accessed from of the context. + /// + public readonly DirectEntityAccessor EntityAccessor; + + /// + /// The EntitySet accessor service, accessed from of the context. + /// + public readonly DirectEntitySetAccessor EntitySetAccessor; + /// /// Gets the sequence of keys to prefetch. /// @@ -42,10 +59,9 @@ public sealed class OperationExecutionContext /// Remapped key public Key TryRemapKey(Key key) { - if (key==null) + if (key is null) return key; - Key remappedKey; - return KeyMapping.TryGetValue(key, out remappedKey) ? remappedKey : key; + return KeyMapping.TryGetValue(key, out var remappedKey) ? remappedKey : key; } /// @@ -55,18 +71,17 @@ public Key TryRemapKey(Key key) /// if set to , the key is new. public void RegisterKey(Key key, bool isNew) { - if (key == null) + if (key is null) return; if (isNew) - excludedKeys.Add(key); - else - if (!excludedKeys.Contains(key)) - prefetchKeys.Add(key); + _ = excludedKeys.Add(key); + else if (!excludedKeys.Contains(key)) + _ = prefetchKeys.Add(key); } internal void AddKeyMapping(Key localKey, Key realKey) { - if (localKey!=realKey) + if (localKey != realKey) keyMapping.Add(localKey, realKey); } @@ -80,8 +95,10 @@ public OperationExecutionContext(Session session) { Session = session; KeyMapping = new ReadOnlyDictionary(keyMapping); - prefetchKeys = new HashSet(); - excludedKeys = new HashSet(); + + EntityAccessor = session.Services.Get(); + PersistentAccessor = session.Services.Get(); + EntitySetAccessor = session.Services.Get(); } } } \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.Operations/OperationExtensions.cs b/Extensions/Xtensive.Orm.Operations/OperationExtensions.cs new file mode 100644 index 0000000000..1d47d35087 --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations/OperationExtensions.cs @@ -0,0 +1,20 @@ +// Copyright (C) 2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +namespace Xtensive.Orm.Operations +{ + /// + /// Various extension. + /// + public static class OperationExtensions + { + /// + /// Easy access to operation factory. + /// + public static IOperationFactory GetOperationFactory(this IOperationRegistry operationRegistry) + { + return operationRegistry.Session.Domain.Services.Get(); + } + } +} diff --git a/Extensions/Xtensive.Orm.Operations/OperationFactory.cs b/Extensions/Xtensive.Orm.Operations/OperationFactory.cs new file mode 100644 index 0000000000..a4f61985d6 --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations/OperationFactory.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Xtensive.IoC; +using Xtensive.Orm.Model; + +namespace Xtensive.Orm.Operations +{ + /// + /// Creates real instances of operations. + /// + [Service(typeof(IOperationFactory), Singleton = true)] + public sealed class OperationFactory : IOperationFactory + { + // Operations defined in kind-of-entity-lifecycle order + + /// + public IOperation KeyGenerateOperation(Key key) => new KeyGenerateOperation(key); + + /// + public IOperation EntityCreationOperation(Key key) => new EntityCreateOperation(key); + + /// + public IOperation EntityInitializeOperation(Key key) => new EntityInitializeOperation(key); + + // Entity Fields set calls + /// + public IOperation EntityFieldSetOperation(Key key, FieldInfo field, object value) => new EntityFieldSetOperation(key, field, value); + + /// + public IOperation EntityFieldSetOperation(Key key, FieldInfo field, Key valueKey) => new EntityFieldSetOperation(key, field, valueKey); + + // EntitySet Operations - Add, Remove, Clear + /// + public IOperation EntitySetItemAddOperation(Key key, FieldInfo field, Key itemKey) => new EntitySetItemAddOperation(key, field, itemKey); + + /// + public IOperation EntitySetItemRemoveOperation(Key key, FieldInfo field, Key itemKey) => new EntitySetItemRemoveOperation(key, field, itemKey); + + /// + public IOperation EntitySetClearOperation(Key key, FieldInfo field) => new EntitySetClearOperation(key, field); + + // Entity Removal + /// + public IOperation EntitiesRemoveOperation(IEnumerable keys) => new EntitiesRemoveOperation(keys.ToArray()); + + /// + public IOperation EntityRemovalOperation(Key key) => new EntitiesRemoveOperation(key); + + + // other operations + /// + public IOperation MethodCallOperation(Action executeAction, params object[] arguments) + => new MethodCallOperation(executeAction, arguments); + + /// + public IOperation MethodCallOperation(Action prepareAction, Action executeAction, params object[] arguments) + => new MethodCallOperation(prepareAction, executeAction, arguments); + + /// + public IOperation ValidateVersionOperation(Key key, VersionInfo version) => new ValidateVersionOperation(key, version); + } +} diff --git a/Orm/Xtensive.Orm/Orm/OperationLog.cs b/Extensions/Xtensive.Orm.Operations/OperationLog.cs similarity index 79% rename from Orm/Xtensive.Orm/Orm/OperationLog.cs rename to Extensions/Xtensive.Orm.Operations/OperationLog.cs index 7262f36ba5..b4c430027b 100644 --- a/Orm/Xtensive.Orm/Orm/OperationLog.cs +++ b/Extensions/Xtensive.Orm.Operations/OperationLog.cs @@ -7,21 +7,20 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Linq; using System.Text; using Xtensive.Core; +using Xtensive.Orm.Operations.Interfaces; -using Xtensive.Orm.Operations; - -namespace Xtensive.Orm +namespace Xtensive.Orm.Operations { /// /// Built-in implementation of both /// and . /// - [Serializable] public sealed class OperationLog : IOperationLogger, - IOperationSequence + Interfaces.IOperationSequence { private readonly List operations = new List(); private HashSet uniqueOperations; @@ -54,22 +53,23 @@ public void Log(IEnumerable source) public KeyMapping Replay(Session session) { if (session.Operations.IsRegisteringOperation) - throw new InvalidOperationException(Strings.ExRunningOperationRegistrationMustBeFinished); + throw new InvalidOperationException("Running operation registration must be finished."); var executionContext = new OperationExecutionContext(session); bool isSystemOperationLog = LogType==OperationLogType.SystemOperationLog; KeyMapping keyMapping; using (session.Activate()) { - using (isSystemOperationLog ? (IDisposable) session.OpenSystemLogicOnlyRegion() : null) + using (isSystemOperationLog ? (IDisposable) AccessOpenSystemLogicOnlyRegionMethod(session) : null) using (var tx = session.OpenTransaction(TransactionOpenMode.New)) { - foreach (var operation in operations) + var executableOperations = operations.OfType().ToArray(); + foreach (var operation in executableOperations) operation.Prepare(executionContext); session.Query.Many(executionContext.KeysToPrefetch).Run(); - foreach (var operation in operations) { + foreach (var operation in executableOperations) { var identifierToKey = new Dictionary(); var handler = new EventHandler((sender, e) => { foreach (var pair in e.Operation.IdentifiedEntities) @@ -110,10 +110,11 @@ public object Replay(object target) /// public override string ToString() { - var sb = new StringBuilder($"{Strings.Operations}:"); + var sb = new StringBuilder("Operations:"); _ = sb.AppendLine(); - foreach (var o in operations) - sb.AppendLine(o.ToString().Indent(2)); + foreach (var o in operations) { + _ = sb.AppendLine(o.ToString().Indent(2)); + } return sb.ToString().Trim(); } @@ -142,11 +143,17 @@ private void TryAppendUniqueOperation(IOperation operation) if (uniqueOperations==null) uniqueOperations = new HashSet(); if (!uniqueOperations.Add(uniqueOperation) && !uniqueOperation.IgnoreIfDuplicate) - throw new InvalidOperationException(string.Format( - Strings.ExDuplicateForOperationXIsFound, uniqueOperation)); + throw new InvalidOperationException(string.Format("Duplicate for Operation {0} is found", uniqueOperation)); } } + private static IDisposable AccessOpenSystemLogicOnlyRegionMethod(Session session) + { + var OpenSystemLogicOnlyRegion = typeof(Session).GetMethod("OpenSystemLogicOnlyRegion", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); + + return (IDisposable) OpenSystemLogicOnlyRegion.Invoke(session, null); + } + #endregion diff --git a/Orm/Xtensive.Orm/Orm/Operations/OperationRegistry.cs b/Extensions/Xtensive.Orm.Operations/OperationRegistry.cs similarity index 70% rename from Orm/Xtensive.Orm/Orm/Operations/OperationRegistry.cs rename to Extensions/Xtensive.Orm.Operations/OperationRegistry.cs index cc4e6b4d08..06fd32c24e 100644 --- a/Orm/Xtensive.Orm/Orm/Operations/OperationRegistry.cs +++ b/Extensions/Xtensive.Orm.Operations/OperationRegistry.cs @@ -1,36 +1,20 @@ -// Copyright (C) 2010-2020 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Alex Yakunin -// Created: 2010.08.04 - using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Xtensive.Core; +using Xtensive.IoC; +using Xtensive.Orm.Model; +using Xtensive.Orm.Operations.Internal; namespace Xtensive.Orm.Operations { + /// /// Operation registry for type. /// - public sealed class OperationRegistry + [ServiceAttribute(typeof(IOperationRegistry), Singleton = true)] + public sealed class OperationRegistry : IOperationRegistry { - public readonly struct SystemOperationRegistrationScope : IDisposable - { - private readonly OperationRegistry registry; - private readonly bool prevIsSystemOperationRegistrationEnabled; - - internal SystemOperationRegistrationScope(OperationRegistry registry, bool enable) - { - this.registry = registry; - prevIsSystemOperationRegistrationEnabled = registry.IsSystemOperationRegistrationEnabled; - registry.IsSystemOperationRegistrationEnabled = enable; - } - - public void Dispose() => registry.IsSystemOperationRegistrationEnabled = prevIsSystemOperationRegistrationEnabled; - } - private readonly ICompletableScope blockingScope; private readonly Collections.Deque scopes = new(); private bool isOperationRegistrationEnabled = true; @@ -39,18 +23,14 @@ internal SystemOperationRegistrationScope(OperationRegistry registry, bool enabl /// /// Gets the session this instance is bound to. /// - internal Session Session { get; private set; } + public Session Session { get; private set; } #region IsXxx properties /// /// Indicates whether operation logging is enabled. - /// implicitly turns this option off; - /// does this explicitly. /// - public bool IsRegistrationEnabled { - get { return isOperationRegistrationEnabled || isUndoOperationRegistrationEnabled; } - } + public bool IsRegistrationEnabled => isOperationRegistrationEnabled || isUndoOperationRegistrationEnabled; /// /// Gets a value indicating whether system operation registration is enabled. @@ -59,12 +39,13 @@ public bool IsRegistrationEnabled { /// /// Gets a value indicating whether this instance can register operation - /// using method. + /// using method. /// - public bool CanRegisterOperation { + public bool CanRegisterOperation + { get { var scope = scopes.TailOrDefault; - return scope!=null && scope is OperationRegistrationScope; + return scope != null && scope is OperationRegistrationScope; } } @@ -73,38 +54,40 @@ public bool CanRegisterOperation { /// i.e. method was invoked, but the /// scope isn't closed yet. /// - public bool IsRegisteringOperation { - get { return scopes.Count!=0; } - } + public bool IsRegisteringOperation => scopes.Count != 0; - internal bool IsOutermostOperationRegistrationEnabled { + internal bool IsOutermostOperationRegistrationEnabled + { get { return ( - OutermostOperationCompleted!=null || OutermostOperationStarting!=null || - NestedOperationCompleted!=null || NestedOperationStarting!=null + OutermostOperationCompleted != null || OutermostOperationStarting != null || + NestedOperationCompleted != null || NestedOperationStarting != null ) && IsRegistrationEnabled; } } - internal bool IsNestedOperationRegistrationEnabled { - get { - return - (NestedOperationStarting!=null || NestedOperationCompleted!=null) - && IsRegistrationEnabled; + internal bool IsNestedOperationRegistrationEnabled + { + get { + return + (NestedOperationStarting != null || NestedOperationCompleted != null) + && IsRegistrationEnabled; } } - internal bool IsOperationRegistrationEnabled { + internal bool IsOperationRegistrationEnabled + { get { return ( - OutermostOperationCompleted!=null || OutermostOperationStarting!=null || - NestedOperationCompleted!=null || NestedOperationStarting!=null + OutermostOperationCompleted != null || OutermostOperationStarting != null || + NestedOperationCompleted != null || NestedOperationStarting != null ) && isOperationRegistrationEnabled; } } - internal bool IsUndoOperationRegistrationEnabled { - get { return UndoOperation!=null && IsUndoOperationRegistrationEnabled; } + internal bool IsUndoOperationRegistrationEnabled + { + get { return UndoOperation != null && IsUndoOperationRegistrationEnabled; } } #endregion @@ -113,7 +96,7 @@ internal bool IsUndoOperationRegistrationEnabled { /// Registers the operation. /// /// The operation to register. - public void RegisterOperation(Operation operation) + public void RegisterOperation(IOperation operation) { RegisterOperation(operation, false); } @@ -125,14 +108,14 @@ public void RegisterOperation(Operation operation) /// If set to , /// method /// will be called on completion of operation registration. - public void RegisterOperation(Operation operation, bool isStarted) + public void RegisterOperation(IOperation operation, bool isStarted) { var scope = GetCurrentOperationRegistrationScope(); - if (scope==null) + if (scope == null) return; - if (scope.Operation!=null) - throw new InvalidOperationException(Strings.ExOnlyOneOperationCanBeRegisteredInEachScope); - operation.Type = scope.OperationType; + if (scope.Operation != null) + throw new InvalidOperationException("Only one operation can be registered in each scope."); + (operation as Operation).Type = scope.OperationType; scope.Operation = operation; if (isStarted) { scope.IsOperationStarted = true; @@ -163,17 +146,17 @@ public void NotifyOperationStarting(bool throwIfNotRegistered) if (!CanRegisterOperation) return; var scope = GetCurrentOperationRegistrationScope(); - if (scope==null) + if (scope == null) return; var operation = scope.Operation; - if (operation==null) { + if (operation == null) { if (throwIfNotRegistered) - throw new InvalidOperationException(Strings.ExOperationIsNotRegisteredYet); + throw new InvalidOperationException("Operation isn't registered yet. See Session.Operations.RegisterOperations()."); else return; } if (scope.IsOperationStarted) - throw new InvalidOperationException(Strings.ExOperationStartedIsAlreadyCalledForThisOperation); + throw new InvalidOperationException("OperatonStarted is alerady called for this operation."); scope.IsOperationStarted = true; if (scope.IsOutermost) NotifyOutermostOperationStarting(operation); @@ -185,12 +168,12 @@ public void NotifyOperationStarting(bool throwIfNotRegistered) /// Registers the operation. /// /// The operation to register. - public void RegisterUndoOperation(Operation operation) + public void RegisterUndoOperation(IOperation operation) { var scope = GetCurrentOperationRegistrationScope(); - if (scope==null) + if (scope == null) return; - if (scope.UndoOperations==null) + if (scope.UndoOperations == null) scope.UndoOperations = new List(); scope.UndoOperations.Add(operation); // Notifying... @@ -207,7 +190,7 @@ public void RegisterUndoOperation(Operation operation) public void RegisterEntityIdentifier(Key key, string identifier) { var scope = scopes.HeadOrDefault as OperationRegistrationScope; - if (scope==null) + if (scope == null) return; scope.RegisterEntityIdentifier(key, identifier); } @@ -230,13 +213,15 @@ public IDisposable DisableUndoOperationRegistration() /// Temporarily disables system operation logging. /// /// An object enabling the logging back on its disposal. - public SystemOperationRegistrationScope DisableSystemOperationRegistration() => new(this, false); + public SystemOperationRegistrationScope DisableSystemOperationRegistration() => new SystemOperationRegistrationScope(this, false, + static (reg, newState) => ((OperationRegistry) reg).IsSystemOperationRegistrationEnabled = newState); /// /// Temporarily enables system operation logging. /// /// An object disabling the logging back on its disposal. - public SystemOperationRegistrationScope EnableSystemOperationRegistration() => new(this, true); + public SystemOperationRegistrationScope EnableSystemOperationRegistration() => new SystemOperationRegistrationScope(this, true, + static (reg, newState) => ((OperationRegistry) reg).IsSystemOperationRegistrationEnabled = newState); /// /// Registers the operation. @@ -246,12 +231,12 @@ public IDisposable DisableUndoOperationRegistration() public ICompletableScope BeginRegistration(OperationType operationType) { // Let's see if any kind of operation (incl. undo) is enabled for registration - bool isRegistrationEnabled = IsOutermostOperationRegistrationEnabled; + bool isRegistrationEnabled = IsOutermostOperationRegistrationEnabled; if (!isRegistrationEnabled) return SetCurrentScope(blockingScope); - + ICompletableScope currentScope; - bool isSystemOperation = (operationType & OperationType.System)==OperationType.System; + bool isSystemOperation = (operationType & OperationType.System) == OperationType.System; if (isSystemOperation) { if (!IsSystemOperationRegistrationEnabled) return SetCurrentScope(blockingScope); @@ -260,11 +245,11 @@ public ICompletableScope BeginRegistration(OperationType operationType) } else { currentScope = GetCurrentScope(); - bool currentScopeIsBlocking = currentScope!=null && (currentScope as OperationRegistrationScope)==null; + bool currentScopeIsBlocking = currentScope != null && (currentScope as OperationRegistrationScope) == null; if (currentScopeIsBlocking) return SetCurrentScope(blockingScope); } - + return SetCurrentScope(new OperationRegistrationScope(this, operationType, currentScope)); } @@ -277,19 +262,19 @@ internal void CloseOperationRegistrationScope(OperationRegistrationScope scope) return; if (!scope.IsOperationStarted) { if (scope.IsCompleted) - throw new InvalidOperationException(Strings.ExOperationIsNotMarkedAsStarted); + throw new InvalidOperationException("Operation isn't marked as started. See Session.Operations.OperationStarted() method."); else // We can't throw an exception here, since it will suppress the thrown one. return; } - if (scope.PrecedingOperations!=null) + if (scope.PrecedingOperations != null) operation.PrecedingOperations = scope.PrecedingOperations.AsReadOnly(); - if (scope.FollowingOperations!=null) + if (scope.FollowingOperations != null) operation.FollowingOperations = scope.FollowingOperations.AsReadOnly(); - if (scope.UndoOperations!=null) + if (scope.UndoOperations != null) operation.UndoOperations = scope.UndoOperations.AsReadOnly(); - if (scope.KeyByIdentifier!=null) + if (scope.KeyByIdentifier != null) operation.IdentifiedEntities = new ReadOnlyDictionary(scope.KeyByIdentifier); } finally { @@ -299,12 +284,12 @@ internal void CloseOperationRegistrationScope(OperationRegistrationScope scope) var parentScope = GetCurrentOrParentOperationRegistrationScope(); if (parentScope != null) { if (!parentScope.IsOperationStarted) { - if (parentScope.PrecedingOperations==null) + if (parentScope.PrecedingOperations == null) parentScope.PrecedingOperations = new List(); parentScope.PrecedingOperations.Add(operation); } else { - if (parentScope.FollowingOperations==null) + if (parentScope.FollowingOperations == null) parentScope.FollowingOperations = new List(); parentScope.FollowingOperations.Add(operation); } @@ -343,31 +328,31 @@ internal void CloseOperationRegistrationScope(OperationRegistrationScope scope) /// public event EventHandler UndoOperation; - internal void NotifyOutermostOperationStarting(IOperation operation) + private void NotifyOutermostOperationStarting(IOperation operation) { - if (OutermostOperationStarting!=null && IsRegistrationEnabled) + if (OutermostOperationStarting != null && IsRegistrationEnabled) OutermostOperationStarting(this, new OperationEventArgs(operation)); } - internal void NotifyOutermostOperationCompleted(IOperation operation, bool isCompleted) + private void NotifyOutermostOperationCompleted(IOperation operation, bool isCompleted) { - if (OutermostOperationCompleted!=null && IsRegistrationEnabled) + if (OutermostOperationCompleted != null && IsRegistrationEnabled) OutermostOperationCompleted(this, new OperationCompletedEventArgs(operation, isCompleted)); } - internal void NotifyNestedOperationStarting(IOperation operation) + private void NotifyNestedOperationStarting(IOperation operation) { - if (NestedOperationStarting!=null && IsRegistrationEnabled) + if (NestedOperationStarting != null && IsRegistrationEnabled) NestedOperationStarting(this, new OperationEventArgs(operation)); } - internal void NotifyNestedOperationCompleted(IOperation operation, bool isCompleted) + private void NotifyNestedOperationCompleted(IOperation operation, bool isCompleted) { - if (NestedOperationCompleted!=null && IsRegistrationEnabled) + if (NestedOperationCompleted != null && IsRegistrationEnabled) NestedOperationCompleted(this, new OperationCompletedEventArgs(operation, isCompleted)); } - internal void NotifyUndoOperation(IOperation operation) + private void NotifyUndoOperation(IOperation operation) { if (IsUndoOperationRegistrationEnabled) UndoOperation(this, new OperationEventArgs(operation)); @@ -377,35 +362,37 @@ internal void NotifyUndoOperation(IOperation operation) #region Private \ internal methods - internal ICompletableScope GetCurrentScope() - { - return scopes.TailOrDefault; - } + private OperationRegistrationScope GetCurrentOperationRegistrationScope() { var scope = GetCurrentScope(); - if (scope==null) - throw new InvalidOperationException(Strings.ExNoOperationRegistrationScope); + if (scope == null) + throw new InvalidOperationException("No operation registration scope. Use Session.OperationRegistry.BeginRegistration method to open it."); return scope as OperationRegistrationScope; } private OperationRegistrationScope GetCurrentOrParentOperationRegistrationScope() { var scope = GetCurrentScope(); - if (scope==null) + if (scope == null) return null; var result = scope as OperationRegistrationScope; - if (result!=null) + if (result != null) return result; var list = new ICompletableScope[scopes.Count]; scopes.CopyTo(list, 0); - for (int i = list.Length - 2; i>=0; i--) { + for (int i = list.Length - 2; i >= 0; i--) { result = list[i] as OperationRegistrationScope; - if (result!=null) + if (result != null) return result; } - throw new InvalidOperationException(Strings.ExNoOperationRegistrationScope); + throw new InvalidOperationException("No operation registration scope. Use Session.OperationRegistry.BeginRegistration method to open it."); + } + + internal ICompletableScope GetCurrentScope() + { + return scopes.TailOrDefault; } internal ICompletableScope SetCurrentScope(ICompletableScope scope) @@ -416,15 +403,15 @@ internal ICompletableScope SetCurrentScope(ICompletableScope scope) internal void RemoveCurrentScope(ICompletableScope scope) { - if (scopes.TailOrDefault!=scope) - throw new InvalidOperationException(Strings.ExInvalidScopeDisposalOrder); - scopes.ExtractTail(); + if (scopes.TailOrDefault != scope) + throw new InvalidOperationException("Invalid scope disposal order."); + _ = scopes.ExtractTail(); } internal long GetNextIdentifier() { var scope = scopes.HeadOrDefault as OperationRegistrationScope; - return scope==null ? -1 : scope.CurrentIdentifier++; + return scope == null ? -1 : scope.CurrentIdentifier++; } #endregion @@ -432,10 +419,16 @@ internal long GetNextIdentifier() // Constructors - internal OperationRegistry(Session session) + + /// + /// Creates instance of this class. + /// + /// The session registry is bound to. + [ServiceConstructor] + public OperationRegistry(Session session) { Session = session; blockingScope = new BlockingOperationRegistrationScope(this); } } -} \ No newline at end of file +} diff --git a/Orm/Xtensive.Orm/Orm/Operations/EntitiesRemoveOperation.cs b/Extensions/Xtensive.Orm.Operations/Operations/EntitiesRemoveOperation.cs similarity index 78% rename from Orm/Xtensive.Orm/Orm/Operations/EntitiesRemoveOperation.cs rename to Extensions/Xtensive.Orm.Operations/Operations/EntitiesRemoveOperation.cs index 1f378137c3..b9d28556e9 100644 --- a/Orm/Xtensive.Orm/Orm/Operations/EntitiesRemoveOperation.cs +++ b/Extensions/Xtensive.Orm.Operations/Operations/EntitiesRemoveOperation.cs @@ -6,13 +6,9 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; -using System.Runtime.Serialization; -using System.Security; -using System.Security.Permissions; +using System.Text.Json.Serialization; using Xtensive.Core; -using Xtensive.Collections; namespace Xtensive.Orm.Operations @@ -20,10 +16,10 @@ namespace Xtensive.Orm.Operations /// /// Describes removal operation. /// - [Serializable] public class EntitiesRemoveOperation : KeySetOperation { /// + [JsonIgnore] public override string Title { get { return "Remove entities"; } } @@ -61,17 +57,10 @@ public EntitiesRemoveOperation(Key key) /// Initializes a new instance of this class. /// /// The keys of entities to remove. - public EntitiesRemoveOperation(IEnumerable keys) + [JsonConstructor] + public EntitiesRemoveOperation(IReadOnlyList keys) : base(keys) { } - - // Serialization - - /// - public EntitiesRemoveOperation(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Operations/EntityCreateOperation.cs b/Extensions/Xtensive.Orm.Operations/Operations/EntityCreateOperation.cs similarity index 67% rename from Orm/Xtensive.Orm/Orm/Operations/EntityCreateOperation.cs rename to Extensions/Xtensive.Orm.Operations/Operations/EntityCreateOperation.cs index f65c759a27..aca5aeb511 100644 --- a/Orm/Xtensive.Orm/Orm/Operations/EntityCreateOperation.cs +++ b/Extensions/Xtensive.Orm.Operations/Operations/EntityCreateOperation.cs @@ -5,8 +5,8 @@ // Created: 2010.02.25 using System; -using System.Runtime.Serialization; -using Xtensive.Core; +using System.Text.Json.Serialization; +using Xtensive.Orm.Services; namespace Xtensive.Orm.Operations @@ -14,20 +14,22 @@ namespace Xtensive.Orm.Operations /// /// Describes creation operation. /// - [Serializable] public class EntityCreateOperation : EntityOperation { /// /// Gets the type name of the entity. /// + [JsonInclude] public string TypeName { get; private set; } /// + [JsonIgnore] public override string Title { get { return "Create entity"; } } /// + [JsonIgnore] public override string Description { get { return $"{Title}, TypeName = {TypeName}, Key = {Key}"; @@ -48,8 +50,9 @@ protected override void ExecuteSelf(OperationExecutionContext context) var domain = session.Domain; var key = context.TryRemapKey(Key); var type = domain.Model.Types[TypeName]; - key = Key.Create(domain, session.StorageNodeId, type, TypeReferenceAccuracy.ExactType, key.Value); - session.CreateOrInitializeExistingEntity(type.UnderlyingType, key); + key = Key.Create(domain, session.StorageNodeId, type.UnderlyingType, TypeReferenceAccuracy.ExactType, key.Value); + var persistentAccessor = session.Services.GetService(); + _ = persistentAccessor.CreateEntity(key); } /// @@ -68,24 +71,8 @@ public EntityCreateOperation(Key key) : base(key) { if (!key.HasExactType) - throw Exceptions.InternalError(Strings.ExKeyMustHaveExactType, OrmLog.Instance); + throw new ArgumentException("Key must have exact type here.", nameof(key)); TypeName = key.TypeInfo.Name; } - - // Serialization - - /// - protected override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddValue("TypeName", TypeName); - } - - /// - protected EntityCreateOperation(SerializationInfo info, StreamingContext context) - : base(info, context) - { - TypeName = info.GetString("TypeName"); - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Operations/EntityFieldOperation.cs b/Extensions/Xtensive.Orm.Operations/Operations/EntityFieldOperation.cs similarity index 62% rename from Orm/Xtensive.Orm/Orm/Operations/EntityFieldOperation.cs rename to Extensions/Xtensive.Orm.Operations/Operations/EntityFieldOperation.cs index cc82032fcf..831337f984 100644 --- a/Orm/Xtensive.Orm/Orm/Operations/EntityFieldOperation.cs +++ b/Extensions/Xtensive.Orm.Operations/Operations/EntityFieldOperation.cs @@ -5,9 +5,7 @@ // Created: 2009.11.19 using System; -using System.Runtime.Serialization; -using System.Security; -using System.Security.Permissions; +using System.Text.Json.Serialization; using Xtensive.Core; using Xtensive.Orm.Model; @@ -17,15 +15,16 @@ namespace Xtensive.Orm.Operations /// /// Describes an operation with field. /// - [Serializable] public abstract class EntityFieldOperation : EntityOperation { /// /// Gets the field involved into the operation. /// + [JsonInclude] public FieldInfo Field { get; private set; } /// + [JsonIgnore] public override string Description { get { @@ -46,23 +45,5 @@ protected EntityFieldOperation(Key key, FieldInfo field) { Field = field ?? throw new ArgumentNullException(nameof(field)); } - - // Serialization - - /// - protected EntityFieldOperation(SerializationInfo info, StreamingContext context) - : base(info, context) - { - var session = Session.Demand(); - var fieldRef = (FieldInfoRef)info.GetValue("field", typeof(FieldInfoRef)); - Field = fieldRef.Resolve(session.Domain.Model); - } - - /// - protected override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddValue("field", new FieldInfoRef(Field), typeof(FieldInfoRef)); - } } } \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.Operations/Operations/EntityFieldSetOperation.cs b/Extensions/Xtensive.Orm.Operations/Operations/EntityFieldSetOperation.cs new file mode 100644 index 0000000000..41b9cbb741 --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations/Operations/EntityFieldSetOperation.cs @@ -0,0 +1,212 @@ +// Copyright (C) 2009-2020 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Alexis Kochetov +// Created: 2009.10.22 + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json.Serialization; +using Xtensive.Orm.Model; +using Xtensive.Orm.Operations.Interfaces; +using Xtensive.Orm.Operations.Serialization.Json; +using Tuple = Xtensive.Tuples.Tuple; + +namespace Xtensive.Orm.Operations +{ + /// + /// Describes field set operation. + /// + public sealed class EntityFieldSetOperation : EntityFieldOperation + { + [JsonIgnore] + private IReadOnlyList nestedOperations = Array.Empty(); + + /// + /// Gets the new field value, if field is NOT a reference field + /// (i.e. not a field of type). + /// + [JsonInclude] + public object Value { get; set; } + + /// + /// Gets the new field value key, if field is a reference field + /// (i.e. field of type). + /// + [JsonInclude] + public Key ValueKey { get; set; } + + /// + [JsonIgnore] + public override string Title { + get { return "Set field"; } + } + + /// + [JsonIgnore] + public override string Description { + get + { + if (!IsStructure) + return $"{base.Description}, Value = {Value ?? ValueKey}"; + else { + return $"{base.Description}, Values = [{string.Join("," + Environment.NewLine, NestedOperations.Select(n => n.Description))}]"; + } + } + } + + /// + /// Describes whether changed field is reference field. + /// If , ValueKey property defines referenced entity key. + /// + [JsonIgnore] + public bool IsReference => Field.IsEntity; + + /// + /// Describes whether changed field is field. + /// If , both Value and ValueKey property will be and NestedOperations will contain actual operations. + /// + [JsonIgnore] + public bool IsStructure => Field.IsStructure; + + /// + /// In case of setting a field of persistent structure type, declared in Entity, it contains actual operations with Entity fields. + /// + [JsonInclude] + [JsonConverter(typeof(CollectionOfOperationsConverter))] + public IReadOnlyList NestedOperations + { + get { return nestedOperations; } + private set { + nestedOperations = (value.Count == 0) ? Array.Empty() : value; + } + } + + /// + protected override void PrepareSelf(OperationExecutionContext context) + { + base.PrepareSelf(context); + // Next line works properly when ValueKey==null + context.RegisterKey(context.TryRemapKey(ValueKey), false); + foreach(var nested in NestedOperations.OfType()) { + nested.Prepare(context); + } + } + + /// + protected override void ExecuteSelf(OperationExecutionContext context) + { + if (IsStructure) { + foreach (var nested in NestedOperations.OfType()) { + nested.Execute(context); + } + } + else { + var session = context.Session; + var key = context.TryRemapKey(Key); + var valueKey = context.TryRemapKey(ValueKey); + var entity = session.Query.Single(key); + var value = IsReference ? session.Query.Single(valueKey) : Value; + context.EntityAccessor.SetFieldValue(entity, Field, value); + //entity.SetFieldValue(Field, value); + } + } + + /// + protected override Operation CloneSelf(Operation clone) + { + if (clone == null) { + if (this.IsReference) { + clone = new EntityFieldSetOperation(Key, Field, ValueKey); + } + else if (this.IsStructure) { + + var clonedNestedOperations = new IOperation[this.NestedOperations.Count]; + var i = 0; + foreach (var nested in this.nestedOperations) { + clonedNestedOperations[i++] = nested.Clone(false); + } + + clone = new EntityFieldSetOperation(Key, Field, clonedNestedOperations); + } + else + clone = new EntityFieldSetOperation(Key, Field, Value); + } + return clone; + } + + + // Constructors + + /// + /// Initializes a new instance of this class.. + /// + /// The key of the changed entity. + /// The field involved into the operation. + /// The new field value. + public EntityFieldSetOperation(Key key, FieldInfo field, object value) + : base(key, field) + { + if (value is IEntity entityValue) { + ValueKey = entityValue.Key; + } + else if (value is Structure structure) { + + // when update Entity.SomeStructure field we treat the update as series of single-field updates + var structureType = structure.Session.Domain.Model.Types[value.GetType()]; + var ownerType = key.TypeInfo; + + var nOperations = new IOperation[structureType.Fields.Count]; + var i = 0; + foreach (var strField in structureType.Fields) { + var mappedEntityField = ownerType.StructureFieldMapping[new Core.Pair(field, strField)]; + var structFieldValue = structure[strField.Name]; + nOperations[i++] = new EntityFieldSetOperation(key, mappedEntityField, structFieldValue); + } + nestedOperations = nOperations.AsReadOnly(); + + // temporary; + //Value = value; + } + else { + Value = value; + } + } + + /// + /// Initializes a new instance of this class.. + /// + /// The key of the changed entity. + /// The field involved into the operation. + /// The new field value key. + public EntityFieldSetOperation(Key key, FieldInfo field, Key valueKey) + : base(key, field) + { + ValueKey = valueKey; + } + + + /// + /// Cloning only. + /// + private EntityFieldSetOperation(Key key, FieldInfo field, IReadOnlyList nestedOperations) + : base(key, field) + { + if (!field.IsStructure) + throw new InvalidOperationException(); + this.nestedOperations = nestedOperations; + } + + [JsonConstructor] + [System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("Style", "IDE0051")] + private EntityFieldSetOperation(Key key, FieldInfo field, object value, Key valueKey) + : base(key, field) + { + if (field.IsEntity) + ValueKey = valueKey; + else + Value = value; + } + } +} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Operations/EntityInitializeOperation.cs b/Extensions/Xtensive.Orm.Operations/Operations/EntityInitializeOperation.cs similarity index 80% rename from Orm/Xtensive.Orm/Orm/Operations/EntityInitializeOperation.cs rename to Extensions/Xtensive.Orm.Operations/Operations/EntityInitializeOperation.cs index 1d15fa9735..1d22bab312 100644 --- a/Orm/Xtensive.Orm/Orm/Operations/EntityInitializeOperation.cs +++ b/Extensions/Xtensive.Orm.Operations/Operations/EntityInitializeOperation.cs @@ -5,8 +5,7 @@ // Created: 2010.08.11 using System; -using System.Diagnostics; -using System.Runtime.Serialization; +using System.Text.Json.Serialization; namespace Xtensive.Orm.Operations { @@ -15,10 +14,10 @@ namespace Xtensive.Orm.Operations /// Actually, does nothing - it is used to suppress nested /// system operations. /// - [Serializable] public class EntityInitializeOperation : EntityOperation { /// + [JsonIgnore] public override string Title { get { return "Initialize entity"; } } @@ -45,13 +44,5 @@ public EntityInitializeOperation(Key key) : base(key) { } - - // Serialization - - /// - protected EntityInitializeOperation(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Operations/EntityOperation.cs b/Extensions/Xtensive.Orm.Operations/Operations/EntityOperation.cs similarity index 74% rename from Orm/Xtensive.Orm/Orm/Operations/EntityOperation.cs rename to Extensions/Xtensive.Orm.Operations/Operations/EntityOperation.cs index bbcb6251a5..74236d32d1 100644 --- a/Orm/Xtensive.Orm/Orm/Operations/EntityOperation.cs +++ b/Extensions/Xtensive.Orm.Operations/Operations/EntityOperation.cs @@ -5,8 +5,6 @@ // Created: 2009.10.22 using System; -using System.Runtime.Serialization; -using System.Security.Permissions; using Xtensive.Core; @@ -15,7 +13,6 @@ namespace Xtensive.Orm.Operations /// /// Describes an operation with . /// - [Serializable] public abstract class EntityOperation : KeyOperation { // Constructors @@ -29,11 +26,5 @@ protected EntityOperation(Key key) { ArgumentNullException.ThrowIfNull(key); } - - /// - protected EntityOperation(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Operations/EntitySetClearOperation.cs b/Extensions/Xtensive.Orm.Operations/Operations/EntitySetClearOperation.cs similarity index 78% rename from Orm/Xtensive.Orm/Orm/Operations/EntitySetClearOperation.cs rename to Extensions/Xtensive.Orm.Operations/Operations/EntitySetClearOperation.cs index 57f586d3a2..be1a9fc238 100644 --- a/Orm/Xtensive.Orm/Orm/Operations/EntitySetClearOperation.cs +++ b/Extensions/Xtensive.Orm.Operations/Operations/EntitySetClearOperation.cs @@ -5,7 +5,7 @@ // Created: 2010.02.25 using System; -using System.Runtime.Serialization; +using System.Text.Json.Serialization; using Xtensive.Orm.Model; namespace Xtensive.Orm.Operations @@ -13,10 +13,10 @@ namespace Xtensive.Orm.Operations /// /// Describes creation operation. /// - [Serializable] - public class EntitySetClearOperation : EntitySetOperation + public sealed class EntitySetClearOperation : EntitySetOperation { /// + [JsonIgnore] public override string Title { get { return "Clear entity set"; } } @@ -43,11 +43,5 @@ public EntitySetClearOperation(Key key, FieldInfo field) : base(key, field) { } - - /// - protected EntitySetClearOperation(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Operations/EntitySetItemAddOperation.cs b/Extensions/Xtensive.Orm.Operations/Operations/EntitySetItemAddOperation.cs similarity index 77% rename from Orm/Xtensive.Orm/Orm/Operations/EntitySetItemAddOperation.cs rename to Extensions/Xtensive.Orm.Operations/Operations/EntitySetItemAddOperation.cs index 2b2b392a76..7032fc3823 100644 --- a/Orm/Xtensive.Orm/Orm/Operations/EntitySetItemAddOperation.cs +++ b/Extensions/Xtensive.Orm.Operations/Operations/EntitySetItemAddOperation.cs @@ -5,7 +5,7 @@ // Created: 2010.02.25 using System; -using System.Runtime.Serialization; +using System.Text.Json.Serialization; using Xtensive.Orm.Model; namespace Xtensive.Orm.Operations @@ -13,10 +13,10 @@ namespace Xtensive.Orm.Operations /// /// Describes item add operation. /// - [Serializable] - public class EntitySetItemAddOperation : EntitySetItemOperation + public sealed class EntitySetItemAddOperation : EntitySetItemOperation { /// + [JsonIgnore] public override string Title { get { return "Add item to entity set"; } } @@ -26,7 +26,9 @@ protected override void ExecuteSelf(OperationExecutionContext context) { var session = context.Session; var item = session.Query.Single(context.TryRemapKey(ItemKey)); - GetEntitySet(context).Add(item); + _ = context.EntitySetAccessor.Add(GetEntitySet(context), item); + + //GetEntitySet(context).Add(item); } /// @@ -44,11 +46,5 @@ public EntitySetItemAddOperation(Key key, FieldInfo field, Key itemKey) : base(key, field, itemKey) { } - - /// - protected EntitySetItemAddOperation(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Operations/EntitySetItemOperation.cs b/Extensions/Xtensive.Orm.Operations/Operations/EntitySetItemOperation.cs similarity index 67% rename from Orm/Xtensive.Orm/Orm/Operations/EntitySetItemOperation.cs rename to Extensions/Xtensive.Orm.Operations/Operations/EntitySetItemOperation.cs index 6c155b0f8d..f33527e986 100644 --- a/Orm/Xtensive.Orm/Orm/Operations/EntitySetItemOperation.cs +++ b/Extensions/Xtensive.Orm.Operations/Operations/EntitySetItemOperation.cs @@ -5,27 +5,27 @@ // Created: 2009.10.22 using System; -using System.Runtime.Serialization; -using System.Security; -using System.Security.Permissions; +using System.Text.Json.Serialization; using Xtensive.Core; using Xtensive.Orm.Model; +using Xtensive.Orm.Operations.Serialization.Json; namespace Xtensive.Orm.Operations { /// /// Describes an operation with item. /// - [Serializable] public abstract class EntitySetItemOperation : EntitySetOperation { /// /// Gets the key of the involved item. /// + [JsonInclude] public Key ItemKey { get; set; } /// + [JsonIgnore] public override string Description { get { @@ -54,22 +54,5 @@ protected EntitySetItemOperation(Key key, FieldInfo field, Key itemKey) { ItemKey = itemKey ?? throw new ArgumentNullException(nameof(itemKey)); } - - // Serialization - - /// - protected override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddValue("ItemKey", ItemKey.Format()); - } - - /// - protected EntitySetItemOperation(SerializationInfo info, StreamingContext context) - : base(info, context) - { - ItemKey = Key.Parse(Domain.Demand(), info.GetString("ItemKey")); -// ItemKey.TypeReference = new TypeReference(ItemKey.TypeReference.Type, TypeReferenceAccuracy.ExactType); - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Operations/EntitySetItemRemoveOperation.cs b/Extensions/Xtensive.Orm.Operations/Operations/EntitySetItemRemoveOperation.cs similarity index 76% rename from Orm/Xtensive.Orm/Orm/Operations/EntitySetItemRemoveOperation.cs rename to Extensions/Xtensive.Orm.Operations/Operations/EntitySetItemRemoveOperation.cs index 6b905898f6..29b2a072c4 100644 --- a/Orm/Xtensive.Orm/Orm/Operations/EntitySetItemRemoveOperation.cs +++ b/Extensions/Xtensive.Orm.Operations/Operations/EntitySetItemRemoveOperation.cs @@ -5,7 +5,7 @@ // Created: 2010.02.25 using System; -using System.Runtime.Serialization; +using System.Text.Json.Serialization; using Xtensive.Orm.Model; namespace Xtensive.Orm.Operations @@ -13,10 +13,10 @@ namespace Xtensive.Orm.Operations /// /// Describes item add operation. /// - [Serializable] - public class EntitySetItemRemoveOperation : EntitySetItemOperation + public sealed class EntitySetItemRemoveOperation : EntitySetItemOperation { /// + [JsonIgnore] public override string Title { get { return "Remove item from entity set"; } } @@ -26,7 +26,7 @@ protected override void ExecuteSelf(OperationExecutionContext context) { var session = context.Session; var item = session.Query.Single(context.TryRemapKey(ItemKey)); - GetEntitySet(context).Remove(item); + _ = context.EntitySetAccessor.Remove(GetEntitySet(context), item); } /// @@ -44,11 +44,5 @@ public EntitySetItemRemoveOperation(Key key, FieldInfo field, Key itemKey) : base(key, field, itemKey) { } - - /// - protected EntitySetItemRemoveOperation(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Operations/EntitySetOperation.cs b/Extensions/Xtensive.Orm.Operations/Operations/EntitySetOperation.cs similarity index 74% rename from Orm/Xtensive.Orm/Orm/Operations/EntitySetOperation.cs rename to Extensions/Xtensive.Orm.Operations/Operations/EntitySetOperation.cs index c17dc0c681..c24111e5bf 100644 --- a/Orm/Xtensive.Orm/Orm/Operations/EntitySetOperation.cs +++ b/Extensions/Xtensive.Orm.Operations/Operations/EntitySetOperation.cs @@ -5,8 +5,6 @@ // Created: 2009.11.20 using System; -using System.Runtime.Serialization; -using Xtensive.Orm.Internals; using Xtensive.Orm.Model; using Xtensive.Reflection; @@ -16,7 +14,6 @@ namespace Xtensive.Orm.Operations /// /// Describes an operation with field of type. /// - [Serializable] public abstract class EntitySetOperation : EntityFieldOperation { /// @@ -29,7 +26,7 @@ public EntitySetBase GetEntitySet(OperationExecutionContext context) var session = context.Session; var key = context.TryRemapKey(Key); var target = session.Query.Single(key); - return (EntitySetBase) target.GetFieldValue(Field); + return context.EntitySetAccessor.GetEntitySet(target, Field); } @@ -51,18 +48,10 @@ protected EntitySetOperation(Key key, FieldInfo field) fieldType = field.UnderlyingProperty.PropertyType; var name = field.UnderlyingProperty.GetShortName(true); } - - if (!WellKnownOrmTypes.EntitySetBase.IsAssignableFrom(fieldType)) - throw new ArgumentOutOfRangeException( - Strings.ExTypeOfXMustBeADescendantOfYType, - fieldName, - WellKnownOrmTypes.EntitySetBase.Name); - } - /// - protected EntitySetOperation(SerializationInfo info, StreamingContext context) - : base(info, context) - { + if (!WellKnownTypes.EntitySetBase.IsAssignableFrom(fieldType)) + throw new ArgumentOutOfRangeException( + $"Type of {fieldName} must be a descendant of {WellKnownTypes.EntitySetBase.GetShortName()} type"); } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Operations/KeyGenerateOperation.cs b/Extensions/Xtensive.Orm.Operations/Operations/KeyGenerateOperation.cs similarity index 93% rename from Orm/Xtensive.Orm/Orm/Operations/KeyGenerateOperation.cs rename to Extensions/Xtensive.Orm.Operations/Operations/KeyGenerateOperation.cs index 35f0507925..8c82e63313 100644 --- a/Orm/Xtensive.Orm/Orm/Operations/KeyGenerateOperation.cs +++ b/Extensions/Xtensive.Orm.Operations/Operations/KeyGenerateOperation.cs @@ -6,7 +6,7 @@ using System; using System.Linq; -using System.Runtime.Serialization; +using System.Text.Json.Serialization; using Xtensive.Core; using Xtensive.Tuples; using Tuple = Xtensive.Tuples.Tuple; @@ -16,10 +16,10 @@ namespace Xtensive.Orm.Operations /// /// Describes key generation operation. /// - [Serializable] public sealed class KeyGenerateOperation : KeyOperation { /// + [JsonIgnore] public override string Title { get { return "Generate Key"; } } @@ -40,7 +40,7 @@ private void MapNewKey(OperationExecutionContext context) { var domain = context.Session.Domain; if (Key.IsTemporary(domain)) { - var mappedKey = Key.Generate(context.Session, Key.TypeInfo); + var mappedKey = Key.Generate(context.Session, Key.ResolveTypeInfo(context.Session).UnderlyingType); context.AddKeyMapping(Key, mappedKey); } } @@ -111,11 +111,5 @@ public KeyGenerateOperation(Key key) { ArgumentNullException.ThrowIfNull(key); } - - /// - private KeyGenerateOperation(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.Operations/Operations/KeyOperation.cs b/Extensions/Xtensive.Orm.Operations/Operations/KeyOperation.cs new file mode 100644 index 0000000000..c82c48e165 --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations/Operations/KeyOperation.cs @@ -0,0 +1,50 @@ +// Copyright (C) 2003-2010 Xtensive LLC. +// All rights reserved. +// For conditions of distribution and use, see license. +// Created by: Alexis Kochetov +// Created: 2009.10.22 + +using System; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.Operations +{ + /// + /// Describes an operation involving the . + /// + public abstract class KeyOperation : Operation + { + /// + /// Gets the key of the entity. + /// + [JsonInclude] + public Key Key { get; private set; } + + /// + [JsonIgnore] + public override string Description { + get + { + return $"{Title}, Key = {Key}"; + } + } + + /// + protected override void PrepareSelf(OperationExecutionContext context) + { + context.RegisterKey(context.TryRemapKey(Key), false); + } + + + // Constructors + + /// + /// Initializes a new instance of this class.. + /// + /// The key of the entity. + protected KeyOperation(Key key) + { + Key = key; + } + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.Operations/Operations/KeySetOperation.cs b/Extensions/Xtensive.Orm.Operations/Operations/KeySetOperation.cs new file mode 100644 index 0000000000..454b6c3786 --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations/Operations/KeySetOperation.cs @@ -0,0 +1,65 @@ +// Copyright (C) 2003-2010 Xtensive LLC. +// All rights reserved. +// For conditions of distribution and use, see license. +// Created by: Alex Yakunin +// Created: 2010.08.10 + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json.Serialization; +using Xtensive.Core; + + +namespace Xtensive.Orm.Operations +{ + /// + /// Describes operation over key set. + /// + public abstract class KeySetOperation : Operation + { + /// + [JsonIgnore] + public override string Description { + get + { + return $"{Title}:{Environment.NewLine}{Keys.ToDelimitedString(Environment.NewLine).Indent(2)}"; + } + } + + /// + /// Gets the key set. + /// + [JsonInclude] + public IReadOnlyList Keys { get; } + + /// + protected override void PrepareSelf(OperationExecutionContext context) + { + foreach (var key in Keys) + context.RegisterKey(context.TryRemapKey(key), false); + } + + + // Constructors + + /// + public KeySetOperation(Key key) + { + Keys = new[] { key }.AsReadOnly(); + } + + /// + /// Initializes a new instance of this class. + /// + /// The sequence of keys. + public KeySetOperation(IReadOnlyList keys) + { + ArgumentNullException.ThrowIfNull(keys); + if (keys.Count == 0) + throw new ArgumentException("Keys collection must have at least 1 item"); + + Keys = keys; + } + } +} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Operations/MethodCallOperation.cs b/Extensions/Xtensive.Orm.Operations/Operations/MethodCallOperation.cs similarity index 90% rename from Orm/Xtensive.Orm/Orm/Operations/MethodCallOperation.cs rename to Extensions/Xtensive.Orm.Operations/Operations/MethodCallOperation.cs index dcd184234f..1955e96bcb 100644 --- a/Orm/Xtensive.Orm/Orm/Operations/MethodCallOperation.cs +++ b/Extensions/Xtensive.Orm.Operations/Operations/MethodCallOperation.cs @@ -6,7 +6,6 @@ using System; using Xtensive.Core; - using Xtensive.Reflection; namespace Xtensive.Orm.Operations @@ -14,7 +13,7 @@ namespace Xtensive.Orm.Operations /// /// Describes arbitrary method call operation. /// - [Serializable] + // Can't be serialized because of Actions public sealed class MethodCallOperation : Operation { private readonly Action prepareAction; @@ -24,26 +23,17 @@ public sealed class MethodCallOperation : Operation /// /// Gets the method action. /// - public Action PrepareAction - { - get { return prepareAction; } - } + public Action PrepareAction => prepareAction; /// /// Gets the method action. /// - public Action ExecuteAction - { - get { return executeAction; } - } + public Action ExecuteAction => executeAction; /// /// Gets the arguments. /// - public object[] Arguments - { - get { return arguments; } - } + public object[] Arguments => arguments; /// public override string Title { @@ -60,8 +50,7 @@ public override string Description { /// protected override void PrepareSelf(OperationExecutionContext context) { - if (prepareAction!=null) - prepareAction.Invoke(context, arguments); + prepareAction?.Invoke(context, arguments); } /// @@ -73,7 +62,7 @@ protected override void ExecuteSelf(OperationExecutionContext context) /// protected override Operation CloneSelf(Operation clone) { - if (clone==null) + if (clone is null) clone = new MethodCallOperation(prepareAction, executeAction, arguments); return clone; } diff --git a/Orm/Xtensive.Orm/Orm/Operation.cs b/Extensions/Xtensive.Orm.Operations/Operations/Operation.cs similarity index 62% rename from Orm/Xtensive.Orm/Orm/Operation.cs rename to Extensions/Xtensive.Orm.Operations/Operations/Operation.cs index 06d25b69b3..99c7b5012b 100644 --- a/Orm/Xtensive.Orm/Orm/Operation.cs +++ b/Extensions/Xtensive.Orm.Operations/Operations/Operation.cs @@ -9,80 +9,112 @@ using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; +using System.Text.Json.Serialization; using Xtensive.Core; +using Xtensive.Orm.Operations.Interfaces; +using Xtensive.Orm.Operations.Serialization.Json; -using Xtensive.Orm.Operations; - -namespace Xtensive.Orm +namespace Xtensive.Orm.Operations { /// /// Base abstract class for all implementors. /// [DebuggerDisplay("Description = {Description}")] - [Serializable] - public abstract class Operation : IOperation + [JsonDerivedType(typeof(EntitiesRemoveOperation), nameof(EntitiesRemoveOperation))] + [JsonDerivedType(typeof(EntityCreateOperation), nameof(EntityCreateOperation))] + [JsonDerivedType(typeof(EntityFieldSetOperation), nameof(EntityFieldSetOperation))] + [JsonDerivedType(typeof(EntityInitializeOperation), nameof(EntityInitializeOperation))] + [JsonDerivedType(typeof(EntitySetClearOperation), nameof(EntitySetClearOperation))] + [JsonDerivedType(typeof(EntitySetItemAddOperation), nameof(EntitySetItemAddOperation))] + [JsonDerivedType(typeof(EntitySetItemRemoveOperation), nameof(EntitySetItemRemoveOperation))] + [JsonDerivedType(typeof(KeyGenerateOperation), nameof(KeyGenerateOperation))] + [JsonDerivedType(typeof(MethodCallOperation), nameof(MethodCallOperation))] + [JsonDerivedType(typeof(ValidateVersionOperation), nameof(ValidateVersionOperation))] + public abstract class Operation : IOperation, IExecutableOperation { - private static readonly IReadOnlyDictionary EmptyIdentifiedEntities = - new ReadOnlyDictionary(new Dictionary()); + private static readonly IReadOnlyDictionary EmptyIdentifiedEntities = new Dictionary().AsReadOnly(); + [JsonIgnore] private IReadOnlyDictionary identifiedEntities = EmptyIdentifiedEntities; + [JsonIgnore] private IReadOnlyList precedingOperations = Array.Empty(); + [JsonIgnore] private IReadOnlyList followingOperations = Array.Empty(); + [JsonIgnore] private IReadOnlyList undoOperations = Array.Empty(); /// + [JsonIgnore] public abstract string Title { get; } /// + [JsonIgnore] public virtual string Description { get { return Title; } } /// + [JsonInclude] public OperationType Type { get; internal set; } /// + [JsonInclude] + [JsonConverter(typeof(CollectionOfOperationsConverter))] public IReadOnlyList PrecedingOperations { get { return precedingOperations; } - internal set { precedingOperations = value; } + internal set { precedingOperations = (value.Count == 0) ? Array.Empty() : value; } } /// + [JsonInclude] + [JsonConverter(typeof(CollectionOfOperationsConverter))] public IReadOnlyList FollowingOperations { get { return followingOperations; } - internal set { followingOperations = value; } + internal set { followingOperations = (value.Count == 0) ? Array.Empty(): value ; } } /// + [JsonInclude] + [JsonConverter(typeof(CollectionOfOperationsConverter))] public IReadOnlyList UndoOperations { get { return undoOperations; } - internal set { undoOperations = value; } + internal set { undoOperations = (value.Count == 0) ? Array.Empty() : value; } } /// + [JsonInclude] + [JsonConverter(typeof(CollectionOfIdentifiedEntitiesConverter))] public IReadOnlyDictionary IdentifiedEntities { get { return identifiedEntities; } - set { identifiedEntities = value; } + set { identifiedEntities = value.Count==0 ? EmptyIdentifiedEntities : value; } } /// public void Prepare(OperationExecutionContext context) { - foreach (var operation in PrecedingOperations) - operation.Prepare(context); + foreach (var operation in PrecedingOperations.Cast()) { + if (operation is not null) + operation.Prepare(context); + } PrepareSelf(context); - foreach (var operation in FollowingOperations) - operation.Prepare(context); + foreach (var operation in FollowingOperations.Cast()) { + if (operation is not null) + operation.Prepare(context); + } } /// public void Execute(OperationExecutionContext context) { - foreach (var operation in PrecedingOperations) - operation.Execute(context); + foreach (var operation in PrecedingOperations.Cast()) { + if (operation is not null) + operation.Execute(context); + } ExecuteSelf(context); - foreach (var operation in FollowingOperations) - operation.Execute(context); + foreach (var operation in FollowingOperations.Cast()) { + if (operation is not null) + operation.Execute(context); + } } /// diff --git a/Orm/Xtensive.Orm/Orm/Operations/ValidateVersionOperation.cs b/Extensions/Xtensive.Orm.Operations/Operations/ValidateVersionOperation.cs similarity index 72% rename from Orm/Xtensive.Orm/Orm/Operations/ValidateVersionOperation.cs rename to Extensions/Xtensive.Orm.Operations/Operations/ValidateVersionOperation.cs index f7ff94ede6..f9c41f94c9 100644 --- a/Orm/Xtensive.Orm/Orm/Operations/ValidateVersionOperation.cs +++ b/Extensions/Xtensive.Orm.Operations/Operations/ValidateVersionOperation.cs @@ -5,44 +5,46 @@ // Created: 2010.02.19 using System; -using System.Runtime.Serialization; -using System.Security; -using System.Security.Permissions; +using System.Text.Json.Serialization; using Xtensive.Core; -using Xtensive.Orm.Logging; - - +using Xtensive.Orm.Operations.Interfaces; +using Xtensive.Orm.Operations.Serialization.Json; namespace Xtensive.Orm.Operations { /// /// Describes version validation operation. /// - [Serializable] public sealed class ValidateVersionOperation : EntityOperation, IUniqueOperation { /// /// Gets the original version of . /// + [JsonInclude] + [JsonConverter(typeof(VersionInfoConverter))] public VersionInfo Version { get; private set; } /// + [JsonIgnore] public bool IgnoreIfDuplicate { get { return true; } } /// + [JsonIgnore] public object Identifier { get { return Key; } } /// + [JsonIgnore] public override string Title { get { return "Validate version"; } } /// + [JsonIgnore] public override string Description { get { @@ -63,11 +65,11 @@ protected override void ExecuteSelf(OperationExecutionContext context) var session = context.Session; var entity = session.Query.Single(Key); if (entity.VersionInfo != Version) { - if (OrmLog.IsLogged(LogLevel.Info)) - OrmLog.Info(nameof(Strings.LogSessionXVersionValidationFailedKeyYVersionZExpected3), - session, Key, entity.VersionInfo, Version); + //if (OrmLog.IsLogged(LogLevel.Info)) + // OrmLog.Info(nameof(Strings.LogSessionXVersionValidationFailedKeyYVersionZExpected3), + // session, Key, entity.VersionInfo, Version); throw new VersionConflictException( - string.Format(Strings.ExVersionOfEntityWithKeyXDiffersFromTheExpectedOne, Key)); + string.Format("Version of entity with key '{0}' differs from the expected one.", Key)); } } @@ -87,26 +89,12 @@ protected override Operation CloneSelf(Operation clone) /// /// The key of the . /// The original version. + [JsonConstructor] public ValidateVersionOperation(Key key, VersionInfo version) : base(key) { ArgumentValidator.EnsureArgumentIsNotDefault(version, nameof(version)); Version = version; } - - // Serialization - - /// - public ValidateVersionOperation(SerializationInfo info, StreamingContext context) - : base(info, context) - { - Version = (VersionInfo) info.GetValue("Version", typeof (VersionInfo)); - } - - /// - protected override void GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue("Version", Version); - } } } \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.Operations/Properties/Visibility.cs b/Extensions/Xtensive.Orm.Operations/Properties/Visibility.cs new file mode 100644 index 0000000000..b28791e72b --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations/Properties/Visibility.cs @@ -0,0 +1,12 @@ +// Copyright (C) 2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Xtensive.Orm.Operations.Tests, PublicKey=" + +"00240000048000009400000006020000002400005253413100040000010001007f8790a0573a2a" + +"4f7b77907240977b669d33774bcaef77ef39d5186de4d4c836623fb661be674c7db731bc376184" + +"f6848fc6b64eeba506654c8212de624e9d1f15ad1fe765f769e9a5b59ecaab2866632a983e7828" + +"f3bf20ff7afffa021951cf8adc9ac1e786716430b0637893fb71b7566405fe14acc5e340c4af4a" + +"a293c994")] \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.Operations/Serialization/Json/Converters/CollectionOfIdentifiedEntitiesConverter.cs b/Extensions/Xtensive.Orm.Operations/Serialization/Json/Converters/CollectionOfIdentifiedEntitiesConverter.cs new file mode 100644 index 0000000000..3d3cdc17b4 --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations/Serialization/Json/Converters/CollectionOfIdentifiedEntitiesConverter.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.Operations.Serialization.Json +{ + /// + /// Converter for collection of identified entities. + /// + public sealed class CollectionOfIdentifiedEntitiesConverter : JsonConverter> + { + /// + public override IReadOnlyDictionary Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var dictionary = JsonSerializer.Deserialize>(ref reader, options); + if (dictionary == null) { + return null; + } + if (dictionary.Count == 0) + return new Dictionary();// property rewrites empty collections with internal empty instance + + return dictionary.AsReadOnly(); + } + + /// + public override void Write(Utf8JsonWriter writer, IReadOnlyDictionary value, JsonSerializerOptions options) + { + if (value == null) { + throw new ArgumentNullException("value"); + } + + var arrayToWrite = value.Count == 0 + ? new Dictionary() + : value.ToDictionary(); + JsonSerializer.Serialize>(writer, arrayToWrite, options); + } + } +} diff --git a/Extensions/Xtensive.Orm.Operations/Serialization/Json/Converters/CollectionOfOperationsConverter.cs b/Extensions/Xtensive.Orm.Operations/Serialization/Json/Converters/CollectionOfOperationsConverter.cs new file mode 100644 index 0000000000..c6c94f93fb --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations/Serialization/Json/Converters/CollectionOfOperationsConverter.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.Operations.Serialization.Json +{ + /// + /// Converter for collection of operations. + /// + public sealed class CollectionOfOperationsConverter : JsonConverter> + { + /// + public override IReadOnlyList Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var array = JsonSerializer.Deserialize(ref reader, options); + if (array == null) { + return null; + } + if (array.Length == 0) + return Array.Empty(); + return array.Cast().ToArray().AsReadOnly(); + } + + /// + public override void Write(Utf8JsonWriter writer, IReadOnlyList value, JsonSerializerOptions options) + { + if (value == null) { + throw new ArgumentNullException("value"); + } + var arrayToWrite = value.Count == 0 + ? Array.Empty() + : value.Cast().ToArray(); + JsonSerializer.Serialize(writer, arrayToWrite, options); + } + } +} diff --git a/Extensions/Xtensive.Orm.Operations/Serialization/Json/Converters/FieldInfoConverter.cs b/Extensions/Xtensive.Orm.Operations/Serialization/Json/Converters/FieldInfoConverter.cs new file mode 100644 index 0000000000..b598e1497e --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations/Serialization/Json/Converters/FieldInfoConverter.cs @@ -0,0 +1,71 @@ +// Copyright (C) 2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System; +using System.Text.Json; +using System.Text.Json.Serialization; +using FieldInfo = Xtensive.Orm.Model.FieldInfo; + + +namespace Xtensive.Orm.Operations.Serialization.Json +{ + /// + /// Json converter for . + /// + /// Domain, required for deserialization. + public sealed class FieldInfoConverter(Domain domain) : JsonConverter + { + private readonly Domain domain = domain; + + /// + public override FieldInfo Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + reader.EnsureStartObject(); + + _ = reader.Read(); + if (reader.TokenType is not JsonTokenType.PropertyName) + throw JsonExceptions.WrongStructurePropertyExpected(); + var propertyName = reader.GetString(); + if (propertyName != options.ApplyNamingPolicy(nameof(FieldInfo.ReflectedType))) + throw JsonExceptions.WrongStructurePropertyNameExpected(options.ApplyNamingPolicy(nameof(FieldInfo.ReflectedType)), propertyName); + + _ = reader.Read(); + var reflecteTypeRaw = reader.GetString(); + var reflecteType = Type.GetType(reflecteTypeRaw); + if (reflecteType is null) + throw JsonExceptions.NoTypeForName(reflecteTypeRaw); + if (!domain.Model.Types.TryGetValue(reflecteType, out var typeInfo)) + throw new JsonException("Type Owner of the field belongs to different Domain than the one that provided to the converter."); + + _ = reader.Read(); + if (reader.TokenType is not JsonTokenType.PropertyName) + throw JsonExceptions.WrongStructurePropertyExpected(); + propertyName = reader.GetString(); + if (propertyName != options.ApplyNamingPolicy(nameof(FieldInfo.Name))) + throw JsonExceptions.WrongStructurePropertyNameExpected(options.ApplyNamingPolicy(nameof(FieldInfo.Name)), propertyName); + + _ = reader.Read(); + var name = reader.GetString(); + + _ = reader.Read(); + reader.EnsureEndObject(); + + if (!typeInfo.Fields.TryGetValue(name, out var field)) + throw new JsonException("Field is not found."); + + return field; + } + + /// + public override void Write(Utf8JsonWriter writer, FieldInfo value, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteString(nameof(FieldInfo.ReflectedType), value.ReflectedType.UnderlyingType.AssemblyQualifiedName); + writer.WriteString(options.ApplyNamingPolicy(nameof(FieldInfo.Name)), value.Name); + + writer.WriteEndObject(); + } + } +} diff --git a/Extensions/Xtensive.Orm.Operations/Serialization/Json/Converters/KeyConverterFactory.cs b/Extensions/Xtensive.Orm.Operations/Serialization/Json/Converters/KeyConverterFactory.cs new file mode 100644 index 0000000000..c9c50358a8 --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations/Serialization/Json/Converters/KeyConverterFactory.cs @@ -0,0 +1,52 @@ +// Copyright (C) 2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System; +using System.Text.Json; +using System.Text.Json.Serialization; + + +namespace Xtensive.Orm.Operations.Serialization.Json +{ + /// + /// Json converter factory for s. + /// + /// Domain, required for deserialization. + public class KeyConverterFactory(Domain domain) : JsonConverterFactory + { + #region Converters + private sealed class DefaultKeyConverter(Domain domain) : JsonConverter + { + private readonly Domain domain = domain; + + /// + public override Key Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var formattedKey = reader.GetString(); + return Key.Parse(domain, formattedKey); + } + + /// + public override void Write(Utf8JsonWriter writer, Key value, JsonSerializerOptions options) + { + writer.WriteStringValue(value.Format()); + } + } + + #endregion + + private readonly Domain domain = domain; + + /// + public override bool CanConvert(Type typeToConvert) => + typeToConvert.IsAssignableTo(typeof(Key)); + + /// + public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) + { + // there might be implementation of per-type converters + return new DefaultKeyConverter(domain); + } + } +} diff --git a/Extensions/Xtensive.Orm.Operations/Serialization/Json/Converters/ObjectToInferredTypesConverter.cs b/Extensions/Xtensive.Orm.Operations/Serialization/Json/Converters/ObjectToInferredTypesConverter.cs new file mode 100644 index 0000000000..64a479809d --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations/Serialization/Json/Converters/ObjectToInferredTypesConverter.cs @@ -0,0 +1,76 @@ +// Copyright (C) 2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System; +using System.Text.Json; +using System.Text.Json.Serialization; + + +namespace Xtensive.Orm.Operations.Serialization.Json +{ + /// + /// Json converter that helps to serialize/deserialize different values which are cast to object. + /// + public class ObjectToInferredTypesConverter : JsonConverter + { + private const string ActualValueProperty = "ActualValue"; + private const string ObjectTypeProperty = "ObjectType"; + + /// + public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + reader.EnsureStartObject(); + + var runtimeType = GetObjectType(ref reader, options); + + _ = reader.Read(); + if (reader.TokenType is not JsonTokenType.PropertyName) + throw JsonExceptions.WrongStructurePropertyExpected(); + var propertyName = reader.GetString(); + if (propertyName != options.ApplyNamingPolicy(ActualValueProperty)) + throw JsonExceptions.WrongStructurePropertyNameExpected(options.ApplyNamingPolicy(ActualValueProperty), propertyName); + var value = JsonSerializer.Deserialize(ref reader, runtimeType, options); + + _ = reader.Read(); + reader.EnsureEndObject(); + + return value; + } + + /// + public override void Write(Utf8JsonWriter writer, object objectToWrite, JsonSerializerOptions options) + { + var runtimeType = objectToWrite.GetType(); + if (runtimeType == typeof(object)) { + writer.WriteStartObject(); + writer.WriteEndObject(); + return; + } + writer.WriteStartObject(); + writer.WriteString(options.ApplyNamingPolicy(ObjectTypeProperty), runtimeType.AssemblyQualifiedName); + + writer.WritePropertyName(options.ApplyNamingPolicy(ActualValueProperty)); + JsonSerializer.Serialize(writer, objectToWrite, runtimeType, options); + + writer.WriteEndObject(); + } + + private static Type GetObjectType(ref Utf8JsonReader reader, JsonSerializerOptions options) + { + _ = reader.Read(); + if (reader.TokenType is not JsonTokenType.PropertyName) + throw JsonExceptions.WrongStructurePropertyExpected(); + + string propertyName = reader.GetString(); + if (propertyName != options.ApplyNamingPolicy(ObjectTypeProperty)) + throw JsonExceptions.WrongStructurePropertyNameExpected(options.ApplyNamingPolicy(ObjectTypeProperty), propertyName); + + _ = reader.Read(); + if (reader.TokenType is not JsonTokenType.String) + throw JsonExceptions.WrongStructure("Wrong type of return type property"); + var typeName = reader.GetString(); + return Type.GetType(typeName); + } + } +} diff --git a/Extensions/Xtensive.Orm.Operations/Serialization/Json/Converters/VersionInfoConverter.cs b/Extensions/Xtensive.Orm.Operations/Serialization/Json/Converters/VersionInfoConverter.cs new file mode 100644 index 0000000000..f4d60d297b --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations/Serialization/Json/Converters/VersionInfoConverter.cs @@ -0,0 +1,160 @@ +// Copyright (C) 2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System; +using System.Linq; +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Serialization; +using Xtensive.Core; +using Xtensive.Orm; +using Xtensive.Tuples; + + +namespace Xtensive.Orm.Operations.Serialization.Json +{ + /// + /// + /// + public class VersionInfoConverter : JsonConverter + { + private const string FieldTypesProperty = "FieldTypes"; + private const string FieldValuesProperty = "FieldValues"; + + private readonly PropertyInfo tupleAccessor = typeof(VersionInfo).GetProperty("Value", BindingFlags.Instance | BindingFlags.NonPublic); + + /// + public override VersionInfo Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + reader.EnsureStartObject(); + + _ = reader.Read(); + if (reader.TokenType is not JsonTokenType.PropertyName) + throw JsonExceptions.WrongStructurePropertyExpected(); + var propertyName = reader.GetString(); + if (propertyName != options.ApplyNamingPolicy(nameof(VersionInfo.IsVoid))) + throw JsonExceptions.WrongStructurePropertyNameExpected(options.ApplyNamingPolicy(nameof(VersionInfo.IsVoid)), propertyName); + _ = reader.Read(); + var isVoid = reader.GetBoolean(); + if (isVoid) { + reader.EnsureEndObject(); + return VersionInfo.Void; + } + + _ = reader.Read(); + if (reader.TokenType is not JsonTokenType.PropertyName) + throw JsonExceptions.WrongStructurePropertyExpected(); + propertyName = reader.GetString(); + if (propertyName != options.ApplyNamingPolicy(FieldTypesProperty)) + throw JsonExceptions.WrongStructurePropertyNameExpected(options.ApplyNamingPolicy(FieldTypesProperty), propertyName); + _ = reader.Read(); + var tupleTypes = JsonSerializer.Deserialize(ref reader, options); + + _ = reader.Read(); + if (reader.TokenType is not JsonTokenType.PropertyName) + throw JsonExceptions.WrongStructurePropertyExpected(); + propertyName = reader.GetString(); + if (propertyName != options.ApplyNamingPolicy(FieldValuesProperty)) + throw JsonExceptions.WrongStructurePropertyNameExpected(options.ApplyNamingPolicy(FieldValuesProperty), propertyName); + _ = reader.Read(); + var tupleValues = JsonSerializer.Deserialize(ref reader, options); + _ = reader.Read(); + reader.EnsureEndObject(); + + var descriptor = ToDescriptorFromSerializableForm(tupleTypes); + var tuple = ToTupleFromSerializableForm(descriptor, tupleValues); + + return new VersionInfo(tuple); + } + + /// + public override void Write(Utf8JsonWriter writer, VersionInfo value, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + writer.WriteBoolean(options.ApplyNamingPolicy(nameof(VersionInfo.IsVoid)), value.IsVoid); + + if (!value.IsVoid) { + var tuple = ExtractTuple(value); + + var fieldTypes = ToSerializableFormat(tuple.Descriptor); + var formattedTuple = ToSerializableFormat(tuple); + + writer.WritePropertyName(options.ApplyNamingPolicy(FieldTypesProperty)); + JsonSerializer.Serialize(writer, fieldTypes, options); + + writer.WritePropertyName(options.ApplyNamingPolicy(FieldValuesProperty)); + JsonSerializer.Serialize(writer, formattedTuple, options); + } + + writer.WriteEndObject(); + } + + + private Tuples.Tuple ExtractTuple(VersionInfo value) + { + var tuple = (Tuples.Tuple) tupleAccessor.GetValue(value); + return tuple.Clone(); + } + + private static string[] ToSerializableFormat(Xtensive.Tuples.Tuple tuple) + { + var rawFormat = tuple.Format(); + return rawFormat.Split(','); + } + + private static string[] ToSerializableFormat(TupleDescriptor descriptor) + { + var types = new string[descriptor.Count]; + for (int i = 0, count = descriptor.Count; i < count; i++) { + + var fieldType = descriptor[i]; + + // use simplyfied format for system types, which are always there and well-known + types[i] = (fieldType.IsArray && IsCoreDotNetType(fieldType.GetElementType())) || IsCoreDotNetType(fieldType) + ? fieldType.FullName + : descriptor[i].AssemblyQualifiedName; + } + return types; + + + static bool IsCoreDotNetType(Type type) + { + if (type.IsArray && IsCoreDotNetType(type.GetElementType()) + || (type.IsGenericType && type.GenericTypeArguments.All(static gt => IsCoreDotNetType(gt)))) { + return true; + } + + var assemblyName = type.Assembly.GetName().Name; + + return assemblyName.Equals("System.Private.CoreLib", StringComparison.Ordinal) + || assemblyName.Equals("mscorlib", StringComparison.Ordinal) + || assemblyName.Equals("System.Runtime", StringComparison.Ordinal); + } + } + + private static TupleDescriptor ToDescriptorFromSerializableForm(string[] fieldTypes) + { + var types = fieldTypes.Select(static st => Type.GetType(st)).ToArray(); + return TupleDescriptor.Create(types); + } + + private static Tuples.Tuple ToTupleFromSerializableForm(TupleDescriptor descriptor, string[] values) + { + var valuesString = string.Join(',', values); + return descriptor.Parse(valuesString); + } + } + + + internal static class TuplesExtesions + { + + + + + + + } +} diff --git a/Extensions/Xtensive.Orm.Operations/Serialization/Json/JsonExceptions.cs b/Extensions/Xtensive.Orm.Operations/Serialization/Json/JsonExceptions.cs new file mode 100644 index 0000000000..3d37fbe6f6 --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations/Serialization/Json/JsonExceptions.cs @@ -0,0 +1,29 @@ +// Copyright (C) 2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System.Text.Json; + + +namespace Xtensive.Orm.Operations.Serialization.Json +{ + /// + /// Produces most used s + /// + internal static class JsonExceptions + { + private const string WrongStructureExceptionTemplate = "Wrong Structure: {0}."; + + public static JsonException WrongStructure(string details) + => new JsonException(string.Format(WrongStructureExceptionTemplate, details)); + + public static JsonException WrongStructurePropertyExpected() + => WrongStructure("Property expected"); + + public static JsonException WrongStructurePropertyNameExpected(string expected, string actual) + => WrongStructure($"Property '{expected}' expected, but was '{actual}'"); + + public static JsonException NoTypeForName(string assemblyQualifiedName) + => new JsonException($"Can't resolve '{assemblyQualifiedName}' type name into System.Type instance."); + } +} diff --git a/Extensions/Xtensive.Orm.Operations/Serialization/Json/JsonSerializationExtensions.cs b/Extensions/Xtensive.Orm.Operations/Serialization/Json/JsonSerializationExtensions.cs new file mode 100644 index 0000000000..a1f14351cc --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations/Serialization/Json/JsonSerializationExtensions.cs @@ -0,0 +1,65 @@ +// Copyright (C) 2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System.Text.Json; + + +namespace Xtensive.Orm.Operations.Serialization.Json +{ + /// + /// Contains extension method that relate to serialization + /// + public static class JsonSerializationExtensions + { + /// + /// Adds to all available converters to serialize/deserialize operations. + /// + /// Options object to which converters should be added. + /// Domain instance for converters that require it. + /// object with registered converters. + public static JsonSerializerOptions AddOperationsConverters(this JsonSerializerOptions options, Domain domain) + { + options.Converters.Add(new KeyConverterFactory(domain)); + options.Converters.Add(new FieldInfoConverter(domain)); + options.Converters.Add(new ObjectToInferredTypesConverter()); + return options; + } + + /// + /// Applies (if such exists) to property name, + /// + /// The options + /// Unmodified property name. + /// Adjusted name, if policy exists, or the same value. + internal static string ApplyNamingPolicy(this JsonSerializerOptions options, string propertyName) + { + var policy = options.PropertyNamingPolicy; + if (policy == null) + return propertyName; + return options.PropertyNamingPolicy.ConvertName(propertyName); + } + + /// + /// Checks that Reader is in the position. + /// + /// The reader. + /// Reader token has different value + internal static void EnsureStartObject(this ref Utf8JsonReader reader) + { + if (reader.TokenType is not JsonTokenType.StartObject) + throw JsonExceptions.WrongStructure("Starting of object expected."); + } + + /// + /// Checks that Reader is in the position. + /// + /// The reader. + /// Reader token has different value + internal static void EnsureEndObject(this ref Utf8JsonReader reader) + { + if (reader.TokenType != JsonTokenType.EndObject) + throw JsonExceptions.WrongStructure("End of object expected."); + } + } +} diff --git a/Extensions/Xtensive.Orm.Operations/WellKnownTypes.cs b/Extensions/Xtensive.Orm.Operations/WellKnownTypes.cs new file mode 100644 index 0000000000..eaf6b30989 --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations/WellKnownTypes.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Xtensive.Orm.Operations +{ + internal static class WellKnownTypes + { + public static Type EntitySetBase = typeof(EntitySetBase); + } +} diff --git a/Extensions/Xtensive.Orm.Operations/Xtensive.Orm.Operations.csproj b/Extensions/Xtensive.Orm.Operations/Xtensive.Orm.Operations.csproj new file mode 100644 index 0000000000..247f589ed0 --- /dev/null +++ b/Extensions/Xtensive.Orm.Operations/Xtensive.Orm.Operations.csproj @@ -0,0 +1,26 @@ + + + true + $(OutputPath)$(TargetFramework)\$(AssemblyName).xml + Debug;Release;Debug-NET8;Release-NET8;Debug-NET10;Release-NET10 + + + Xtensive.Orm.Operations + Operations log for $(DoProductName) + $(Title) + Adds logging of entity life-cycle in form of operations. + true + $(ExtensionsKeyFile) + + + ReadMe.md + + + + + + + . + + + diff --git a/Extensions/Xtensive.Orm.Reprocessing/ReprocessAttribute.cs b/Extensions/Xtensive.Orm.Reprocessing/ReprocessAttribute.cs index 275c53630e..3332c6f75f 100644 --- a/Extensions/Xtensive.Orm.Reprocessing/ReprocessAttribute.cs +++ b/Extensions/Xtensive.Orm.Reprocessing/ReprocessAttribute.cs @@ -1,4 +1,4 @@ -#if NOT_IMPLMENETED +#if NOT_IMPLMENETED using System; using System.Transactions; @@ -9,7 +9,6 @@ namespace Xtensive.Orm.Reprocessing /// /// Execute method in reprocessable mode. /// - [Serializable] public class ReprocessAttribute : MethodInterceptionAspect { private StandardExecutionStrategy? _strategy; diff --git a/Extensions/Xtensive.Orm.Security/Configuration/SecurityConfiguration.cs b/Extensions/Xtensive.Orm.Security/Configuration/SecurityConfiguration.cs index 005d37cade..a0831549e6 100644 --- a/Extensions/Xtensive.Orm.Security/Configuration/SecurityConfiguration.cs +++ b/Extensions/Xtensive.Orm.Security/Configuration/SecurityConfiguration.cs @@ -16,8 +16,7 @@ namespace Xtensive.Orm.Security.Configuration { /// /// The configuration of the security system. - /// - [Serializable] + /// public class SecurityConfiguration : ConfigurationBase { /// diff --git a/Extensions/Xtensive.Orm.SerializableExpressions.Tests/SerializableExpressionsTest.cs b/Extensions/Xtensive.Orm.SerializableExpressions.Tests/SerializableExpressionsTest.cs new file mode 100644 index 0000000000..a8664173a3 --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions.Tests/SerializableExpressionsTest.cs @@ -0,0 +1,1556 @@ +// Copyright (C) 2009-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Krjuchkov +// Created: 2009.05.13 + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +using Xtensive.Core; +using Xtensive.Linq; +using Xtensive.Orm.Tests; + +namespace Xtensive.Orm.SerializableExpressions.Tests +{ + [TestFixture] + public class SerializableExpressionsTest + { + #region Nested Types + private struct Struct + { + public int Id; + } + + private class Helper + { + public int Field; + + public Helper NestedClass; + + public List NestedCollection; + + public int InstanceGenericMethod(int value) + { + return value + typeof(T).Name.Length + +GetHashCode(); + } + + public static int StaticGenericMethod(int value) + { + return value + typeof(T).GetHashCode(); + } + } + + [DataContract] + internal class Foo + { + [JsonInclude, DataMember] + public int IntField; + + [JsonInclude, DataMember] + public int IntProperty { get; set; } + + [JsonInclude, DataMember] + public List ListProperty { get; set; } + + public Foo() { } + } + + [DataContract] + internal class Address + { + [JsonInclude, DataMember] + public string City { get; set; } + [JsonInclude, DataMember] + public string ZipCode { get; set; } + + public override bool Equals(object obj) => Equals((Address) obj); + + public bool Equals(Address other) + { + if (other is null) + return false; + return City == other.City && ZipCode == other.ZipCode; + } + + public static bool operator ==(Address a, Address b) + { + if (!ReferenceEquals(a, null) && !ReferenceEquals(b, null)) { + return a.Equals(b); + } + return ReferenceEquals(a, b); + } + + public static bool operator !=(Address a, Address b) + { + return !a.Equals(b); + } + + public Address() { } + + public Address(string city, string zipCode) + { + City = city; + ZipCode = zipCode; + } + } + + [DataContract] + internal class Person + { + [JsonInclude, DataMember] + public Address HomeAddress { get; set; } + [JsonInclude, DataMember] + public string Name { get; set; } + + public override bool Equals(object obj) => Equals((Person) obj); + + public bool Equals(Person other) + { + return HomeAddress == other.HomeAddress && Name == other.Name; + } + + public static bool operator ==(Person a, Person b) + { + if (!ReferenceEquals(a, null) && !ReferenceEquals(b, null)) { + return a.Equals(b); + } + return ReferenceEquals(a, b); + } + + public static bool operator !=(Person a, Person b) + { + return !a.Equals(b); + } + } + + public enum ByteEnum : byte + { + None = 0, + One, Two, + } + + public enum ShortEnum : short + { + None = 10, + One, Two, + } + + public enum IntEnum : int + { + None = 100, + One, Two, + } + + public enum LongEnum : long + { + None = 1000, + One, Two, + } + #endregion + + public static readonly IReadOnlyList SystemTypes = [ + typeof(DateOnly), typeof(DateOnly?), typeof(DateOnly[]), typeof(DateOnly?[]), + typeof(TimeOnly), typeof(TimeOnly?), typeof(TimeOnly[]), typeof(TimeOnly?[]), + typeof(DateTime), typeof(DateTime?), typeof(DateTime[]), typeof(DateTime?[]), + typeof(TimeSpan), typeof(TimeSpan?), typeof(TimeSpan[]), typeof(TimeSpan?[]), + typeof(DateTimeOffset), typeof(DateTimeOffset?), typeof(DateTimeOffset[]), typeof(DateTimeOffset?[]), + typeof(Type), typeof(Type[]), + typeof(MethodInfo), typeof(MethodInfo[]), + typeof(MemberInfo), typeof(MemberInfo[]), + typeof(ConstructorInfo), typeof(ConstructorInfo[]), + typeof(bool?), typeof(bool[]), typeof(bool?[]), + typeof(byte?), typeof(byte[]), typeof(byte?[]), + typeof(sbyte?), typeof(sbyte[]), typeof(sbyte?[]), + typeof(short?), typeof(short[]), typeof(short?[]), + typeof(ushort?), typeof(ushort[]), typeof(ushort?[]), + typeof(int?), typeof(int[]), typeof(int?[]), + typeof(uint?), typeof(uint[]), typeof(uint?[]), + typeof(long?), typeof(long[]), typeof(long?[]), + typeof(ulong?), typeof(ulong[]), typeof(ulong?[]), + typeof(Int128), typeof(Int128?), typeof(Int128[]), typeof(Int128?[]), + typeof(UInt128), typeof(UInt128?), typeof(UInt128[]), typeof(UInt128?[]), + typeof(float?), typeof(float[]), typeof(float?[]), + typeof(double?), typeof(double[]), typeof(double?[]), + typeof(decimal?), typeof(decimal[]), typeof(decimal?[]), + typeof(string[]), + ]; + + public LambdaExpression[] LambdaExpressions { get; private set; } + + #region Additional Test Data + + public ConstantExpression[] ConstantExpressions { get; private set; } + public DefaultExpression[] DefaultExpressions { get; private set; } + public ParameterExpression[] ParameterExpressions { get; private set; } + public ParameterExpression[] VariableExpressions { get; private set; } + public BinaryExpression[] BinaryExpressions { get; private set; } + public ConditionalExpression[] ConditionalExpressions { get; private set; } + public InvocationExpression[] InvocationExpressions { get; private set; } + public ListInitExpression[] ListInitExpressions { get; private set; } + public MemberExpression[] MemberExpressions { get; private set; } + public MemberInitExpression[] MemberInitExpressions { get; private set; } + public MethodCallExpression[] MethodCallExpressions { get; private set; } + public NewArrayExpression[] NewArrayExpressions { get; private set; } + public TypeBinaryExpression[] TypeBinaryExpressions { get; private set; } + public UnaryExpression[] UnaryExpressions { get; private set; } + public NewExpression[] NewExpressions { get; private set; } + + #endregion + + [OneTimeSetUp] + public void TestFixtureSetUp() + { + LambdaExpressions = GetTestLambdaExpressions(); + + ConstantExpressions = GetTestConstantExpressions(); + DefaultExpressions = GetTestDefaultExpressions(); + ParameterExpressions = GetTestParameterExpressions(); + VariableExpressions = GetTestVariableExpressions(); + BinaryExpressions = GetTestBinaryExpressions(); + ConditionalExpressions = GetTestConditionalExpressions(); + InvocationExpressions = GetTestInvocationExpressions(); + ListInitExpressions = GetTestListInitExpressions(); + MemberExpressions = GetTestMemberExpressions(); + NewExpressions = GetTestNewExpressions(); + MemberInitExpressions = GetTestMemberInitExressions(); + MethodCallExpressions = GetTestMethodCallExpressions(); + NewArrayExpressions = GetTestNewArrayExpressions(); + TypeBinaryExpressions = GetTestTypeBinaryExpressions(); + UnaryExpressions = GetTestUnaryExpressions(); + } + + + [Test] + public void ConstantExpressionTest() + { + foreach (var origin in ConstantExpressions) { + Console.WriteLine(origin.ToString(true)); + var converted = origin.ToSerializableExpression().ToExpression(); + Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); + Console.WriteLine("OK"); + } + } + + [Test] + public void ConstantExpressionDataContractCloneTest() + { + var settings = new DataContractSerializerSettings { + KnownTypes = SystemTypes + .Union(new[] { typeof(ByteEnum), typeof(ByteEnum?), typeof(ByteEnum[]), typeof(ByteEnum?[]), + typeof(ShortEnum), typeof(ShortEnum?), typeof(ShortEnum[]), typeof(ShortEnum?[]), + typeof(IntEnum), typeof(IntEnum?), typeof(IntEnum[]), typeof(IntEnum?[]), + typeof(LongEnum), typeof(LongEnum?), typeof(LongEnum[]), typeof(LongEnum?[]), + typeof(Person), typeof(Person[]), + typeof(Address), typeof(Address[]) + }), + PreserveObjectReferences = true + }; + RunDataContractTest(new DataContractSerializer(typeof(SerializableExpression), settings), ConstantExpressions); + } + + [Test] + public void ConstantExpressionDataContractJsonCloneTest() + { + var settings = new DataContractJsonSerializerSettings { + KnownTypes = SystemTypes + .Union(new[] { typeof(ByteEnum), typeof(ByteEnum?), typeof(ByteEnum[]), typeof(ByteEnum?[]), + typeof(ShortEnum), typeof(ShortEnum?), typeof(ShortEnum[]), typeof(ShortEnum?[]), + typeof(IntEnum), typeof(IntEnum?), typeof(IntEnum[]), typeof(IntEnum?[]), + typeof(LongEnum), typeof(LongEnum?), typeof(LongEnum[]), typeof(LongEnum?[]), + typeof(Person), typeof(Person[]), + typeof(Address), typeof(Address[]) + }) + }; + RunDataContractTest(new DataContractJsonSerializer(typeof(SerializableExpression), settings), ConstantExpressions); + } + + [Test] + public void ConstantExpressionJsonSerializerCloneTest() + { + var options = new JsonSerializerOptions { WriteIndented = true }; + RunJsonSerializerTest(ConstantExpressions, options); + } + + [Test] + public void DefaultExpressionTest() + { + foreach (var origin in DefaultExpressions) { + Console.WriteLine(origin.ToString(true)); + var converted = origin.ToSerializableExpression().ToExpression(); + Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); + Console.WriteLine("OK"); + } + } + + [Test] + public void DefaultExpressionDataContractCloneTest() + { + var settings = new DataContractSerializerSettings { + KnownTypes = SystemTypes + .Union(new[] { typeof(ByteEnum), typeof(ByteEnum?), typeof(ByteEnum[]), typeof(ByteEnum?[]), + typeof(ShortEnum), typeof(ShortEnum?), typeof(ShortEnum[]), typeof(ShortEnum?[]), + typeof(IntEnum), typeof(IntEnum?), typeof(IntEnum[]), typeof(IntEnum?[]), + typeof(LongEnum), typeof(LongEnum?), typeof(LongEnum[]), typeof(LongEnum?[]), + typeof(Person), typeof(Person[]), + typeof(Address), typeof(Address[]) + }), + PreserveObjectReferences = true + }; + RunDataContractTest(new DataContractSerializer(typeof(SerializableExpression), settings), DefaultExpressions); + } + + [Test] + public void DefaultExpressionDataContractJsonCloneTest() + { + var settings = new DataContractJsonSerializerSettings { + KnownTypes = SystemTypes + .Union(new[] { typeof(ByteEnum), typeof(ByteEnum?), typeof(ByteEnum[]), typeof(ByteEnum?[]), + typeof(ShortEnum), typeof(ShortEnum?), typeof(ShortEnum[]), typeof(ShortEnum?[]), + typeof(IntEnum), typeof(IntEnum?), typeof(IntEnum[]), typeof(IntEnum?[]), + typeof(LongEnum), typeof(LongEnum?), typeof(LongEnum[]), typeof(LongEnum?[]), + typeof(Person), typeof(Person[]), + typeof(Address), typeof(Address[]) + }) + }; + RunDataContractTest(new DataContractJsonSerializer(typeof(SerializableExpression), settings), DefaultExpressions); + } + + [Test] + public void DefaultExpressionJsonSerializerCloneTest() + { + var options = new JsonSerializerOptions { WriteIndented = true }; + RunJsonSerializerTest(DefaultExpressions, options); + } + + [Test] + public void ParameterExpressionTest() + { + foreach (var origin in ParameterExpressions) { + Console.WriteLine(origin.ToString(true)); + var converted = origin.ToSerializableExpression().ToExpression(); + Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); + Console.WriteLine("OK"); + } + + foreach (var origin in VariableExpressions) { + Console.WriteLine(origin.ToString(true)); + var converted = origin.ToSerializableExpression().ToExpression(); + Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); + Console.WriteLine("OK"); + } + } + + [Test] + public void ParameterExpressionDataContractCloneTest() + { + var settings = new DataContractSerializerSettings { + KnownTypes = SystemTypes, + PreserveObjectReferences = true + }; + RunDataContractTest(new DataContractSerializer(typeof(SerializableExpression), settings), ParameterExpressions); + RunDataContractTest(new DataContractSerializer(typeof(SerializableExpression), settings), VariableExpressions); + } + + [Test] + public void ParameterExpressionDataContractJsonCloneTest() + { + var settings = new DataContractJsonSerializerSettings { KnownTypes = SystemTypes }; + RunDataContractTest(new DataContractJsonSerializer(typeof(SerializableExpression), settings), ParameterExpressions); + RunDataContractTest(new DataContractJsonSerializer(typeof(SerializableExpression), settings), VariableExpressions); + } + + [Test] + public void ParameterExpressionJsonSerializerCloneTest() + { + var options = new JsonSerializerOptions { WriteIndented = true }; + RunJsonSerializerTest(ParameterExpressions, options); + RunJsonSerializerTest(VariableExpressions, options); + } + + [Test] + public void BinaryExpressionTest() + { + foreach (var origin in BinaryExpressions) { + Console.WriteLine(origin.ToString(true)); + var converted = origin.ToSerializableExpression().ToExpression(); + Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); + Console.WriteLine("OK"); + } + } + + [Test] + public void BinaryExpressionDataContractCloneTest() + { + var settings = new DataContractSerializerSettings { + KnownTypes = SystemTypes, + PreserveObjectReferences = true + }; + RunDataContractTest(new DataContractSerializer(typeof(SerializableExpression), settings), BinaryExpressions); + } + + [Test] + public void BinaryExpressionDataContractJsonCloneTest() + { + var settings = new DataContractJsonSerializerSettings { KnownTypes = SystemTypes }; + RunDataContractTest(new DataContractJsonSerializer(typeof(SerializableExpression), settings), BinaryExpressions); + } + + [Test] + public void BinaryExpressionJsonSerializerCloneTest() + { + var options = new JsonSerializerOptions { WriteIndented = true }; + RunJsonSerializerTest(BinaryExpressions, options); + } + + [Test] + public void ConditionalExpressionTest() + { + foreach (var origin in ConditionalExpressions) { + Console.WriteLine(origin.ToString(true)); + var converted = origin.ToSerializableExpression().ToExpression(); + Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); + Console.WriteLine("OK"); + } + } + + [Test] + public void ConditionalExpressionDataContractCloneTest() + { + var settings = new DataContractSerializerSettings { + KnownTypes = SystemTypes, + PreserveObjectReferences = true + }; + RunDataContractTest(new DataContractSerializer(typeof(SerializableExpression), settings), ConditionalExpressions); + } + + [Test] + public void ConditionalExpressionDataContractJsonCloneTest() + { + var settings = new DataContractJsonSerializerSettings { KnownTypes = SystemTypes }; + RunDataContractTest(new DataContractJsonSerializer(typeof(SerializableExpression), settings), ConditionalExpressions); + } + + [Test] + public void ConditionalExpressionJsonSerializerCloneTest() + { + var options = new JsonSerializerOptions { WriteIndented = true }; + RunJsonSerializerTest(ConditionalExpressions, options); + } + + [Test] + public void ListInitExpressionTest() + { + foreach (var origin in ListInitExpressions) { + Console.WriteLine(origin.ToString(true)); + var converted = origin.ToSerializableExpression().ToExpression(); + Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); + Console.WriteLine("OK"); + } + } + + [Test] + public void ListInitExpressionDataContractCloneTest() + { + var settings = new DataContractSerializerSettings { + KnownTypes = SystemTypes, + PreserveObjectReferences = true + }; + RunDataContractTest(new DataContractSerializer(typeof(SerializableExpression), settings), ListInitExpressions); + } + + [Test] + public void ListInitExpressionDataContractJsonCloneTest() + { + var settings = new DataContractJsonSerializerSettings { KnownTypes = SystemTypes }; + RunDataContractTest(new DataContractJsonSerializer(typeof(SerializableExpression), settings), ListInitExpressions); + } + + [Test] + public void ListInitExpressionJsonSerializerCloneTest() + { + var options = new JsonSerializerOptions { WriteIndented = true }; + RunJsonSerializerTest(ListInitExpressions, options); + } + + [Test] + public void MemberExpressionTest() + { + foreach (var origin in MemberExpressions) { + Console.WriteLine(origin.ToString(true)); + var converted = origin.ToSerializableExpression().ToExpression(); + Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); + Console.WriteLine("OK"); + } + } + + [Test] + public void MemberExpressionDataContractCloneTest() + { + var settings = new DataContractSerializerSettings { + KnownTypes = SystemTypes.Union(new[] { typeof(Foo) }), + PreserveObjectReferences = true + }; + RunDataContractTest(new DataContractSerializer(typeof(SerializableExpression), settings), MemberExpressions); + } + + [Test] + public void MemberExpressionDataContractJsonCloneTest() + { + var settings = new DataContractJsonSerializerSettings { KnownTypes = SystemTypes.Union(new[] { typeof(Foo) }) }; + RunDataContractTest(new DataContractJsonSerializer(typeof(SerializableExpression), settings), MemberExpressions); + } + + [Test] + public void MemberExpressionJsonSerializerCloneTest() + { + var options = new JsonSerializerOptions { WriteIndented = true, ReferenceHandler = ReferenceHandler.Preserve }; + RunJsonSerializerTest(MemberExpressions, options); + } + + [Test] + public void NewExpressionTest() + { + foreach (var origin in NewExpressions) { + Console.WriteLine(origin.ToString(true)); + var converted = origin.ToSerializableExpression().ToExpression(); + Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); + Console.WriteLine("OK"); + } + } + + [Test] + public void NewExpressionDataContractCloneTest() + { + var settings = new DataContractSerializerSettings { + KnownTypes = SystemTypes, + PreserveObjectReferences = true + }; + RunDataContractTest(new DataContractSerializer(typeof(SerializableExpression), settings), NewExpressions); + } + + [Test] + public void NewExpressionDataContractJsonCloneTest() + { + var settings = new DataContractJsonSerializerSettings { KnownTypes = SystemTypes }; + RunDataContractTest(new DataContractJsonSerializer(typeof(SerializableExpression), settings), NewExpressions); + } + + [Test] + public void NewExpressionJsonSerializerCloneTest() + { + var options = new JsonSerializerOptions { WriteIndented = true }; + RunJsonSerializerTest(NewExpressions, options); + } + + [Test] + public void MemberInitExpressionTest() + { + foreach (var origin in MemberInitExpressions) { + Console.WriteLine(origin.ToString(true)); + var converted = origin.ToSerializableExpression().ToExpression(); + Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); + Console.WriteLine("OK"); + } + } + + [Test] + public void MemberInitExpressionDataContractCloneTest() + { + var settings = new DataContractSerializerSettings { + KnownTypes = SystemTypes, + PreserveObjectReferences = true + }; + RunDataContractTest(new DataContractSerializer(typeof(SerializableExpression), settings), MemberInitExpressions); + } + + [Test] + public void MemberInitExpressionDataContractJsonCloneTest() + { + var settings = new DataContractJsonSerializerSettings { KnownTypes = SystemTypes }; + RunDataContractTest(new DataContractJsonSerializer(typeof(SerializableExpression), settings), MemberInitExpressions); + } + + [Test] + public void MemberInitExpressionJsonSerializerCloneTest() + { + var options = new JsonSerializerOptions { WriteIndented = true }; + RunJsonSerializerTest(MemberInitExpressions, options); + } + + [Test] + public void MethodCallExpressionTest() + { + foreach (var origin in MethodCallExpressions) { + Console.WriteLine(origin.ToString(true)); + var converted = origin.ToSerializableExpression().ToExpression(); + Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); + Console.WriteLine("OK"); + } + } + + [Test] + public void MethodCallExpressionDataContractCloneTest() + { + var settings = new DataContractSerializerSettings { + KnownTypes = SystemTypes, + PreserveObjectReferences = true + }; + RunDataContractTest(new DataContractSerializer(typeof(SerializableExpression), settings), MethodCallExpressions); + } + + [Test] + public void MethodCallExpressionDataContractJsonCloneTest() + { + var settings = new DataContractJsonSerializerSettings { KnownTypes = SystemTypes }; + RunDataContractTest(new DataContractJsonSerializer(typeof(SerializableExpression), settings), MethodCallExpressions); + } + + [Test] + public void MethodCallExpressionJsonSerializerCloneTest() + { + var options = new JsonSerializerOptions { WriteIndented = true }; + RunJsonSerializerTest(MethodCallExpressions, options); + } + + [Test] + public void NewArrayExpressionTest() + { + foreach (var origin in NewArrayExpressions) { + Console.WriteLine(origin.ToString(true)); + var converted = origin.ToSerializableExpression().ToExpression(); + Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); + Console.WriteLine("OK"); + } + } + + [Test] + public void NewArrayExpressionDataContractCloneTest() + { + var settings = new DataContractSerializerSettings { + KnownTypes = SystemTypes, + PreserveObjectReferences = true + }; + RunDataContractTest(new DataContractSerializer(typeof(SerializableExpression), settings), NewArrayExpressions); + } + + [Test] + public void NewArrayExpressionDataContractJsonCloneTest() + { + var settings = new DataContractJsonSerializerSettings { KnownTypes = SystemTypes }; + RunDataContractTest(new DataContractJsonSerializer(typeof(SerializableExpression), settings), NewArrayExpressions); + } + + [Test] + public void NewArrayExpressionJsonSerializerCloneTest() + { + var options = new JsonSerializerOptions { WriteIndented = true }; + RunJsonSerializerTest(NewArrayExpressions, options); + } + + [Test] + public void TypeBinaryExpressionTest() + { + foreach (var origin in TypeBinaryExpressions) { + Console.WriteLine(origin.ToString(true)); + var converted = origin.ToSerializableExpression().ToExpression(); + Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); + Console.WriteLine("OK"); + } + } + + [Test] + public void TypeBinaryExpressionDataContractCloneTest() + { + var settings = new DataContractSerializerSettings { + KnownTypes = SystemTypes, + PreserveObjectReferences = true + }; + RunDataContractTest(new DataContractSerializer(typeof(SerializableExpression), settings), TypeBinaryExpressions); + } + + [Test] + public void TypeBinaryExpressionDataContractJsonCloneTest() + { + var settings = new DataContractJsonSerializerSettings { KnownTypes = SystemTypes }; + RunDataContractTest(new DataContractJsonSerializer(typeof(SerializableExpression), settings), TypeBinaryExpressions); + } + + [Test] + public void TypeBinaryExpressionJsonSerializerCloneTest() + { + var options = new JsonSerializerOptions { WriteIndented = true }; + RunJsonSerializerTest(TypeBinaryExpressions, options); + } + + [Test] + public void UnaryExpressionsTest() + { + foreach (var origin in UnaryExpressions) { + Console.WriteLine(origin.ToString(true)); + var converted = origin.ToSerializableExpression().ToExpression(); + Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); + Console.WriteLine("OK"); + } + } + + [Test] + public void UnaryExpressionDataContractCloneTest() + { + var settings = new DataContractSerializerSettings { + KnownTypes = SystemTypes, + PreserveObjectReferences = true + }; + RunDataContractTest(new DataContractSerializer(typeof(SerializableExpression), settings), UnaryExpressions); + } + + [Test] + public void UnaryExpressionDataContractJsonCloneTest() + { + var settings = new DataContractJsonSerializerSettings { KnownTypes = SystemTypes }; + RunDataContractTest(new DataContractJsonSerializer(typeof(SerializableExpression), settings), UnaryExpressions); + } + + [Test] + public void UnaryExpressionJsonSerializerCloneTest() + { + var options = new JsonSerializerOptions { WriteIndented = true }; + RunJsonSerializerTest(UnaryExpressions, options); + } + + [Test] + public void InvocationExpressionTest() + { + foreach (var origin in InvocationExpressions) { + Console.WriteLine(origin.ToString(true)); + var converted = origin.ToSerializableExpression().ToExpression(); + Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); + Console.WriteLine("OK"); + } + } + + [Test] + public void InvocationExpressionDataContractCloneTest() + { + var settings = new DataContractSerializerSettings { + KnownTypes = SystemTypes, + PreserveObjectReferences = true + }; + RunDataContractTest(new DataContractSerializer(typeof(SerializableExpression), settings), InvocationExpressions); + + settings = new DataContractSerializerSettings { + KnownTypes = SystemTypes, + PreserveObjectReferences = false + }; + RunDataContractTest(new DataContractSerializer(typeof(SerializableExpression), settings), InvocationExpressions); + } + + [Test] + public void InvocationExpressionDataContractJsonCloneTest() + { + var settings = new DataContractJsonSerializerSettings { KnownTypes = SystemTypes }; + RunDataContractTest(new DataContractJsonSerializer(typeof(SerializableExpression), settings), InvocationExpressions); + } + + [Test] + public void InvocationExpressionJsonSerializerCloneTest() + { + var options = new JsonSerializerOptions { WriteIndented = true }; + RunJsonSerializerTest(InvocationExpressions, options); + + options = new JsonSerializerOptions { WriteIndented = true, ReferenceHandler = ReferenceHandler.Preserve }; + RunJsonSerializerTest(InvocationExpressions, options); + } + + [Test] + public void LambdaExpressionTest() + { + foreach (var origin in LambdaExpressions) { + Console.WriteLine(origin.ToString(true)); + var converted = origin.ToSerializableExpression().ToExpression(); + Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); + Console.WriteLine("OK"); + } + } + + [Test] + public void LambdaExpressionDataContractCloneTest() + { + var settings = new DataContractSerializerSettings { + KnownTypes = SystemTypes, + PreserveObjectReferences = true + }; + RunDataContractTest(new DataContractSerializer(typeof(SerializableExpression), settings), LambdaExpressions); + + settings = new DataContractSerializerSettings { + KnownTypes = SystemTypes, + PreserveObjectReferences = false + }; + RunDataContractTest(new DataContractSerializer(typeof(SerializableExpression), settings), LambdaExpressions); + } + + [Test] + public void LambdaExpressionDataContractJsonCloneTest() + { + var settings = new DataContractJsonSerializerSettings { KnownTypes = SystemTypes, }; + RunDataContractTest(new DataContractJsonSerializer(typeof(SerializableExpression), settings), LambdaExpressions); + } + + [Test] + public void LambdaExpressionJsonSerializerCloneTest() + { + var options = new JsonSerializerOptions { WriteIndented = true }; + RunJsonSerializerTest(LambdaExpressions, options); + + options = new JsonSerializerOptions { WriteIndented = true, ReferenceHandler = ReferenceHandler.Preserve }; + RunJsonSerializerTest(LambdaExpressions, options); + } + + private void RunDataContractTest(XmlObjectSerializer serializer, IEnumerable expressions) + { + using (var stream = new MemoryStream()) { + foreach (var expression in expressions) { + Console.WriteLine(expression.ToString(true)); + serializer.WriteObject(stream, expression.ToSerializableExpression()); + _ = stream.Seek(0, SeekOrigin.Begin); + var serialized = (SerializableExpression) serializer.ReadObject(stream); + stream.SetLength(0); + CompareExpressions(expression, serialized.ToExpression()); + Console.WriteLine("OK"); + } + } + } + + private void RunJsonSerializerTest(IEnumerable expressions, JsonSerializerOptions options) + { + using (var stream = new MemoryStream()) { + foreach (var expression in expressions) { + Console.WriteLine(expression.ToString(true)); + + var serializableExpression = expression.ToSerializableExpression(); + + JsonSerializer.Serialize(stream, serializableExpression, options); + _ = stream.Seek(0, SeekOrigin.Begin); + var serialized = JsonSerializer.Deserialize(stream, options); + stream.SetLength(0); + CompareExpressions(expression, serialized.ToExpression()); + Console.WriteLine("OK"); + } + } + } + + private void CompareExpressions(Expression expression, Expression serialized) + { + if (expression is ConstantExpression cExpressions) + CompareConstants(cExpressions, (ConstantExpression) serialized); + else if (expression is MemberExpression mExpression) + CompareMemberExpressions(mExpression, (MemberExpression) serialized); + else if (expression is BinaryExpression bExpression && bExpression.NodeType == ExpressionType.ArrayIndex) + CompareArrayIndex(bExpression, (BinaryExpression) serialized); + else if (expression is UnaryExpression uExpression && uExpression.NodeType == ExpressionType.ArrayLength) + CompareArrayLength(uExpression, (UnaryExpression) serialized); + else + Assert.That(serialized.ToExpressionTree(), Is.EqualTo(expression.ToExpressionTree())); + } + + private void CompareMemberExpressions(MemberExpression origin, MemberExpression clone) + { + Assert.That(clone.Type, Is.EqualTo(origin.Type)); + + var instanceOrig = origin.Expression as ConstantExpression; + var instanceClone = clone.Expression as ConstantExpression; + + Assert.That(instanceClone.Type, Is.EqualTo(instanceOrig.Type)); + + var instValueOrig = instanceOrig.Value as Foo; + var instValueClone = instanceClone.Value as Foo; + + Assert.That(instValueClone.IntField, Is.EqualTo(instValueOrig.IntField)); + Assert.That(instValueClone.IntProperty, Is.EqualTo(instValueOrig.IntProperty)); + + Assert.That(clone.Member, Is.EqualTo(origin.Member)); + } + + private void CompareArrayIndex(BinaryExpression origin, BinaryExpression clone) + { + if (origin.NodeType != ExpressionType.ArrayIndex) + throw new ArgumentException(); + + Assert.That(clone.Type, Is.EqualTo(origin.Type)); + + CompareConstants((ConstantExpression) origin.Left, (ConstantExpression) clone.Left); + CompareConstants((ConstantExpression) origin.Right, (ConstantExpression) clone.Right); + + } + + private void CompareArrayLength(UnaryExpression origin, UnaryExpression clone) + { + if (origin.NodeType != ExpressionType.ArrayLength) + throw new ArgumentException(); + + Assert.That(clone.Type, Is.EqualTo(origin.Type)); + + var instanceOrig = (origin.Operand as ConstantExpression); + var instanceClone = (clone.Operand as ConstantExpression); + + CompareConstants(instanceOrig, instanceClone); + } + + private void CompareConstants(ConstantExpression origin, ConstantExpression clone) + { + Assert.That(clone.Type, Is.EqualTo(origin.Type)); + + if (origin.Type.IsArray) { + Assert.That(origin.Value, Is.Not.Null); + Assert.That(clone.Value, Is.Not.Null); + Assert.That(clone.Value, Is.EquivalentTo(origin.Value as Array)); + } + else { + Assert.That(clone.Value, Is.EqualTo(origin.Value)); + } + } + + #region Performance test + + private const int warmUpOperationCount = 10; + private const int actualOperationCount = 10000; + + [Test] + [Category("Performance")] + [Explicit] + public void DataContractXmlSerializationBenchmarkTest() + { + var settings = new DataContractSerializerSettings { + KnownTypes = SystemTypes, + PreserveObjectReferences = true + }; + + var serializer = new DataContractSerializer(typeof(SerializableExpression), settings); + RunSerializeBenchmark(serializer, true); + RunSerializeBenchmark(serializer, false); + } + + [Test] + [Category("Performance")] + [Explicit] + public void DataContractJsonSerializationBenchmarkTest() + { + var settings = new DataContractJsonSerializerSettings { KnownTypes = SystemTypes }; + + var serializer = new DataContractJsonSerializer(typeof(SerializableExpression), settings); + RunSerializeBenchmark(serializer, true); + RunSerializeBenchmark(serializer, false); + } + + [Test] + [Category("Performance")] + [Explicit] + public void JsonSerializerWithReferenceSerializationBenchmarkTest() + { + var options = new JsonSerializerOptions() { WriteIndented = true, ReferenceHandler = ReferenceHandler.Preserve }; + + RunSerializeViaJsonSerializerBenchmark(true, options); + RunSerializeViaJsonSerializerBenchmark(false, options); + } + + [Test] + [Category("Performance")] + [Explicit] + public void JsonSerializerWithoutReferenceSerializationBenchmarkTest() + { + var options = new JsonSerializerOptions() { WriteIndented = true }; + + RunSerializeViaJsonSerializerBenchmark(true, options); + RunSerializeViaJsonSerializerBenchmark(false, options); + } + + private void RunSerializeBenchmark(XmlObjectSerializer serializer, bool warmUp) + { + var operationCount = warmUp ? warmUpOperationCount : actualOperationCount; + using (var stream = new MemoryStream()) { + int operation = 0; + long length = 0; + using (CreateMeasurement(warmUp, serializer.GetType().Name, operationCount)) { + while (operation < operationCount) { + foreach (var expression in LambdaExpressions) { + operation++; + if (operation > operationCount) + break; + serializer.WriteObject(stream, expression.ToSerializableExpression()); + length += stream.Position; + _ = stream.Seek(0, SeekOrigin.Begin); + var serialized = (SerializableExpression) serializer.ReadObject(stream); + stream.SetLength(0); + } + } + } + + Console.Out.WriteLine($"Stream size: {length / 1024} Kb"); + } + } + + private void RunSerializeViaJsonSerializerBenchmark(bool warmUp, JsonSerializerOptions options) + { + var operationCount = warmUp ? warmUpOperationCount : actualOperationCount; + using (var stream = new MemoryStream()) { + int operation = 0; + long length = 0; + using (CreateMeasurement(warmUp, "JsonSerializer", operationCount)) { + while (operation < operationCount) { + foreach (var expression in LambdaExpressions) { + operation++; + if (operation > operationCount) + break; + var serializableExpression = expression.ToSerializableExpression(); + + JsonSerializer.Serialize(stream, serializableExpression, options); + length += stream.Position; + _ = stream.Seek(0, SeekOrigin.Begin); + var serialized = JsonSerializer.Deserialize(stream, options); + stream.SetLength(0); + } + } + } + + Console.Out.WriteLine($"Stream size: {length / 1024} Kb"); + } + } + + private static IDisposable CreateMeasurement(bool warmUp, string name, int operationCount) + { + return warmUp + ? new Measurement(name, MeasurementOptions.None, operationCount) + : new Measurement(name, operationCount); + } + + #endregion + + #region Test Data initializers + private LambdaExpression[] GetTestLambdaExpressions() + { + return new LambdaExpression[] + { + // Simple expression + (Expression>) (k => k + 1), + + // Instance method call + (Expression>) (p => p.ToString()), + + // Static method call + (Expression>) ((a, b) => Console.Write($"{a} + {b} = {a + b}")), + + // Instance generic method call + (Expression>) (h => h.InstanceGenericMethod(0)), + + // Static generic method call + (Expression>) (() => Helper.StaticGenericMethod(0)), + + // Instance generic method call (with generic argument being generic type) + (Expression>) (h => h.InstanceGenericMethod>(0)), + + // Static generic method call (with generic argument being generic type) + (Expression>) (() => Helper.StaticGenericMethod>(0)), + + // Static (extension) generic method call + (Expression>, IEnumerable>>) (funcs => funcs.Select(f => f.Invoke())), + + // Anonymous type constructor + (Expression>) (s => new {Value = s}), + + // Static property access + binary operator + (Expression>) (d => (d - DateTime.Now).Duration().ToString()), + + // Constructor + a lots of generics + (Expression>>) (i => new List(i)), + (Expression>>>) (i => new List>(i)), + (Expression>>>>) (i => new List>>(i)), + (Expression>>>>>) (i => new List>>>(i)), + + // Static generic method call + static method call + constant expression + (Expression>>>) (x => Expression.Lambda>(Expression.Constant(x))), + + // Constructor + (Expression>) ((y, m, d) => new DateTime(y, m, d)), + + // List init expression + (Expression>>) (s => new List {s.Length}), + + // Array init expression + (Expression>) (g => new[] {g}), + + // Delegate call + (Expression>) (() => ((Func) (x => x + 1)).Invoke(5)), + + // Conditional + new array + static property of generic type + // Stupid casts are required because otherwise expression won't construct at runtime + (Expression>) (k => k <= 0 ? (byte[]) Array.Empty() : (byte[]) new byte[k]), + + // TypeIs + (Expression>) (o => o is string), + + // Coalesce + constructor + member assignment + (Expression>) (o => o ?? new Helper {Field = 5}), + + // Member list init + (Expression>) (() => new Helper {NestedCollection = {1,2,3}}), + + // Member member binding + (Expression>) (() => new Helper {NestedClass = {Field = 5}}), + + // Struct constructor + (Expression>) (a => new Struct {Id = 2}), + + // Don't know how to write InvocationExpression in C# syntax :-( + Expression.Lambda>( + Expression.Invoke( + Expression.Lambda>(Expression.Constant(0), Expression.Parameter(typeof(int), "p")), + Expression.Constant(1))) + }; + } + + private ConstantExpression[] GetTestConstantExpressions() + { + return new ConstantExpression[] { + // Regular values + Expression.Constant(false, typeof(bool)), + Expression.Constant(true, typeof(bool)), + Expression.Constant((byte) 64, typeof(byte)), + Expression.Constant((sbyte) -64, typeof(sbyte)), + Expression.Constant((short) -128, typeof(short)), + Expression.Constant((ushort) 128, typeof(ushort)), + Expression.Constant((int) -256, typeof(int)), + Expression.Constant((uint) 256, typeof(uint)), + Expression.Constant((long) -512, typeof(long)), + Expression.Constant((ulong) 512, typeof(ulong)), + Expression.Constant(new Int128(65, 64), typeof(Int128)), + Expression.Constant(new UInt128(65, 64), typeof(UInt128)), + Expression.Constant((float) 6.283185307f, typeof(float)), + Expression.Constant((double) 6.283185307179586476925, typeof(double)), + Expression.Constant((decimal) 6.2895762354m, typeof(decimal)), + Expression.Constant(TimeSpan.FromSeconds(1024), typeof(TimeSpan)), + Expression.Constant(new DateTime(2018, 9, 27, 18, 55, 56), typeof(DateTime)), + Expression.Constant(new DateTimeOffset(2018, 9, 27, 18, 55, 56, new TimeSpan(6, 0, 0)), typeof(DateTimeOffset)), + Expression.Constant(new DateOnly(2018, 9, 27), typeof(DateOnly)), + Expression.Constant(new TimeOnly(18, 55, 56), typeof(TimeOnly)), + Expression.Constant(null, typeof(string)), + Expression.Constant(string.Empty, typeof(string)), + Expression.Constant("DBC", typeof(string)), + Expression.Constant(ByteEnum.One, typeof(ByteEnum)), + Expression.Constant(ShortEnum.One, typeof(ShortEnum)), + Expression.Constant(IntEnum.One, typeof(IntEnum)), + Expression.Constant(LongEnum.One, typeof(LongEnum)), + Expression.Constant(Guid.NewGuid(), typeof(Guid)), + Expression.Constant(new Person() { Name = "The Person", HomeAddress = new Address() { City = "Landon", ZipCode = "666777" } }, typeof(Person)), + + // Arrays of regular values + Expression.Constant(new bool[] { true, false, true }, typeof(bool[])), + Expression.Constant(new byte[] { 44, 45, 46 }, typeof(byte[])), + Expression.Constant(new sbyte[] { -44, -45, -46 }, typeof(sbyte[])), + Expression.Constant(new short[] { -111, -112, -113 }, typeof(short[])), + Expression.Constant(new ushort[] { 111, 112, 113 }, typeof(ushort[])), + Expression.Constant(new long[] { -500, -501, -502 }, typeof(long[])), + Expression.Constant(new ulong[] { 500, 501, 502 }, typeof(ulong[])), + Expression.Constant(new Int128[] { -1000, -1001, -1002 }, typeof(Int128[])), + Expression.Constant(new UInt128[] { 1000, 1001, 1002 }, typeof(UInt128[])), + Expression.Constant(new float[] { float.Tau, float.Tau, float.Tau }, typeof(float[])), + Expression.Constant(new double[] { double.Tau, double.Tau, double.Tau }, typeof(double[])), + Expression.Constant(new decimal[] { 6.2895762354m, 6.2895762354m, 6.2895762354m }, typeof(decimal[])), + Expression.Constant(new TimeSpan[] { TimeSpan.FromSeconds(1024), TimeSpan.FromSeconds(1024 * 2), TimeSpan.FromSeconds(1024 * 3) }, typeof(TimeSpan[])), + Expression.Constant(new DateTime[] { + new DateTime(2018, 9, 27, 18, 55, 56), + new DateTime(2019, 9, 27, 18, 55, 56), + new DateTime(2020, 9, 27, 18, 55, 56) + }, typeof(DateTime[])), + Expression.Constant(new DateOnly[] { + new DateOnly(2018, 9, 27), + new DateOnly(2018, 9, 28), + new DateOnly(2018, 9, 29) + }, typeof(DateOnly[])), + Expression.Constant(new TimeOnly[] { + new TimeOnly(18, 55, 56), + new TimeOnly(18, 56, 56), + new TimeOnly(18, 57, 56) + }, typeof(TimeOnly[])), + Expression.Constant(new[] { "1", "2", "3" }, typeof(string[])), + Expression.Constant(new ByteEnum[] { ByteEnum.One, ByteEnum.Two }, typeof(ByteEnum[])), + Expression.Constant(new ShortEnum[] { ShortEnum.One, ShortEnum.Two }, typeof(ShortEnum[])), + Expression.Constant(new IntEnum[] { IntEnum.One, IntEnum.Two }, typeof(IntEnum[])), + Expression.Constant(new LongEnum[] { LongEnum.One, LongEnum.Two }, typeof(LongEnum[])), + Expression.Constant(new Guid[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }, typeof(Guid[])), + Expression.Constant(new Person[] { + new Person() { Name = "The Person", HomeAddress = new Address() { City = "Landon", ZipCode = "666777" } }, + new Person() { Name = "The Person", HomeAddress = null }, + null + }, + typeof(Person[])), + + //Nullables of regular values + Expression.Constant(false, typeof(bool?)), + Expression.Constant(true, typeof(bool?)), + Expression.Constant((byte?) 64, typeof(byte?)), + Expression.Constant((sbyte?) -64, typeof(sbyte?)), + Expression.Constant((short?) -128, typeof(short?)), + Expression.Constant((ushort?) 128, typeof(ushort?)), + Expression.Constant((int?) -256, typeof(int?)), + Expression.Constant((uint?) 256, typeof(uint?)), + Expression.Constant((long?) -512, typeof(long?)), + Expression.Constant((ulong?) 512, typeof(ulong?)), + Expression.Constant(new Int128(65, 64), typeof(Int128?)), + Expression.Constant(new UInt128(65, 64), typeof(UInt128?)), + Expression.Constant((float?) 6.283185307f, typeof(float?)), + Expression.Constant((double?) 6.283185307179586476925, typeof(double?)), + Expression.Constant((decimal?) 6.2895762354m, typeof(decimal?)), + Expression.Constant(TimeSpan.FromSeconds(1024), typeof(TimeSpan?)), + Expression.Constant(new DateTime(2018, 9, 27, 18, 55, 56), typeof(DateTime?)), + Expression.Constant(new DateTimeOffset(2018, 9, 27, 18, 55, 56, new TimeSpan(6, 0, 0)), typeof(DateTimeOffset?)), + Expression.Constant(new DateOnly(2018, 9, 27), typeof(DateOnly?)), + Expression.Constant(new TimeOnly(18, 55, 56), typeof(TimeOnly?)), + Expression.Constant(ByteEnum.One, typeof(ByteEnum?)), + Expression.Constant(ShortEnum.One, typeof(ShortEnum?)), + Expression.Constant(IntEnum.One, typeof(IntEnum?)), + Expression.Constant(LongEnum.One, typeof(LongEnum?)), + Expression.Constant(Guid.NewGuid(), typeof(Guid?)), + + // Arrays of Nullables + Expression.Constant(new bool?[] { true, false, null }, typeof(bool?[])), + Expression.Constant(new byte?[] { 44, 45, null }, typeof(byte?[])), + Expression.Constant(new sbyte?[] { -44, -45, null }, typeof(sbyte?[])), + Expression.Constant(new short?[] { -111, -112, null }, typeof(short?[])), + Expression.Constant(new ushort?[] { 111, 112, null }, typeof(ushort?[])), + Expression.Constant(new long?[] { -500, -501, null }, typeof(long?[])), + Expression.Constant(new ulong?[] { 500, 501, null }, typeof(ulong?[])), + Expression.Constant(new Int128?[] { -1000, -1001, null }, typeof(Int128?[])), + Expression.Constant(new UInt128?[] { 1000, 1001, null }, typeof(UInt128?[])), + Expression.Constant(new float?[] { float.Tau, float.Tau, null }, typeof(float?[])), + Expression.Constant(new double?[] { double.Tau, double.Tau, null }, typeof(double?[])), + Expression.Constant(new decimal?[] { 6.2895762354m, 6.2895762354m, null }, typeof(decimal?[])), + Expression.Constant(new TimeSpan?[] { TimeSpan.FromSeconds(1024), TimeSpan.FromSeconds(1024 * 2), null }, typeof(TimeSpan?[])), + Expression.Constant(new DateTime?[] { + new DateTime(2018, 9, 27, 18, 55, 56), + new DateTime(2019, 9, 27, 18, 55, 56), + null + }, typeof(DateTime?[])), + Expression.Constant(new DateOnly?[] { + new DateOnly(2018, 9, 27), + new DateOnly(2018, 9, 28), + null + }, typeof(DateOnly?[])), + Expression.Constant(new TimeOnly?[] { + new TimeOnly(18, 55, 56), + new TimeOnly(18, 56, 56), + null + }, typeof(TimeOnly?[])), + + Expression.Constant(new ByteEnum?[] { ByteEnum.One, null }, typeof(ByteEnum?[])), + Expression.Constant(new ShortEnum?[] { ShortEnum.One, null }, typeof(ShortEnum?[])), + Expression.Constant(new IntEnum?[] { IntEnum.One, null }, typeof(IntEnum?[])), + Expression.Constant(new LongEnum?[] { LongEnum.One, null }, typeof(LongEnum?[])), + Expression.Constant(new Guid?[] { Guid.NewGuid(), Guid.NewGuid(), null }, typeof(Guid?[])), + + }; + ; + } + + private DefaultExpression[] GetTestDefaultExpressions() + { + return new[] { + Expression.Default(typeof(bool)), + Expression.Default(typeof(byte)), + Expression.Default(typeof(sbyte)), + Expression.Default(typeof(short)), + Expression.Default(typeof(ushort)), + Expression.Default(typeof(int)), + Expression.Default(typeof(uint)), + Expression.Default(typeof(long)), + Expression.Default(typeof(ulong)), + Expression.Default(typeof(float)), + Expression.Default(typeof(double)), + Expression.Default(typeof(decimal)), + Expression.Default(typeof(TimeSpan)), + Expression.Default(typeof(DateTime)), + Expression.Default(typeof(string)), + }; + } + + private ParameterExpression[] GetTestParameterExpressions() + { + return new[] { + Expression.Parameter(typeof(bool)), Expression.Parameter(typeof(bool), "boolP"), + Expression.Parameter(typeof(byte)), Expression.Parameter(typeof(byte), "byteP"), + Expression.Parameter(typeof(sbyte)), Expression.Parameter(typeof(sbyte), "sbyteP"), + Expression.Parameter(typeof(short)), Expression.Parameter(typeof(short), "shortP"), + Expression.Parameter(typeof(ushort)), Expression.Parameter(typeof(ushort), "ushortP"), + Expression.Parameter(typeof(int)), Expression.Parameter(typeof(int), "intP"), + Expression.Parameter(typeof(uint)), Expression.Parameter(typeof(uint), "uintP"), + Expression.Parameter(typeof(long)), Expression.Parameter(typeof(long), "longP"), + Expression.Parameter(typeof(ulong)), Expression.Parameter(typeof(ulong), "ulongP"), + Expression.Parameter(typeof(float)), Expression.Parameter(typeof(float), "floatP"), + Expression.Parameter(typeof(double)), Expression.Parameter(typeof(double), "doubleP"), + Expression.Parameter(typeof(decimal)), Expression.Parameter(typeof(decimal), "decimalP"), + Expression.Parameter(typeof(TimeSpan)), Expression.Parameter(typeof(TimeSpan), "timespanP"), + Expression.Parameter(typeof(DateTime)), Expression.Parameter(typeof(DateTime), "datetimeP"), + Expression.Parameter(typeof(string)), Expression.Parameter(typeof(string), "stringP"), + }; + } + + private ParameterExpression[] GetTestVariableExpressions() + { + return new[] { + Expression.Variable(typeof(bool)), Expression.Variable(typeof(bool), "boolP"), + Expression.Variable(typeof(byte)), Expression.Variable(typeof(byte), "byteP"), + Expression.Variable(typeof(sbyte)), Expression.Variable(typeof(sbyte), "sbyteP"), + Expression.Variable(typeof(short)), Expression.Variable(typeof(short), "shortP"), + Expression.Variable(typeof(ushort)), Expression.Variable(typeof(ushort), "ushortP"), + Expression.Variable(typeof(int)), Expression.Variable(typeof(int), "intP"), + Expression.Variable(typeof(uint)), Expression.Variable(typeof(uint), "uintP"), + Expression.Variable(typeof(long)), Expression.Variable(typeof(long), "longP"), + Expression.Variable(typeof(ulong)), Expression.Variable(typeof(ulong), "ulongP"), + Expression.Variable(typeof(float)), Expression.Variable(typeof(float), "floatP"), + Expression.Variable(typeof(double)), Expression.Variable(typeof(double), "doubleP"), + Expression.Variable(typeof(decimal)), Expression.Variable(typeof(decimal), "decimalP"), + Expression.Variable(typeof(TimeSpan)), Expression.Variable(typeof(TimeSpan), "timespanP"), + Expression.Variable(typeof(DateTime)), Expression.Variable(typeof(DateTime), "datetimeP"), + Expression.Variable(typeof(string)), Expression.Variable(typeof(string), "stringP"), + }; + } + + private BinaryExpression[] GetTestBinaryExpressions() + { + return new[] { + //Expression.Add(Expression.Constant(1), Expression.Constant(2)), + //Expression.AddChecked(Expression.Constant(2), Expression.Constant(3)), + //Expression.Subtract(Expression.Constant(4), Expression.Constant(2)), + //Expression.SubtractChecked(Expression.Constant(5), Expression.Constant(6)), + //Expression.Divide(Expression.Constant(2), Expression.Constant(1)), + //Expression.Multiply(Expression.Constant(3), Expression.Constant(5)), + //Expression.MultiplyChecked(Expression.Constant(4), Expression.Constant(4)), + //Expression.Modulo(Expression.Constant(5), Expression.Constant(2)), + Expression.Power(Expression.Constant(2.0), Expression.Constant(4.0)), + + Expression.And(Expression.Constant(10), Expression.Constant(6)), + Expression.Or(Expression.Constant(10), Expression.Constant(6)), + Expression.ExclusiveOr(Expression.Constant(10), Expression.Constant(6)), + Expression.LeftShift(Expression.Constant(256), Expression.Constant(2)), + Expression.RightShift(Expression.Constant(256), Expression.Constant(2)), + + Expression.Equal(Expression.Constant(256), Expression.Constant(2)), + Expression.NotEqual(Expression.Constant(256), Expression.Constant(2)), + Expression.GreaterThan(Expression.Constant(256), Expression.Constant(2)), + Expression.GreaterThanOrEqual(Expression.Constant(256), Expression.Constant(2)), + Expression.LessThan(Expression.Constant(256), Expression.Constant(2)), + Expression.LessThanOrEqual(Expression.Constant(256), Expression.Constant(2)), + + Expression.AndAlso(Expression.Equal(Expression.Constant(256), Expression.Constant(2)), Expression.NotEqual(Expression.Constant(256), Expression.Constant(3))), + Expression.OrElse(Expression.Equal(Expression.Constant(256), Expression.Constant(2)), Expression.NotEqual(Expression.Constant(256), Expression.Constant(3))), + + Expression.Assign(Expression.Variable(typeof(int), "addAssignVar"), Expression.Constant(111)), + + Expression.Coalesce(Expression.Constant("abc"), Expression.Constant("default")), + Expression.ArrayIndex(Expression.Constant( new[] { 2, 8, 7 }), Expression.Constant(2)) + }; + } + + private ConditionalExpression[] GetTestConditionalExpressions() + { + return new[] { + Expression.Condition( + Expression.Equal(Expression.Constant(12), Expression.Constant(12)), + Expression.Constant(111), + Expression.Constant(222)), + Expression.IfThen( + Expression.Equal(Expression.Constant(13), Expression.Constant(13)), + Expression.Constant(333)), + Expression.IfThenElse( + Expression.Equal(Expression.Constant(14), Expression.Constant(14)), + Expression.Constant(222), + Expression.Constant(444)) + }; + } + + private InvocationExpression[] GetTestInvocationExpressions() + { + Expression> largeSumTest = (num1, num2) => (num1 + num2) > 1000; + return new[] { + Expression.Invoke( + largeSumTest, + Expression.Constant(539), + Expression.Constant(281)) + }; + } + + private ListInitExpression[] GetTestListInitExpressions() + { + var listType = typeof(List); + var constructor = listType.GetConstructor(Type.EmptyTypes); + var newListExpression = Expression.New(constructor); + var addMethod = listType.GetMethod("Add"); + return new[] { + Expression.ListInit( + newListExpression, + Expression.ElementInit(addMethod, Expression.Constant("Apple", typeof(string))), + Expression.ElementInit(addMethod, Expression.Constant("Banana", typeof(string))), + Expression.ElementInit(addMethod, Expression.Constant("Cherry", typeof(string))) + ) + }; + } + + private MemberExpression[] GetTestMemberExpressions() + { + var fooType = typeof(Foo); + var prop = fooType.GetProperty(nameof(Foo.IntProperty)); + var field = fooType.GetField(nameof(Foo.IntField)); + + var instance = new Foo() { IntField = 123, IntProperty = 234 }; + + var instanceExp = Expression.Constant(instance); + + return new[] { + Expression.Field(instanceExp, nameof(Foo.IntField)), + Expression.Field(instanceExp, field), + Expression.Property(instanceExp, nameof(Foo.IntProperty)), + Expression.Property(instanceExp, prop), + }; + } + + private NewExpression[] GetTestNewExpressions() + { + var addressType = typeof(Address); + var addressCtor1 = addressType.GetConstructor(Type.EmptyTypes); + var addressCtor2 = addressType.GetConstructor(new Type[] { typeof(string), typeof(string) }); + + var cityProp = addressType.GetProperty("City"); + var zipCodeProp = addressType.GetProperty("ZipCode"); + + var dateTimeType = typeof(DateTime); + var dateTimeCtor1 = dateTimeType.GetConstructor(new[] { typeof(long) }); + var dateTimeCtor2 = dateTimeType.GetConstructor(new[] { typeof(int), typeof(int), typeof(int) }); + + return new[] { + Expression.New(addressCtor1), + Expression.New(addressCtor2, Expression.Constant("City"), Expression.Constant("ZipCode")), + Expression.New(dateTimeCtor1, Expression.Constant(1224585425L)), + Expression.New(dateTimeCtor2, Expression.Constant(21), Expression.Constant(24), Expression.Constant(26)) + }; + } + + private MemberInitExpression[] GetTestMemberInitExressions() + { + var listType = typeof(List); + var constructor = listType.GetConstructor(Type.EmptyTypes); + var newListExpression = Expression.New(constructor); + var addMethod = listType.GetMethod("Add"); + + var fooType = typeof(Foo); + var prop = fooType.GetProperty(nameof(Foo.IntProperty)); + var field = fooType.GetField(nameof(Foo.IntField)); + + var parameter = Expression.Parameter(typeof(int), "i"); + var newExpression1 = Expression.New(fooType); + var binding = Expression.Bind(prop, parameter); + + var init1 = Expression.ElementInit(addMethod, Expression.Constant("Hello")); + var init2 = Expression.ElementInit(addMethod, Expression.Constant("World")); + + var messagesProperty = fooType.GetProperty(nameof(Foo.ListProperty)); + MemberListBinding listBinding = Expression.ListBind(messagesProperty, init1, init2); + NewExpression newExpression2 = Expression.New(fooType); + + var personType = typeof(Person); + var addressType = typeof(Address); + + var homeAddressMember = personType.GetProperty(nameof(Person.HomeAddress)); + var nameMember = personType.GetProperty(nameof(Person.Name)); + var cityMember = addressType.GetProperty(nameof(Address.City)); + var zipCodeMember = addressType.GetProperty(nameof(Address.ZipCode)); + + var cityAssignment = Expression.Bind(cityMember, Expression.Constant("New York")); + var zipCodeAssignment = Expression.Bind(zipCodeMember, Expression.Constant("10001")); + + var addressBinding = Expression.MemberBind(homeAddressMember, cityAssignment, zipCodeAssignment); + var nameAssignment = Expression.Bind(nameMember, Expression.Constant("John Doe")); + + var newPerson = Expression.New(personType); + + return new[] { + Expression.MemberInit(newExpression1, new[] { binding }), + Expression.MemberInit(newExpression2, new MemberBinding[] { listBinding }), + Expression.MemberInit(newPerson, addressBinding, nameAssignment) + }; + } + + private MethodCallExpression[] GetTestMethodCallExpressions() + { + var param1 = Expression.Constant(2, typeof(int)); + var param2 = Expression.Constant(3L, typeof(long)); + var thisType = this.GetType(); + + var nonpublicMethods = thisType.GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); + var publicMethods = thisType.GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); + + var staticLocalMethod = nonpublicMethods + .FirstOrDefault(m => m.Name.StartsWith($"<{nameof(GetTestMethodCallExpressions)}>g__{nameof(SDummyMethod)}")); + + var publicStaticMethod = publicMethods + .FirstOrDefault(m => m.Name.StartsWith($"{nameof(SFromCloneMethodCallExpressionDummy)}")); + + var privateStaticMethod = nonpublicMethods + .FirstOrDefault(m => m.Name.StartsWith($"{nameof(PSFromCloneMethodCallExpressionDummy)}")); + + return new[] { + Expression.Call(publicStaticMethod, param1, param2), + Expression.Call(privateStaticMethod, param1, param2), + Expression.Call(staticLocalMethod, param1, param2), + }; + + static void SDummyMethod(int a, long b) + { } + } + + private NewArrayExpression[] GetTestNewArrayExpressions() + { + return new[] { + Expression.NewArrayBounds(typeof(string), Expression.Constant(1)), + Expression.NewArrayBounds(typeof(string), Expression.Constant(2), Expression.Constant(3)), + Expression.NewArrayInit(typeof(string), Expression.Constant("ABC"), Expression.Constant("DEF")), + }; + } + + private TypeBinaryExpression[] GetTestTypeBinaryExpressions() + { + return new[] { + Expression.TypeIs(Expression.Constant(DateTime.UtcNow), typeof(DateTime)), + Expression.TypeEqual(Expression.Constant(DateTime.UtcNow), typeof(DateTime)) + }; + } + + private UnaryExpression[] GetTestUnaryExpressions() + { + return new[] { + Expression.ArrayLength(Expression.Constant(new int[] { 1,2,3 })), + Expression.Convert(Expression.Constant(23), typeof(long)), + Expression.ConvertChecked(Expression.Constant(23), typeof(long)), + Expression.Decrement(Expression.Constant(24)), + Expression.Increment(Expression.Constant(25)), + Expression.IsFalse(Expression.Constant(true)), + Expression.IsTrue(Expression.Constant(true)), + Expression.Negate(Expression.Constant(-25)), + Expression.NegateChecked(Expression.Constant(-25)), + Expression.Not(Expression.Constant(true)), + Expression.OnesComplement(Expression.Constant(123)), + }; + } + +#pragma warning disable IDE0060 // Remove unused parameter + public static void SFromCloneMethodCallExpressionDummy(int a, long b) { } + private static void PSFromCloneMethodCallExpressionDummy(int a, long b) { } +#pragma warning restore IDE0060 // Remove unused parameter + } + #endregion +} diff --git a/Extensions/Xtensive.Orm.SerializableExpressions.Tests/SerializedQueryTest.cs b/Extensions/Xtensive.Orm.SerializableExpressions.Tests/SerializedQueryTest.cs new file mode 100644 index 0000000000..a02f17a2fb --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions.Tests/SerializedQueryTest.cs @@ -0,0 +1,87 @@ +// Copyright (C) 2010-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Alexis Kochetov +// Created: 2010.02.25 + +using System; +using System.Linq; +using TestCommon.Model; +using Xtensive.Orm.Linq; +using Xtensive.Orm.Providers; +using Xtensive.Orm.Tests; + +namespace Xtensive.Orm.SerializableExpressions.Tests +{ + public class SerializedQueryTest : TestCommon.CommonModelTest + { + public enum SerializerType + { + Json, + DataContractJson, + DataContractXml + } + + protected override void PopulateData() + { + using (var session = Domain.OpenSession()) + using (var tx = session.OpenTransaction()) { + _ = new Bar(session) { Name = "Bar #1", Count = -2 }; + _ = new Bar(session) { Name = "Bar #1", Count = -1 }; + _ = new Bar(session) { Name = "Bar #1", Count = 1 }; + _ = new Bar(session) { Name = "Bar #1", Count = 1 }; + _ = new Bar(session) { Name = "Bar #1", Count = 1 }; + _ = new Bar(session) { Name = "Bar #2", Count = 1 }; + _ = new Bar(session) { Name = "Bar #3", Count = 1 }; + tx.Complete(); + } + } + + [Test] + [TestCase(SerializerType.Json)] + [TestCase(SerializerType.DataContractJson)] + [TestCase(SerializerType.DataContractXml)] + public void MainTest(SerializerType serializerType) + { + Require.AllFeaturesSupported(ProviderFeatures.RowNumber); + + int[] ids; + SerializableExpression serializedExpression; + using (var session = Domain.OpenSession()) + using (var tx = session.OpenTransaction()) { + var query = session.Query.All() + .Where(c => c.Name == "Bar #1") + .Where(c => c.Count > 0) + .Take(5) + .Skip(0); + + var serializableExpression = query.Expression.ToSerializableExpression(); + serializedExpression = CloneExpression(serializableExpression, serializerType); + + ids = query.AsEnumerable().Select(b => b.Id).ToArray(); + Assert.That(ids.Length, Is.GreaterThan(2)); + } + + using (var session = Domain.OpenSession()) + using (var tx = session.OpenTransaction()) { + var deserializedExpression = serializedExpression.ToExpression(); + var deserializedQuery = new Queryable(session.Query.Provider, deserializedExpression); + var result = deserializedQuery.AsEnumerable().Select(b => b.Id).ToArray(); + + Assert.That(result.Length, Is.EqualTo(ids.Length)); + Assert.That(result.SequenceEqual(ids), Is.True); + } + } + + + private SerializableExpression CloneExpression(SerializableExpression serializableExpression, SerializerType serializerType) + { + return serializerType switch { + SerializerType.Json => Cloner.CloneViaJsonSerialization(serializableExpression), + SerializerType.DataContractJson => Cloner.CloneViaJsonSerialization(serializableExpression, useDataContract: true), + SerializerType.DataContractXml => Cloner.CloneViaXmlSerialization(serializableExpression, Cloner.SerializationDomains.System.Value), + _ => throw new NotImplementedException() + }; + } + } +} diff --git a/Extensions/Xtensive.Orm.SerializableExpressions.Tests/Xtensive.Orm.SerializableExpressions.Tests.csproj b/Extensions/Xtensive.Orm.SerializableExpressions.Tests/Xtensive.Orm.SerializableExpressions.Tests.csproj new file mode 100644 index 0000000000..090fd8467c --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions.Tests/Xtensive.Orm.SerializableExpressions.Tests.csproj @@ -0,0 +1,29 @@ + + + + false + true + ..\Extensions.snk + Debug;Release;Debug-NET8;Release-NET8;Debug-NET10;Release-NET10 + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/DataContractConverters/ObjectToInferredTypesConverter.cs b/Extensions/Xtensive.Orm.SerializableExpressions/DataContractConverters/ObjectToInferredTypesConverter.cs new file mode 100644 index 0000000000..5e1d789a24 --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/DataContractConverters/ObjectToInferredTypesConverter.cs @@ -0,0 +1,195 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using Xtensive.Reflection; + +namespace Xtensive.Orm.SerializableExpressions.DataContractConverters +{ + internal sealed class ObjectToInferredTypesConverter + { + public static readonly Lazy Default = new(() => new ObjectToInferredTypesConverter()); + + private readonly Dictionary TypeToSerializableTypeMap = new(); + + private readonly Dictionary> ValueWriters = new(); + private readonly Dictionary> ValueReaders = new(); + private readonly Func EnumReader; + private readonly Func PrimitiveTypesReader; + + public object ToSerializable(object value, Type type) + { + if (type.IsValueType) { + if (!IsNullable(type, out var underlyingType)) { + return ValueWriters.TryGetValue(type, out var converter) ? converter(value) : value; + } + if (value is null) + return null; + else { + return ToSerializable(value, underlyingType); + } + } + else if (type.IsArray) { + var elementType = type.GetElementType(); + + if (!TypeToSerializableTypeMap.TryGetValue(elementType, out var newType)) { + return value; + } + + var array = value as Array; + var newArray = Array.CreateInstance(newType, array.Length); + for (var i = 0; i < array.Length; i++) { + var origItem = array.GetValue(i); + if (origItem != null) { + var newItem = ToSerializable(origItem, elementType); + newArray.SetValue(newItem, i); + } + else { + newArray.SetValue(null, i); + } + } + + return newArray; + } + else { + return value; + } + } + + public object FromSerializable(object value, Type type) + { + if (IsNullable(type, out var underlyingType)) { + if (value is null) { + return null; + } + else { + var deserialized = FromSerializable(value, underlyingType); + var chagedType = Convert.ChangeType(deserialized, underlyingType); + + return Activator.CreateInstance(type, chagedType); + } + } + + if (type.IsArray) { + var array = (Array) value; + var elementType = type.GetElementType(); + var correctArray = Array.CreateInstance(elementType, array.Length); + for (int i = 0; i < array.Length; i++) { + var origValue = array.GetValue(i); + if (origValue is null) + correctArray.SetValue(null, i); + else { + correctArray.SetValue(FromSerializable(origValue, elementType), i); + } + } + return correctArray; + } + if(type.IsEnum) + return EnumReader(value, type); + if(type.IsPrimitive) + return PrimitiveTypesReader(value, type); + if (ValueReaders.TryGetValue(type, out var converter)) { + return converter(value); + } + return value; + } + + private static bool IsNullable(Type type, out Type underlyingType) + { + if (type.IsNullable()) { + underlyingType = Nullable.GetUnderlyingType(type); + return true; + } + + underlyingType = null; + return false; + } + + public ObjectToInferredTypesConverter() + { + var stringType = typeof(string); + var int64Type = typeof(long); + var nullableInt64Type = typeof(long?); + + var dateTimeOffsetType = typeof(DateTimeOffset); + var dateTimeType = typeof(DateTime); + var dateOnlyType = typeof(DateOnly); + var timeOnlyType = typeof(TimeOnly); + var timeSpanType = typeof(TimeSpan); + var guidType = typeof(Guid); + + var nullableDateTimeOffsetType = typeof(DateTime?); + var nullableDateTimeType = typeof(DateTime?); + var nullableDateOnlyType = typeof(DateOnly?); + var nullableTimeOnlyType = typeof(TimeOnly?); + var nullableTimeSpanType = typeof(TimeSpan?); + var nullableGuidType = typeof(Guid?); + + + // Convertsion map + TypeToSerializableTypeMap[dateOnlyType] = stringType; + TypeToSerializableTypeMap[dateTimeType] = stringType; + TypeToSerializableTypeMap[dateTimeOffsetType] = stringType; + TypeToSerializableTypeMap[nullableDateOnlyType] = stringType; + TypeToSerializableTypeMap[nullableDateTimeType] = stringType; + TypeToSerializableTypeMap[nullableDateTimeOffsetType] = stringType; + TypeToSerializableTypeMap[typeof(Int128)] = stringType; + TypeToSerializableTypeMap[typeof(UInt128)] = stringType; + TypeToSerializableTypeMap[typeof(Int128?)] = stringType; + TypeToSerializableTypeMap[typeof(UInt128?)] = stringType; + TypeToSerializableTypeMap[guidType] = stringType; + TypeToSerializableTypeMap[nullableGuidType] = stringType; + + TypeToSerializableTypeMap[timeOnlyType] = int64Type; + TypeToSerializableTypeMap[timeSpanType] = int64Type; + + TypeToSerializableTypeMap[nullableTimeOnlyType] = nullableInt64Type; + TypeToSerializableTypeMap[nullableTimeSpanType] = nullableInt64Type; + + + // Writers + ValueWriters[dateOnlyType] = static (tFromValue) => { + return tFromValue is DateOnly d + ? (object) d.ToDateTime(TimeOnly.FromTimeSpan(TimeSpan.Zero)).ToString("O") + : throw new InvalidCastException(); + }; + + ValueWriters[timeOnlyType] = static (fromValue) => fromValue is TimeOnly t ? (object) t.Ticks : throw new InvalidCastException(); + ValueWriters[timeSpanType] = static (fromValue) => fromValue is TimeSpan ts ? (object) ts.Ticks : throw new InvalidCastException(); + + ValueWriters[dateTimeType] = static (fromValue) => fromValue is DateTime dt ? (object) dt.ToString("O") : throw new InvalidCastException(); + ValueWriters[dateTimeOffsetType] = static (fromValue) => fromValue is DateTimeOffset dto ? (object) dto.ToString("O") : throw new InvalidCastException(); + + Func toStringConverter = static (fromValue) => fromValue.ToString(); + ValueWriters[typeof(Int128)] = toStringConverter; + ValueWriters[typeof(UInt128)] = toStringConverter; + ValueWriters[guidType] = toStringConverter; + + + // Readers + ValueReaders[dateOnlyType] = static (fromValue) => DateOnly.FromDateTime(DateTime.Parse((string) fromValue)); + ValueReaders[timeOnlyType] = static (fromValue) => TimeOnly.FromTimeSpan(TimeSpan.FromTicks((long) fromValue)); + ValueReaders[timeSpanType] = static (fromValue) => TimeSpan.FromTicks((long) fromValue); + ValueReaders[dateTimeType] = static (fromValue) => { + var valueString = (string) fromValue; + var parsed = DateTime.ParseExact(valueString, "O", CultureInfo.InvariantCulture); + if (valueString.EndsWith("Z", StringComparison.OrdinalIgnoreCase)) { + // parsing does not take into account "Z" marker (marks utc kind when ToString("O")), + parsed = parsed.ToUniversalTime(); + } + return parsed; + }; + + ValueReaders[dateTimeOffsetType] = static (fromValue) => DateTimeOffset.ParseExact((string) fromValue, "O", CultureInfo.InvariantCulture); + ValueReaders[typeof(Int128)] = static (fromValue) => Int128.Parse((string) fromValue); + ValueReaders[typeof(UInt128)] = static (fromValue) => UInt128.Parse((string) fromValue); + ValueReaders[guidType] = static (fromValue) => Guid.Parse((string) fromValue); + + EnumReader = static (fromValue, enumType) => Enum.ToObject(enumType, Convert.ChangeType(fromValue, Enum.GetUnderlyingType(enumType))); + PrimitiveTypesReader = static (fromValue, primitiveType) => Convert.ChangeType(fromValue, primitiveType); + } + } +} diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/ExpressionExtensions.cs b/Extensions/Xtensive.Orm.SerializableExpressions/ExpressionExtensions.cs new file mode 100644 index 0000000000..dc71add7de --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/ExpressionExtensions.cs @@ -0,0 +1,32 @@ +using System; +using System.Linq.Expressions; +using Xtensive.Orm.SerializableExpressions.Internals; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// Contains extensions related to s + /// + public static class ExpressionExtensions + { + /// + /// Converts specified to . + /// + /// The expression to convert. + /// Serializable expression that represents . + public static SerializableExpression ToSerializableExpression(this Expression expression) + { + return new ExpressionToSerializableExpressionConverter(expression).Convert(); + } + + /// + /// Converts specified to . + /// + /// The expression to convert. + /// Expression that represents given . + public static Expression ToExpression(this SerializableExpression expression) + { + return new SerializableExpressionToExpressionConverter(expression).Convert(); + } + } +} diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/Internals/ExpressionToSerializableExpressionConverter.cs b/Extensions/Xtensive.Orm.SerializableExpressions/Internals/ExpressionToSerializableExpressionConverter.cs new file mode 100644 index 0000000000..daebbb1253 --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/Internals/ExpressionToSerializableExpressionConverter.cs @@ -0,0 +1,354 @@ +// Copyright (C) 2009-2023 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Kryuchkov +// Created: 2009.05.13 + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Linq.Expressions; +using Xtensive.Core; +using Xtensive.Reflection; + +namespace Xtensive.Orm.SerializableExpressions.Internals +{ + internal sealed class ExpressionToSerializableExpressionConverter + // : Xtensive.Linq.ExpressionVisitor + { + private readonly Dictionary cache = new(); + private readonly Expression source; + + public SerializableExpression Convert() => Visit(source); + + private SerializableExpression Visit(Expression e) + { + if (e == null) + return default(SerializableExpression); + + if (cache.TryGetValue(e, out var result)) + return result; + + switch (e.NodeType) { + case ExpressionType.Negate: + case ExpressionType.NegateChecked: + case ExpressionType.Not: + case ExpressionType.Convert: + case ExpressionType.ConvertChecked: + case ExpressionType.ArrayLength: + case ExpressionType.Quote: + case ExpressionType.TypeAs: + case ExpressionType.Decrement: + case ExpressionType.Increment: + case ExpressionType.IsFalse: + case ExpressionType.IsTrue: + case ExpressionType.OnesComplement: + result = VisitUnary((UnaryExpression) e); + break; + case ExpressionType.Add: + case ExpressionType.AddChecked: + case ExpressionType.Subtract: + case ExpressionType.SubtractChecked: + case ExpressionType.Multiply: + case ExpressionType.MultiplyChecked: + case ExpressionType.Divide: + case ExpressionType.Modulo: + case ExpressionType.And: + case ExpressionType.AndAlso: + case ExpressionType.Or: + case ExpressionType.OrElse: + case ExpressionType.LessThan: + case ExpressionType.LessThanOrEqual: + case ExpressionType.GreaterThan: + case ExpressionType.GreaterThanOrEqual: + case ExpressionType.Equal: + case ExpressionType.NotEqual: + case ExpressionType.Coalesce: + case ExpressionType.ArrayIndex: + case ExpressionType.RightShift: + case ExpressionType.LeftShift: + case ExpressionType.ExclusiveOr: + case ExpressionType.Power: + case ExpressionType.Assign: + result = VisitBinary((BinaryExpression) e); + break; + case ExpressionType.TypeIs: + case ExpressionType.TypeEqual: + result = VisitTypeIs((TypeBinaryExpression) e); + break; + case ExpressionType.Conditional: + result = VisitConditional((ConditionalExpression) e); + break; + case ExpressionType.Constant: + result = VisitConstant((ConstantExpression) e); + break; + case ExpressionType.Default: + result = VisitDefault((DefaultExpression) e); + break; + case ExpressionType.Parameter: + result = VisitParameter((ParameterExpression) e); + break; + case ExpressionType.MemberAccess: + result = VisitMemberAccess((MemberExpression) e); + break; + case ExpressionType.Call: + result = VisitMethodCall((MethodCallExpression) e); + break; + case ExpressionType.Lambda: + result = VisitLambda((LambdaExpression) e); + break; + case ExpressionType.New: + result = VisitNew((NewExpression) e); + break; + case ExpressionType.NewArrayInit: + case ExpressionType.NewArrayBounds: + result = VisitNewArray((NewArrayExpression) e); + break; + case ExpressionType.Invoke: + result = VisitInvocation((InvocationExpression) e); + break; + case ExpressionType.MemberInit: + result = VisitMemberInit((MemberInitExpression) e); + break; + case ExpressionType.ListInit: + result = VisitListInit((ListInitExpression) e); + break; + default: + result = VisitUnknown(e); + break; + } + + cache[e] = result; + return result; + } + + #region Visitors + + private SerializableUnaryExpression VisitUnary(UnaryExpression u) + { + return new SerializableUnaryExpression { + NodeType = u.NodeType, + Type = u.Type, + Method = u.Method, + Operand = Visit(u.Operand) + }; + } + + private SerializableBinaryExpression VisitBinary(BinaryExpression b) + { + return new SerializableBinaryExpression { + NodeType = b.NodeType, + Type = b.Type, + Method = b.Method, + IsLiftedToNull = b.IsLiftedToNull, + Left = Visit(b.Left), + Right = Visit(b.Right) + }; + } + + private SerializableTypeBinaryExpression VisitTypeIs(TypeBinaryExpression tb) + { + return new SerializableTypeBinaryExpression { + NodeType = tb.NodeType, + Type = tb.Type, + Expression = Visit(tb.Expression), + TypeOperand = tb.TypeOperand + }; + } + + private SerializableConstantExpression VisitConstant(ConstantExpression c) + { + return new SerializableConstantExpression { + NodeType = c.NodeType, + Type = c.Type, + Value = c.Value + }; + } + + private SerializableDefaultExpression VisitDefault(DefaultExpression d) + { + return new SerializableDefaultExpression { + NodeType = d.NodeType, + Type = d.Type + }; + } + + private SerializableConditionalExpression VisitConditional(ConditionalExpression c) + { + return new SerializableConditionalExpression { + NodeType = c.NodeType, + Type = c.Type, + Test = Visit(c.Test), + IfTrue = Visit(c.IfTrue), + IfFalse = Visit(c.IfFalse) + }; + } + + private SerializableParameterExpression VisitParameter(ParameterExpression p) + { + return new SerializableParameterExpression { + NodeType = p.NodeType, + Type = p.Type, + Name = p.Name + }; + } + + private SerializableMemberExpression VisitMemberAccess(MemberExpression m) + { + return new SerializableMemberExpression { + NodeType = m.NodeType, + Type = m.Type, + Expression = Visit(m.Expression), + Member = m.Member + }; + } + + private SerializableMethodCallExpression VisitMethodCall(MethodCallExpression mc) + { + return new SerializableMethodCallExpression { + NodeType = mc.NodeType, + Type = mc.Type, + Method = mc.Method, + Arguments = VisitExpressionList(mc.Arguments), + Object = Visit(mc.Object) + }; + } + + private SerializableLambdaExpression VisitLambda(LambdaExpression l) + { + return new SerializableLambdaExpression { + NodeType = l.NodeType, + Type = l.Type, + Body = Visit(l.Body), + Parameters = (l.Parameters.Count == 0) + ? Array.Empty() + : l.Parameters.Select(p => (SerializableParameterExpression) Visit(p)).ToArray() + }; + } + + private SerializableNewExpression VisitNew(NewExpression n) + { + return new SerializableNewExpression { + NodeType = n.NodeType, + Type = n.Type, + Constructor = n.Constructor, + Arguments = VisitExpressionList(n.Arguments), + Members = n.Members?.Select(static m => (SerializableMemberInfo) m).ToArray() + }; + } + + private SerializableMemberInitExpression VisitMemberInit(MemberInitExpression mi) + { + return new SerializableMemberInitExpression { + NodeType = mi.NodeType, + Type = mi.Type, + Bindings = VisitMemberBindingSequence(mi.Bindings), + NewExpression = (SerializableNewExpression) Visit(mi.NewExpression) + }; + } + + private SerializableListInitExpression VisitListInit(ListInitExpression li) + { + return new SerializableListInitExpression { + NodeType = li.NodeType, + Type = li.Type, + NewExpression = (SerializableNewExpression) Visit(li.NewExpression), + Initializers = VisitElementInitSequence(li.Initializers) + }; + } + + private SerializableNewArrayExpression VisitNewArray(NewArrayExpression na) + { + return new SerializableNewArrayExpression { + NodeType = na.NodeType, + Type = na.Type, + Expressions = VisitExpressionList(na.Expressions) + }; + } + + private SerializableInvocationExpression VisitInvocation(InvocationExpression i) + { + return new SerializableInvocationExpression { + NodeType = i.NodeType, + Type = i.Type, + Arguments = VisitExpressionList(i.Arguments), + Expression = Visit(i.Expression) + }; + } + + private SerializableExpression VisitUnknown(Expression e) + { + throw new NotSupportedException($"Unknown Expression : {e.GetType().GetShortName()} ({e.NodeType})"); + } + + #endregion + + #region Helper methods + + private SerializableMemberBinding[] VisitMemberBindingSequence(IEnumerable bindings) + { + var result = new List(); + foreach (var binding in bindings) + switch (binding.BindingType) { + case MemberBindingType.Assignment: + result.Add(new SerializableMemberAssignment + { + BindingType = MemberBindingType.Assignment, + Member = binding.Member, + Expression = Visit(((MemberAssignment) binding).Expression) + }); + break; + case MemberBindingType.ListBinding: + result.Add(new SerializableMemberListBinding + { + BindingType = MemberBindingType.ListBinding, + Member = binding.Member, + Initializers = VisitElementInitSequence(((MemberListBinding) binding).Initializers) + }); + break; + case MemberBindingType.MemberBinding: + result.Add(new SerializableMemberMemberBinding + { + BindingType = MemberBindingType.MemberBinding, + Member = binding.Member, + Bindings = VisitMemberBindingSequence(((MemberMemberBinding) binding).Bindings) + }); + break; + default: + throw new ArgumentOutOfRangeException(); + } + return result.ToArray(); + } + + private SerializableElementInit[] VisitElementInitSequence(IEnumerable initializers) + { + return initializers + .Select(initializer => new SerializableElementInit + { + AddMethod = initializer.AddMethod, + Arguments = VisitExpressionList(initializer.Arguments) + }) + .ToArray(); + } + + private SerializableExpression[] VisitExpressionList(ReadOnlyCollection expressions) + where TExpression : Expression + { + var results = new List(expressions.Count); + for (int i = 0, n = expressions.Count; i < n; i++) { + var p = Visit(expressions[i]); + results.Add(p); + } + return results.ToArray(); + } + + #endregion + + public ExpressionToSerializableExpressionConverter(Expression source) + //: base(true) + { + this.source = source; + } + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/Internals/ReflectionExtensions.cs b/Extensions/Xtensive.Orm.SerializableExpressions/Internals/ReflectionExtensions.cs new file mode 100644 index 0000000000..35fc0c2546 --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/Internals/ReflectionExtensions.cs @@ -0,0 +1,19 @@ +// Copyright (C) 2010 Xtensive LLC. +// All rights reserved. +// For conditions of distribution and use, see license. +// Created by: Alexis Kochetov +// Created: 2010.02.25 + +using System; + +namespace Xtensive.Orm.SerializableExpressions.Internals +{ + internal static class ReflectionExtensions + { + public static string ToSerializableForm(this Type type) + => type?.AssemblyQualifiedName; + + public static Type GetTypeFromSerializableForm(this string serializedValue) + => serializedValue is null ? null : Type.GetType(serializedValue); + } +} diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/Internals/SerializableExpressionToExpressionConverter.cs b/Extensions/Xtensive.Orm.SerializableExpressions/Internals/SerializableExpressionToExpressionConverter.cs similarity index 79% rename from Orm/Xtensive.Orm/Linq/SerializableExpressions/Internals/SerializableExpressionToExpressionConverter.cs rename to Extensions/Xtensive.Orm.SerializableExpressions/Internals/SerializableExpressionToExpressionConverter.cs index 877d0c4314..123a4ae919 100644 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/Internals/SerializableExpressionToExpressionConverter.cs +++ b/Extensions/Xtensive.Orm.SerializableExpressions/Internals/SerializableExpressionToExpressionConverter.cs @@ -10,8 +10,9 @@ using System.Linq.Expressions; using System.Reflection; using Xtensive.Core; +using Xtensive.Linq; -namespace Xtensive.Linq.SerializableExpressions.Internals +namespace Xtensive.Orm.SerializableExpressions.Internals { internal sealed class SerializableExpressionToExpressionConverter { @@ -29,8 +30,8 @@ public LambdaParameterScope(SerializableExpressionToExpressionConverter converte } private readonly SerializableExpression source; - private readonly Dictionary cache; - private readonly Stack> parameterScopes; + private readonly Dictionary cache = new(); + private readonly Stack> parameterScopes = new(); public Expression Convert() { @@ -41,15 +42,14 @@ public Expression Convert() private Expression Visit(SerializableExpression e) { - if (e == null) + if (e is null) return null; Expression result; if (cache.TryGetValue(e, out result)) return result; - switch (e.NodeType) - { + switch (e.NodeType) { case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.Not: @@ -63,7 +63,7 @@ private Expression Visit(SerializableExpression e) case ExpressionType.IsFalse: case ExpressionType.IsTrue: case ExpressionType.OnesComplement: - result = VisitUnary((SerializableUnaryExpression)e); + result = VisitUnary((SerializableUnaryExpression) e); break; case ExpressionType.Add: case ExpressionType.AddChecked: @@ -90,50 +90,50 @@ private Expression Visit(SerializableExpression e) case ExpressionType.ExclusiveOr: case ExpressionType.Power: case ExpressionType.Assign: - result = VisitBinary((SerializableBinaryExpression)e); + result = VisitBinary((SerializableBinaryExpression) e); break; case ExpressionType.TypeIs: - result = VisitTypeIs((SerializableTypeBinaryExpression)e); + result = VisitTypeIs((SerializableTypeBinaryExpression) e); break; case ExpressionType.TypeEqual: result = VisitTypeEqual((SerializableTypeBinaryExpression) e); break; case ExpressionType.Conditional: - result = VisitConditional((SerializableConditionalExpression)e); + result = VisitConditional((SerializableConditionalExpression) e); break; case ExpressionType.Constant: - result = VisitConstant((SerializableConstantExpression)e); + result = VisitConstant((SerializableConstantExpression) e); break; case ExpressionType.Default: - result = VisitDefault((SerializableDefaultExpression)e); + result = VisitDefault((SerializableDefaultExpression) e); break; case ExpressionType.Parameter: - result = VisitParameter((SerializableParameterExpression)e); + result = VisitParameter((SerializableParameterExpression) e); break; case ExpressionType.MemberAccess: - result = VisitMemberAccess((SerializableMemberExpression)e); + result = VisitMemberAccess((SerializableMemberExpression) e); break; case ExpressionType.Call: - result = VisitMethodCall((SerializableMethodCallExpression)e); + result = VisitMethodCall((SerializableMethodCallExpression) e); break; case ExpressionType.Lambda: - result = VisitLambda((SerializableLambdaExpression)e); + result = VisitLambda((SerializableLambdaExpression) e); break; case ExpressionType.New: - result = VisitNew((SerializableNewExpression)e); + result = VisitNew((SerializableNewExpression) e); break; case ExpressionType.NewArrayInit: case ExpressionType.NewArrayBounds: - result = VisitNewArray((SerializableNewArrayExpression)e); + result = VisitNewArray((SerializableNewArrayExpression) e); break; case ExpressionType.Invoke: - result = VisitInvocation((SerializableInvocationExpression)e); + result = VisitInvocation((SerializableInvocationExpression) e); break; case ExpressionType.MemberInit: - result = VisitMemberInit((SerializableMemberInitExpression)e); + result = VisitMemberInit((SerializableMemberInitExpression) e); break; case ExpressionType.ListInit: - result = VisitListInit((SerializableListInitExpression)e); + result = VisitListInit((SerializableListInitExpression) e); break; default: throw new ArgumentException(); @@ -145,7 +145,7 @@ private Expression Visit(SerializableExpression e) private Expression VisitUnary(SerializableUnaryExpression u) { - return Expression.MakeUnary(u.NodeType, Visit(u.Operand), u.Type, u.Method); + return Expression.MakeUnary(u.NodeType, Visit(u.Operand), (Type) u.Type, (MethodInfo) u.Method); } private Expression VisitBinary(SerializableBinaryExpression b) @@ -155,17 +155,17 @@ private Expression VisitBinary(SerializableBinaryExpression b) private Expression VisitTypeIs(SerializableTypeBinaryExpression tb) { - return Expression.TypeIs(Visit(tb.Expression), tb.TypeOperand); + return Expression.TypeIs(Visit(tb.Expression), (Type) tb.TypeOperand); } private Expression VisitTypeEqual(SerializableTypeBinaryExpression tb) { - return Expression.TypeEqual(Visit(tb.Expression), tb.TypeOperand); + return Expression.TypeEqual(Visit(tb.Expression), (Type) tb.TypeOperand); } private Expression VisitConstant(SerializableConstantExpression c) { - return Expression.Constant(c.Value, c.Type); + return Expression.Constant(c.Value, (Type)c.Type); } private Expression VisitDefault(SerializableDefaultExpression d) @@ -186,7 +186,7 @@ private Expression VisitParameter(SerializableParameterExpression p) private Expression VisitMemberAccess(SerializableMemberExpression m) { var target = Visit(m.Expression); - return m.Member switch { + return (MemberInfo) m.Member switch { FieldInfo field => Expression.Field(target, field), PropertyInfo property => Expression.Property(target, property), MethodInfo method => Expression.Property(target, method), @@ -196,7 +196,7 @@ private Expression VisitMemberAccess(SerializableMemberExpression m) private Expression VisitMethodCall(SerializableMethodCallExpression mc) { - return Expression.Call(Visit(mc.Object), mc.Method, VisitExpressionSequence(mc.Arguments)); + return Expression.Call(Visit(mc.Object), (MethodInfo)mc.Method, VisitExpressionSequence(mc.Arguments)); } private Expression VisitLambda(SerializableLambdaExpression l) @@ -209,10 +209,10 @@ private Expression VisitLambda(SerializableLambdaExpression l) private Expression VisitNew(SerializableNewExpression n) { - if (n.Constructor == null) - return Expression.New(n.Type); + if (n.Constructor is null) + return Expression.New((Type) n.Type); if (n.Members != null && n.Members.Length > 0) - return Expression.New(n.Constructor, VisitExpressionSequence(n.Arguments), n.Members); + return Expression.New(n.Constructor, VisitExpressionSequence(n.Arguments), n.Members?.Select(static m => (MemberInfo) m)); return Expression.New(n.Constructor, VisitExpressionSequence(n.Arguments)); } @@ -229,12 +229,12 @@ private Expression VisitListInit(SerializableListInitExpression li) private Expression VisitNewArray(SerializableNewArrayExpression na) { switch (na.NodeType) { - case ExpressionType.NewArrayInit: - return Expression.NewArrayInit(na.Type.GetElementType(), VisitExpressionSequence(na.Expressions)); - case ExpressionType.NewArrayBounds: - return Expression.NewArrayBounds(na.Type.GetElementType(), VisitExpressionSequence(na.Expressions)); - default: - throw new ArgumentException(); + case ExpressionType.NewArrayInit: + return Expression.NewArrayInit(((Type) na.Type).GetElementType(), VisitExpressionSequence(na.Expressions)); + case ExpressionType.NewArrayBounds: + return Expression.NewArrayBounds(((Type) na.Type).GetElementType(), VisitExpressionSequence(na.Expressions)); + default: + throw new ArgumentException(); } } @@ -245,28 +245,29 @@ private Expression VisitInvocation(SerializableInvocationExpression i) private IEnumerable VisitMemberBindingSequence(IEnumerable bindings) { - foreach (var binding in bindings) + foreach (var binding in bindings) { switch (binding.BindingType) { - case MemberBindingType.Assignment: - yield return Expression.Bind(binding.Member, - Visit(((SerializableMemberAssignment) binding).Expression)); - break; - case MemberBindingType.MemberBinding: - yield return Expression.MemberBind(binding.Member, - VisitMemberBindingSequence(((SerializableMemberMemberBinding) binding).Bindings)); - break; - case MemberBindingType.ListBinding: - yield return Expression.ListBind(binding.Member, VisitElementInitSequence(((SerializableMemberListBinding) binding).Initializers)); - break; - default: - throw new ArgumentOutOfRangeException(); + case MemberBindingType.Assignment: + yield return Expression.Bind(binding.Member, + Visit(((SerializableMemberAssignment) binding).Expression)); + break; + case MemberBindingType.MemberBinding: + yield return Expression.MemberBind(binding.Member, + VisitMemberBindingSequence(((SerializableMemberMemberBinding) binding).Bindings)); + break; + case MemberBindingType.ListBinding: + yield return Expression.ListBind((MemberInfo) binding.Member, VisitElementInitSequence(((SerializableMemberListBinding) binding).Initializers)); + break; + default: + throw new ArgumentOutOfRangeException(); } + } } private IEnumerable VisitElementInitSequence(IEnumerable initializers) { return initializers.Select(initializer => - Expression.ElementInit(initializer.AddMethod, VisitExpressionSequence(initializer.Arguments))); + Expression.ElementInit((MethodInfo) initializer.AddMethod, VisitExpressionSequence(initializer.Arguments))); } private IEnumerable VisitExpressionSequence(IEnumerable expressions) @@ -274,7 +275,7 @@ private IEnumerable VisitExpressionSequence(IEnumerable expres { return expressions.Select(e => Visit(e)); } - + private LambdaParameterScope CreateParameterScope(IReadOnlyList lambdaParameters) { var parameters = new Dictionary(lambdaParameters.Count); @@ -315,8 +316,6 @@ private ParameterExpression FindParameterSlow(Type type, string name) public SerializableExpressionToExpressionConverter(SerializableExpression source) { this.source = source; - cache = new Dictionary(); - parameterScopes = new Stack>(); } } } \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/JsonConverters/ObjectToInferredTypesConverter.cs b/Extensions/Xtensive.Orm.SerializableExpressions/JsonConverters/ObjectToInferredTypesConverter.cs new file mode 100644 index 0000000000..a9f7c7ad75 --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/JsonConverters/ObjectToInferredTypesConverter.cs @@ -0,0 +1,100 @@ +using System; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions.JsonConverters +{ + /// + /// Json converter that helps to serialize/deserialize different values which are cast to object. + /// + internal sealed class ObjectToInferredTypesConverter : JsonConverter + { + private const string ActualValueProperty = "ActualValue"; + private const string ObjectTypeProperty = "ObjectType"; + + /// + public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + EnsureStartObject(ref reader); + + var runtimeType = GetObjectType(ref reader, options); + + _ = reader.Read(); + if (reader.TokenType is not JsonTokenType.PropertyName) + throw WrongStructurePropertyExpected(); + var propertyName = reader.GetString(); + var expectedPropertyName = ApplyNamingPolicy(options, ActualValueProperty); + if (propertyName != expectedPropertyName) + throw WrongStructurePropertyNameExpected(expectedPropertyName, propertyName); + var value = JsonSerializer.Deserialize(ref reader, runtimeType, options); + + _ = reader.Read(); + EnsureEndObject( ref reader); + + return value; + } + + /// + public override void Write(Utf8JsonWriter writer, object objectToWrite, JsonSerializerOptions options) + { + var runtimeType = objectToWrite.GetType(); + if (runtimeType == typeof(object)) { + writer.WriteStartObject(); + writer.WriteEndObject(); + return; + } + writer.WriteStartObject(); + writer.WriteString(ApplyNamingPolicy(options, ObjectTypeProperty), runtimeType.AssemblyQualifiedName); + + writer.WritePropertyName(ApplyNamingPolicy(options,ActualValueProperty)); + JsonSerializer.Serialize(writer, objectToWrite, runtimeType, options); + + writer.WriteEndObject(); + } + + private static Type GetObjectType(ref Utf8JsonReader reader, JsonSerializerOptions options) + { + _ = reader.Read(); + if (reader.TokenType is not JsonTokenType.PropertyName) + throw WrongStructurePropertyExpected(); + + string propertyName = reader.GetString(); + var expectedPropertyName = ApplyNamingPolicy(options, ObjectTypeProperty); + if (propertyName != expectedPropertyName) + throw WrongStructurePropertyNameExpected(expectedPropertyName, propertyName); + + _ = reader.Read(); + if (reader.TokenType is not JsonTokenType.String) + throw WrongStructure("Wrong type of return type property"); + var typeName = reader.GetString(); + return Type.GetType(typeName); + } + + private static string ApplyNamingPolicy(JsonSerializerOptions options, string propertyName) + { + var policy = options.PropertyNamingPolicy; + if (policy is null) + return propertyName; + return options.PropertyNamingPolicy.ConvertName(propertyName); + } + + private static void EnsureStartObject(ref Utf8JsonReader reader) + { + if (reader.TokenType is not JsonTokenType.StartObject) + throw WrongStructure("Starting of object expected."); + } + + private static void EnsureEndObject(ref Utf8JsonReader reader) + { + if (reader.TokenType != JsonTokenType.EndObject) + throw WrongStructure("End of object expected."); + } + + private static JsonException WrongStructurePropertyExpected() => WrongStructure("Property expected"); + + private static JsonException WrongStructurePropertyNameExpected(string expected, string actual) + => WrongStructure($"Property '{expected}' expected, but was '{actual}'"); + + private static JsonException WrongStructure(string details) => new ($"Wrong Structure: {details}."); + } +} diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/NugetContent/ReadMe.md b/Extensions/Xtensive.Orm.SerializableExpressions/NugetContent/ReadMe.md new file mode 100644 index 0000000000..d5a4c4a170 --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/NugetContent/ReadMe.md @@ -0,0 +1,177 @@ +Xtensive.Orm.SerializableExpression +===================== + +Summary +------- +Allows to convert System.Linq.Expression instances to serializable to json form. + +Prerequisites +------------- +DataObjects.Net 7.3.x or later (http://dataobjects.net) + +Demo +---- + +1) Serialization to Json (via System.Text.Json.JsonSerializer) + +```csharp +// convert System.Linq.Expresson into serializable form +var serializableExpression = expression.ToSerializableExpression(); + +// we recommend to reserve references in case json will be deserializalized. +// for one-way serialization it is not so important +var options = new JsonSerializerOptions() { WriteIndented = true, ReferenceHandler = ReferenceHandler.Preserve }; +var json = JsonSerializer.Serialize(serializableExpression, options); +``` + + +2) Deserialization from Json (via System.Text.Json.JsonSerializer) + +```csharp + +// we recommend to reserve references in case json will be deserializalized. +// for one-way serialization it is not so important +// use same settings for deserialization +var options = new JsonSerializerOptions() { WriteIndented = true, ReferenceHandler = ReferenceHandler.Preserve }; + +var serializableExpression = JsonSerializer.Deserialize(json, options); + +var expression = serializableExpression.ToExpression(); +``` + + +3) Serialization to Json (via System.Runtime.Serialization.Json.DataContractJsonSerializer) + +```csharp +// convert System.Linq.Expresson into serializable form +var serializableExpression = expression.ToSerializableExpression(); + +// define types which appear in expresson (types of constants for example), apart from SerializableExpression descendants +var knownTypes = new Type[] { typeof (int), typeof (long), typeof (string) }; + +var settings = new DataContractJsonSerializerSettings { KnownTypes = knownTypes }; + +var serializer = new DataContractJsonSerializer(typeof(SerializableExpression), settings); + +string json = null; +using (var stream = new MemoryStream()) { + // Write the object to the stream + serializer.WriteObject(stream, serializableExpression); + + // Convert the stream byte array into a UTF-8 string + json = Encoding.UTF8.GetString(stream.ToArray()); +} + +``` + +4) Deserialization from Json (via System.Runtime.Serialization.Json.DataContractJsonSerializer) + +```csharp +var serializableExpression = expression.ToSerializableExpression(); + +// define types which appear in expresson (types of constants for example), apart from SerializableExpression descendants +var knownTypes = new Type[] { typeof (int), typeof (long), typeof (string) }; + +var settings = new DataContractJsonSerializerSettings { KnownTypes = knownTypes }; + +var serializer = new DataContractJsonSerializer(typeof(SerializableExpression), settings); + +SerializableExpression serializableExpression = null; + +// convert json string into memory stream to be read from +using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json))) { + // read an object + serializableExpression = (SerializableExpression) serializer.ReadObject(ms); +} + +var expression = serializableExpression.ToExpression(); + +``` + +5) Serialization to Xml (via System.Runtime.Serialization.DataContractSerializer) + +```csharp +// convert System.Linq.Expresson into serializable form +var serializableExpression = expression.ToSerializableExpression(); + +// define types which appear in expresson (types of constants for example), apart from SerializableExpression descendants +var knownTypes = new Type[] { typeof (int), typeof (long), typeof (string) }; + +// we recommend to reserve references in case xml will be deserializalized. +// for one-way serialization it is not so important +var settings = new DataContractSerializerSettings { + KnownTypes = SystemTypes, + PreserveObjectReferences = true +}; + +var serializer = new DataContractSerializer(typeof(SerializableExpression), settings); + +string json = null; +using (var stream = new MemoryStream()) { + // Write the object to the stream + serializer.WriteObject(stream, serializableExpression); + + // Convert the stream byte array into a UTF-8 string + json = Encoding.UTF8.GetString(stream.ToArray()); +} + +``` + +6) Deserialization to Xml (via System.Runtime.Serialization.DataContractSerializer) + +```csharp +// define types which appear in expresson (types of constants for example), apart from SerializableExpression descendants +var knownTypes = new Type[] { typeof (int), typeof (long), typeof (string) }; + +// we recommend to reserve references in case xml will be deserializalized. +// for one-way serialization it is not so important +var settings = new DataContractSerializerSettings { + KnownTypes = SystemTypes, + PreserveObjectReferences = true +}; + +var serializer = new DataContractSerializer(typeof(SerializableExpression), settings); + +SerializableExpression serializableExpression = null; + +// convert json string into memory stream to be read from +using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json))) { + // read an object + serializableExpression = (SerializableExpression) serializer.ReadObject(stream); +} + +var expression = serializableExpression.ToExpression(); + +``` + +7) Serialize and deserialize query expression + +```csharp +string json; + +using (var session = domain.OpenSession()) +using (var tx = session.OpenTransaction()) { + + var query = session.Query.All() + .Where(c => c.Name == "Bar #1") + .Where(c => c.Count > 0) + .Take(5) + .Skip(0); + + var serializableExpression = query.Expression.ToSerializableExpression(); + + var options = new JsonSerializerOptions() { WriteIndented = true, ReferenceHandler = ReferenceHandler.Preserve }; + json = JsonSerializer.Serialize(serializableExpression, options); +} + +using (var session = domain.OpenSession()) +using (var tx = session.OpenTransaction()) { + + var options = new JsonSerializerOptions() { WriteIndented = true, ReferenceHandler = ReferenceHandler.Preserve }; + var serializableExpression = JsonSerializer.Deserialize(json, options); + + var queryExpression = serializedExpression.ToExpression(); + var query = new Queryable(session.Query.Provider, queryExpression); + var queryResult = query.ToArray(); +} +``` \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableBinaryExpression.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableBinaryExpression.cs new file mode 100644 index 0000000000..e25267d2cc --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableBinaryExpression.cs @@ -0,0 +1,41 @@ +// Copyright (C) 2009-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Krjuchkov +// Created: 2009.05.12 + +using System; +using System.Linq.Expressions; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// A serializable representation of . + /// + [DataContract] + public sealed class SerializableBinaryExpression : SerializableExpression + { + /// + /// + /// + [DataMember, JsonInclude] + public bool IsLiftedToNull; + /// + /// . + /// + [DataMember, JsonInclude] + public SerializableExpression Left; + /// + /// + /// + [DataMember, JsonInclude] + public SerializableExpression Right; + /// + /// + /// + [DataMember, JsonInclude] + public SerializableMethodInfo Method; + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableConditionalExpression.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableConditionalExpression.cs new file mode 100644 index 0000000000..a501fe8233 --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableConditionalExpression.cs @@ -0,0 +1,36 @@ +// Copyright (C) 2009-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Krjuchkov +// Created: 2009.05.12 + +using System; +using System.Linq.Expressions; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// A serializable representation of . + /// + [DataContract] + public sealed class SerializableConditionalExpression : SerializableExpression + { + /// + /// + /// + [DataMember, JsonInclude] + public SerializableExpression Test; + /// + /// + /// + [DataMember, JsonInclude] + public SerializableExpression IfTrue; + /// + /// + /// + [DataMember, JsonInclude] + public SerializableExpression IfFalse; + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableConstantExpression.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableConstantExpression.cs new file mode 100644 index 0000000000..b6d21abace --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableConstantExpression.cs @@ -0,0 +1,40 @@ +// Copyright (C) 2009-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Krjuchkov +// Created: 2009.05.12 + +using System; +using System.Linq.Expressions; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// A serializable representation of . + /// + [DataContract] + public sealed class SerializableConstantExpression : SerializableExpression + { + /// + /// + /// + [IgnoreDataMember] + [JsonInclude, JsonConverter(typeof(JsonConverters.ObjectToInferredTypesConverter))] + public object Value; + + /// + /// For DataContractSerializer serialization only. + /// + #pragma warning disable IDE0051 + [JsonIgnore] + [DataMember(Name = nameof(Value))] + private object SerializableValue + { + get { return DataContractConverters.ObjectToInferredTypesConverter.Default.Value.ToSerializable(Value, Type); } + set { Value = DataContractConverters.ObjectToInferredTypesConverter.Default.Value.FromSerializable(value, Type); } + } + #pragma warning restore IDE0051 + } +} diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableConstructorInfo.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableConstructorInfo.cs new file mode 100644 index 0000000000..1e39064586 --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableConstructorInfo.cs @@ -0,0 +1,67 @@ +// Copyright (C) 2009-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Krjuchkov +// Created: 2009.05.12 + +using System; +using System.Linq; +using System.Reflection; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// A serializable representation of . + /// + [DataContract] + public sealed class SerializableConstructorInfo + { + /// + /// See . + /// + [DataMember, JsonInclude] + public string DeclaringType; + + /// + /// Constructor signature. + /// + [DataMember, JsonInclude] + public string Ctor; + + #region Cast operators + + /// + /// Implicit conversion of to . + /// + /// The type to create reference for. + /// The result of conversion. + public static implicit operator SerializableConstructorInfo(ConstructorInfo ctor) + { + if (ctor == null) + return null; + return new SerializableConstructorInfo { + DeclaringType = ctor.DeclaringType.AssemblyQualifiedName, + Ctor = ctor.ToString() + }; + } + + /// + /// Implicit conversion of to . + /// + /// The serializable version to convert. + /// The result of conversion. + public static implicit operator ConstructorInfo(SerializableConstructorInfo reference) + { + if (reference == null) + return null; + + var name = reference.Ctor; + var ctor = Type.GetType(reference.DeclaringType).GetConstructors().First(m => m.ToString() == name); + return ctor; + } + + #endregion + } +} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableDefaultExpression.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableDefaultExpression.cs similarity index 58% rename from Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableDefaultExpression.cs rename to Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableDefaultExpression.cs index eae7cd156e..188f8efef7 100644 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableDefaultExpression.cs +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableDefaultExpression.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2023 Xtensive LLC. +// Copyright (C) 2023-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. @@ -6,21 +6,13 @@ using System.Linq.Expressions; using System.Runtime.Serialization; -namespace Xtensive.Linq.SerializableExpressions +namespace Xtensive.Orm.SerializableExpressions { /// /// A serializable representation of . /// - [Serializable] + [DataContract] public sealed class SerializableDefaultExpression : SerializableExpression { - public SerializableDefaultExpression() - { - } - - public SerializableDefaultExpression(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableElementInit.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableElementInit.cs new file mode 100644 index 0000000000..257be5fae1 --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableElementInit.cs @@ -0,0 +1,31 @@ +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Kryuchkov +// Created: 2009.05.14 + +using System; +using System.Linq.Expressions; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// A serializable representation of . + /// + [DataContract] + public sealed class SerializableElementInit + { + /// + /// + /// + [DataMember, JsonInclude] + public SerializableMethodInfo AddMethod; + /// + /// + /// + [DataMember, JsonInclude] + public SerializableExpression[] Arguments; + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableExpression.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableExpression.cs new file mode 100644 index 0000000000..dabead4ca9 --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableExpression.cs @@ -0,0 +1,48 @@ +// Copyright (C) 2009-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Krjuchkov +// Created: 2009.05.12 + +using System; +using System.Linq; +using System.Linq.Expressions; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// A serializable representation of . + /// + [DataContract] + [KnownType(typeof(SerializableBinaryExpression)), JsonDerivedType(typeof(SerializableBinaryExpression), nameof(SerializableBinaryExpression))] + [KnownType(typeof(SerializableConditionalExpression)), JsonDerivedType(typeof(SerializableConditionalExpression), nameof(SerializableConditionalExpression))] + [KnownType(typeof(SerializableConstantExpression)), JsonDerivedType(typeof(SerializableConstantExpression), nameof(SerializableConstantExpression))] + [KnownType(typeof(SerializableDefaultExpression)), JsonDerivedType(typeof(SerializableDefaultExpression), nameof(SerializableDefaultExpression))] + [KnownType(typeof(SerializableInvocationExpression)), JsonDerivedType(typeof(SerializableInvocationExpression), nameof(SerializableInvocationExpression))] + [KnownType(typeof(SerializableLambdaExpression)), JsonDerivedType(typeof(SerializableLambdaExpression), nameof(SerializableLambdaExpression))] + [KnownType(typeof(SerializableListInitExpression)), JsonDerivedType(typeof(SerializableListInitExpression), nameof(SerializableListInitExpression))] + [KnownType(typeof(SerializableMemberExpression)), JsonDerivedType(typeof(SerializableMemberExpression), nameof(SerializableMemberExpression))] + [KnownType(typeof(SerializableMemberInitExpression)), JsonDerivedType(typeof(SerializableMemberInitExpression), nameof(SerializableMemberInitExpression))] + [KnownType(typeof(SerializableMethodCallExpression)), JsonDerivedType(typeof(SerializableMethodCallExpression), nameof(SerializableMethodCallExpression))] + [KnownType(typeof(SerializableNewArrayExpression)), JsonDerivedType(typeof(SerializableNewArrayExpression), nameof(SerializableNewArrayExpression))] + [KnownType(typeof(SerializableNewExpression)), JsonDerivedType(typeof(SerializableNewExpression), nameof(SerializableNewExpression))] + [KnownType(typeof(SerializableParameterExpression)), JsonDerivedType(typeof(SerializableParameterExpression), nameof(SerializableParameterExpression))] + [KnownType(typeof(SerializableTypeBinaryExpression)), JsonDerivedType(typeof(SerializableTypeBinaryExpression), nameof(SerializableTypeBinaryExpression))] + [KnownType(typeof(SerializableUnaryExpression)), JsonDerivedType(typeof(SerializableUnaryExpression), nameof(SerializableUnaryExpression))] + public abstract class SerializableExpression + { + /// + /// . + /// + [DataMember, JsonInclude] + + public ExpressionType NodeType; + /// + /// . + /// + [DataMember, JsonInclude] + public SerializableType Type; + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableInvocationExpression.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableInvocationExpression.cs new file mode 100644 index 0000000000..467d84deda --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableInvocationExpression.cs @@ -0,0 +1,31 @@ +// Copyright (C) 2009-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Krjuchkov +// Created: 2009.05.13 + +using System; +using System.Linq.Expressions; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// A serializable representation of . + /// + [DataContract] + public sealed class SerializableInvocationExpression : SerializableExpression + { + /// + /// + /// + [DataMember, JsonInclude] + public SerializableExpression Expression; + /// + /// + /// + [DataMember, JsonInclude] + public SerializableExpression[] Arguments; + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableLambdaExpression.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableLambdaExpression.cs new file mode 100644 index 0000000000..d7752a4fec --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableLambdaExpression.cs @@ -0,0 +1,32 @@ +// Copyright (C) 2009-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Krjuchkov +// Created: 2009.05.12 + +using System; +using System.Linq.Expressions; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// A serializable representation of . + /// + [DataContract] + public sealed class SerializableLambdaExpression : SerializableExpression + { + /// + /// . + /// + [DataMember, JsonInclude] + public SerializableExpression Body; + + /// + /// . + /// + [DataMember, JsonInclude] + public SerializableParameterExpression[] Parameters; + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableListInitExpression.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableListInitExpression.cs new file mode 100644 index 0000000000..89ab443e6d --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableListInitExpression.cs @@ -0,0 +1,31 @@ +// Copyright (C) 2009-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Krjuchkov +// Created: 2009.05.13 + +using System; +using System.Linq.Expressions; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// A serializable representation of . + /// + [DataContract] + public sealed class SerializableListInitExpression : SerializableExpression + { + /// + /// + /// + [DataMember, JsonInclude] + public SerializableNewExpression NewExpression; + /// + /// + /// + [DataMember, JsonInclude] + public SerializableElementInit[] Initializers; + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMemberAssignment.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMemberAssignment.cs new file mode 100644 index 0000000000..1ceaae2f40 --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMemberAssignment.cs @@ -0,0 +1,26 @@ +// Copyright (C) 2009-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Krjuchkov +// Created: 2009.05.15 + +using System; +using System.Linq.Expressions; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// A serializable representation of + /// + [DataContract] + public class SerializableMemberAssignment : SerializableMemberBinding + { + /// + /// + /// + [DataMember, JsonInclude] + public SerializableExpression Expression; + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMemberBinding.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMemberBinding.cs new file mode 100644 index 0000000000..ff85442a06 --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMemberBinding.cs @@ -0,0 +1,37 @@ +// Copyright (C) 2009-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Krjuchkov +// Created: 2009.05.15 + +using System; +using System.Linq.Expressions; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// A serializable representation of + /// + [DataContract] + [KnownType(typeof(SerializableMemberAssignment)), + JsonDerivedType(typeof(SerializableMemberAssignment), nameof(SerializableMemberAssignment))] + [KnownType(typeof(SerializableMemberListBinding)), + JsonDerivedType(typeof(SerializableMemberListBinding), nameof(SerializableMemberListBinding))] + [KnownType(typeof(SerializableMemberMemberBinding)), + JsonDerivedType(typeof(SerializableMemberMemberBinding), nameof(SerializableMemberMemberBinding))] + public abstract class SerializableMemberBinding + { + /// + /// + /// + [DataMember, JsonInclude] + public MemberBindingType BindingType; + /// + /// + /// + [DataMember, JsonInclude] + public SerializableMemberInfo Member; + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMemberExpression.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMemberExpression.cs new file mode 100644 index 0000000000..3d1f1326d5 --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMemberExpression.cs @@ -0,0 +1,31 @@ +// Copyright (C) 2009-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Krjuchkov +// Created: 2009.05.12 + +using System; +using System.Linq.Expressions; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// A serializable representation of . + /// + [DataContract] + public sealed class SerializableMemberExpression : SerializableExpression + { + /// + /// + /// + [DataMember, JsonInclude] + public SerializableExpression Expression; + /// + /// + /// + [DataMember, JsonInclude] + public SerializableMemberInfo Member; + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMemberInfo.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMemberInfo.cs new file mode 100644 index 0000000000..6c13d02954 --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMemberInfo.cs @@ -0,0 +1,67 @@ +// Copyright (C) 2009-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Krjuchkov +// Created: 2009.05.12 + +using System; +using System.Linq; +using System.Reflection; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// A serializable representation of . + /// + [DataContract] + public sealed class SerializableMemberInfo + { + /// + /// See . + /// + [DataMember, JsonInclude] + public string DeclaringType; + + /// + /// Member signature. + /// + [DataMember, JsonInclude] + public string Member; + + #region Cast operators + + /// + /// Implicit conversion of to . + /// + /// The member to create serializable version. + /// The result of conversion. + public static implicit operator SerializableMemberInfo(MemberInfo member) + { + if (member == null) + return null; + return new SerializableMemberInfo { + DeclaringType = member.DeclaringType.AssemblyQualifiedName, + Member = member.ToString() + }; + } + + /// + /// Implicit conversion of to . + /// + /// The serializable version to convert. + /// The result of conversion. + public static implicit operator MemberInfo(SerializableMemberInfo reference) + { + if (reference == null) + return null; + + var name = reference.Member; + var member = Type.GetType(reference.DeclaringType).GetMembers().First(m => m.ToString() == name); + return member; + } + + #endregion + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMemberInitExpression.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMemberInitExpression.cs new file mode 100644 index 0000000000..0cfe8f5173 --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMemberInitExpression.cs @@ -0,0 +1,31 @@ +// Copyright (C) 2009-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Krjuchkov +// Created: 2009.05.13 + +using System; +using System.Linq.Expressions; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// A serializable representation of + /// + [DataContract] + public sealed class SerializableMemberInitExpression : SerializableExpression + { + /// + /// + /// + [DataMember, JsonInclude] + public SerializableNewExpression NewExpression; + /// + /// + /// + [DataMember, JsonInclude] + public SerializableMemberBinding[] Bindings; + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMemberListBinding.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMemberListBinding.cs new file mode 100644 index 0000000000..870e75f869 --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMemberListBinding.cs @@ -0,0 +1,26 @@ +// Copyright (C) 2009-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Kryuchkov +// Created: 2009.05.15 + +using System; +using System.Linq.Expressions; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// A serializable representation of . + /// + [DataContract] + public sealed class SerializableMemberListBinding : SerializableMemberBinding + { + /// + /// + /// + [DataMember, JsonInclude] + public SerializableElementInit[] Initializers; + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMemberMemberBinding.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMemberMemberBinding.cs new file mode 100644 index 0000000000..dd45ca2c05 --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMemberMemberBinding.cs @@ -0,0 +1,26 @@ +// Copyright (C) 2009-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Krjuchkov +// Created: 2009.05.15 + +using System; +using System.Linq.Expressions; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// A serializable representation of . + /// + [DataContract] + public sealed class SerializableMemberMemberBinding : SerializableMemberBinding + { + /// + /// + /// + [DataMember, JsonInclude] + public SerializableMemberBinding[] Bindings; + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMethodCallExpression.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMethodCallExpression.cs new file mode 100644 index 0000000000..adb2559219 --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMethodCallExpression.cs @@ -0,0 +1,36 @@ +// Copyright (C) 2009-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Krjuchkov +// Created: 2009.05.12 + +using System; +using System.Linq.Expressions; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// A serializable representation of . + /// + [DataContract] + public sealed class SerializableMethodCallExpression : SerializableExpression + { + /// + /// + /// + [DataMember, JsonInclude] + public SerializableExpression[] Arguments; + /// + /// + /// + [DataMember, JsonInclude] + public SerializableMethodInfo Method; + /// + /// + /// + [DataMember, JsonInclude] + public SerializableExpression Object; + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMethodInfo.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMethodInfo.cs new file mode 100644 index 0000000000..244f902644 --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableMethodInfo.cs @@ -0,0 +1,84 @@ +// Copyright (C) 2009-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Krjuchkov +// Created: 2009.05.12 + +using System; +using System.Linq; +using System.Reflection; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// A serializable representation of . + /// + [DataContract] + public sealed class SerializableMethodInfo + { + /// + /// See + /// + [DataMember, JsonInclude] + public string DeclaringType; + + /// + /// Method name. + /// + [DataMember, JsonInclude] + public string Name; + + /// + /// Generic parameters of the method. + /// + [DataMember, JsonInclude] + public SerializableType[] GenericParameters; + + #region Cast operators + + /// + /// Implicit conversion of to . + /// + /// The method to create reference for. + /// The result of conversion. + public static implicit operator SerializableMethodInfo(MethodInfo method) + { + if (method == null) + return null; + var type = method.DeclaringType.AssemblyQualifiedName; + var reference = new SerializableMethodInfo { DeclaringType = type }; + reference.Name = (method.IsGenericMethod) ? method.GetGenericMethodDefinition().ToString() : method.ToString(); + + if (method.IsGenericMethod) { + reference.GenericParameters = method.GetGenericArguments().Select(ty => (SerializableType) ty).ToArray(); + } + return reference; + } + + /// + /// Implicit conversion of to . + /// + /// The serializable version to convert. + /// The result of conversion. + public static implicit operator MethodInfo(SerializableMethodInfo reference) + { + if (reference == null) + return null; + var name = reference.Name; + var type = Type.GetType(reference.DeclaringType); + var method = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static).FirstOrDefault(m => m.ToString() == name); + if (method == null) + method = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static).FirstOrDefault(m => m.ToString() == name); + if (method == null) + throw new ArgumentException("There is no such method found"); + + if (method.IsGenericMethod) + method = method.MakeGenericMethod(reference.GenericParameters.Select(p => (Type) p).ToArray()); + return method; + } + + #endregion + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableNewArrayExpression.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableNewArrayExpression.cs new file mode 100644 index 0000000000..a52575f757 --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableNewArrayExpression.cs @@ -0,0 +1,25 @@ +// Copyright (C) 2009-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Krjuchkov +// Created: 2009.05.13 + +using System; +using System.Linq.Expressions; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// A serializable representation of + /// + public sealed class SerializableNewArrayExpression : SerializableExpression + { + /// + /// + /// + [DataMember, JsonInclude] + public SerializableExpression[] Expressions; + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableNewExpression.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableNewExpression.cs new file mode 100644 index 0000000000..1ba0b029da --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableNewExpression.cs @@ -0,0 +1,36 @@ +// Copyright (C) 2009-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Krjuchkov +// Created: 2009.05.12 + +using System; +using System.Linq.Expressions; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// A serializable representation of + /// + [DataContract] + public sealed class SerializableNewExpression : SerializableExpression + { + /// + /// + /// + [DataMember, JsonInclude] + public SerializableExpression[] Arguments; + /// + /// + /// + [DataMember, JsonInclude] + public SerializableConstructorInfo Constructor; + /// + /// + /// + [DataMember, JsonInclude] + public SerializableMemberInfo[] Members; + } +} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableParameterExpression.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableParameterExpression.cs similarity index 50% rename from Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableParameterExpression.cs rename to Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableParameterExpression.cs index 69d2d40df8..7be827e6f7 100644 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableParameterExpression.cs +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableParameterExpression.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2009-2021 Xtensive LLC. +// Copyright (C) 2009-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Denis Krjuchkov @@ -7,36 +7,20 @@ using System; using System.Linq.Expressions; using System.Runtime.Serialization; -using System.Security; +using System.Text.Json.Serialization; -namespace Xtensive.Linq.SerializableExpressions +namespace Xtensive.Orm.SerializableExpressions { /// /// A serializable representation of . /// - [Serializable] + [DataContract] public sealed class SerializableParameterExpression : SerializableExpression { /// /// . /// + [DataMember, JsonInclude] public string Name; - - [SecurityCritical] - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddValue("Name", Name); - } - - public SerializableParameterExpression() - { - } - - public SerializableParameterExpression(SerializationInfo info, StreamingContext context) - : base(info, context) - { - Name = info.GetString("Name"); - } } } \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableType.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableType.cs new file mode 100644 index 0000000000..d13d43abe0 --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableType.cs @@ -0,0 +1,51 @@ +// Copyright (C) 2009-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Krjuchkov +// Created: 2009.05.12 + +using System; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// A serializable representation of . + /// + [DataContract] + public sealed class SerializableType + { + /// + /// See . + /// + [DataMember, JsonInclude] + public string AssemblyQualifiedName; + + #region Cast operators + + /// + /// Implicit conversion of to . + /// + /// The type to create reference for. + /// The result of conversion. + public static implicit operator SerializableType(Type type) + { + return new SerializableType { AssemblyQualifiedName = type.AssemblyQualifiedName }; + } + + /// + /// Implicit conversion of to . + /// + /// The serializable version to convert. + /// The result of conversion. + public static implicit operator Type(SerializableType reference) + { + if (reference?.AssemblyQualifiedName is null) + return null; + return Type.GetType(reference.AssemblyQualifiedName); + } + + #endregion + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableTypeBinaryExpression.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableTypeBinaryExpression.cs new file mode 100644 index 0000000000..c53fe7d4b7 --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableTypeBinaryExpression.cs @@ -0,0 +1,31 @@ +// Copyright (C) 2009-2021 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Krjuchkov +// Created: 2009.05.12 + +using System; +using System.Linq.Expressions; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// A serializable representation of . + /// + [DataContract] + public sealed class SerializableTypeBinaryExpression : SerializableExpression + { + /// + /// + /// + [DataMember, JsonInclude] + public SerializableExpression Expression; + /// + /// + /// + [DataMember, JsonInclude] + public SerializableType TypeOperand; + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableUnaryExpression.cs b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableUnaryExpression.cs new file mode 100644 index 0000000000..0679563070 --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/SerializableExpressions/SerializableUnaryExpression.cs @@ -0,0 +1,32 @@ +// Copyright (C) 2009-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Denis Krjuchkov +// Created: 2009.05.12 + +using System; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Xtensive.Orm.SerializableExpressions +{ + /// + /// A serializable representation of . + /// + [DataContract] + public sealed class SerializableUnaryExpression : SerializableExpression + { + /// + /// + /// + [DataMember, JsonInclude] + public SerializableExpression Operand; + /// + /// + /// + [DataMember, JsonInclude] + public SerializableMethodInfo Method; + } +} \ No newline at end of file diff --git a/Extensions/Xtensive.Orm.SerializableExpressions/Xtensive.Orm.SerializableExpressions.csproj b/Extensions/Xtensive.Orm.SerializableExpressions/Xtensive.Orm.SerializableExpressions.csproj new file mode 100644 index 0000000000..db60ec726a --- /dev/null +++ b/Extensions/Xtensive.Orm.SerializableExpressions/Xtensive.Orm.SerializableExpressions.csproj @@ -0,0 +1,26 @@ + + + true + $(OutputPath)$(TargetFramework)\$(AssemblyName).xml + Debug;Release;Debug-NET8;Release-NET8;Debug-NET10;Release-NET10 + + + Xtensive.Orm.SerializableExpressions + Serializable variants of System.Linq.Expressions + $(Title) + Provides serializable form of System.Linq.Expressions, ready to json/data-contract serialization. + true + $(ExtensionsKeyFile) + + + ReadMe.md + + + + + + + . + + + diff --git a/Extensions/Xtensive.Orm.Tracking.Tests/Model/MyEntity.cs b/Extensions/Xtensive.Orm.Tracking.Tests/Model/MyEntity.cs index 6a7bebe7f3..ce32366919 100644 --- a/Extensions/Xtensive.Orm.Tracking.Tests/Model/MyEntity.cs +++ b/Extensions/Xtensive.Orm.Tracking.Tests/Model/MyEntity.cs @@ -1,8 +1,7 @@ -using System; +using System; namespace Xtensive.Orm.Tracking.Tests.Model { - [Serializable] [HierarchyRoot] public class MyEntity : Entity { diff --git a/Extensions/Xtensive.Orm.Tracking/TrackingItemState.cs b/Extensions/Xtensive.Orm.Tracking/TrackingItemState.cs index 7fb1fec5d3..066f11c3ed 100644 --- a/Extensions/Xtensive.Orm.Tracking/TrackingItemState.cs +++ b/Extensions/Xtensive.Orm.Tracking/TrackingItemState.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2012 Xtensive LLC. +// Copyright (C) 2012 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Dmitri Maximov @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tracking /// /// State of /// - [Serializable] public enum TrackingItemState { /// diff --git a/Orm.sln b/Orm.sln index e96d010b9c..2b04116111 100644 --- a/Orm.sln +++ b/Orm.sln @@ -88,6 +88,14 @@ Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "Xtensive.Orm.Tests.FSharp", EndProject Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "Xtensive.Orm.Tests.VB", "Orm\Xtensive.Orm.Tests.VB\Xtensive.Orm.Tests.VB.vbproj", "{C78BE7F5-2B6F-D34B-A2D9-EFA97EEF9225}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Xtensive.Orm.Operations", "Extensions\Xtensive.Orm.Operations\Xtensive.Orm.Operations.csproj", "{BD3733FB-B4D2-4845-8B7F-F7484CCBDCEA}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Xtensive.Orm.Operations.Tests", "Extensions\Xtensive.Orm.Operations.Tests\Xtensive.Orm.Operations.Tests.csproj", "{CD3F17F5-F0C5-43C0-9AFC-25048847B89B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Xtensive.Orm.SerializableExpressions", "Extensions\Xtensive.Orm.SerializableExpressions\Xtensive.Orm.SerializableExpressions.csproj", "{FFAF9D47-4B73-4BDF-A2CB-626521DC8FA9}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Xtensive.Orm.SerializableExpressions.Tests", "Extensions\Xtensive.Orm.SerializableExpressions.Tests\Xtensive.Orm.SerializableExpressions.Tests.csproj", "{131AD9BE-F9C6-416C-987D-E3F0AF24DB5D}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -488,6 +496,54 @@ Global {C78BE7F5-2B6F-D34B-A2D9-EFA97EEF9225}.Release-NET10|Any CPU.Build.0 = Release-NET10|Any CPU {C78BE7F5-2B6F-D34B-A2D9-EFA97EEF9225}.Release-NET8|Any CPU.ActiveCfg = Release-NET8|Any CPU {C78BE7F5-2B6F-D34B-A2D9-EFA97EEF9225}.Release-NET8|Any CPU.Build.0 = Release-NET8|Any CPU + {BD3733FB-B4D2-4845-8B7F-F7484CCBDCEA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BD3733FB-B4D2-4845-8B7F-F7484CCBDCEA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BD3733FB-B4D2-4845-8B7F-F7484CCBDCEA}.Debug-NET10|Any CPU.ActiveCfg = Debug|Any CPU + {BD3733FB-B4D2-4845-8B7F-F7484CCBDCEA}.Debug-NET10|Any CPU.Build.0 = Debug|Any CPU + {BD3733FB-B4D2-4845-8B7F-F7484CCBDCEA}.Debug-NET8|Any CPU.ActiveCfg = Debug|Any CPU + {BD3733FB-B4D2-4845-8B7F-F7484CCBDCEA}.Debug-NET8|Any CPU.Build.0 = Debug|Any CPU + {BD3733FB-B4D2-4845-8B7F-F7484CCBDCEA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BD3733FB-B4D2-4845-8B7F-F7484CCBDCEA}.Release|Any CPU.Build.0 = Release|Any CPU + {BD3733FB-B4D2-4845-8B7F-F7484CCBDCEA}.Release-NET10|Any CPU.ActiveCfg = Release|Any CPU + {BD3733FB-B4D2-4845-8B7F-F7484CCBDCEA}.Release-NET10|Any CPU.Build.0 = Release|Any CPU + {BD3733FB-B4D2-4845-8B7F-F7484CCBDCEA}.Release-NET8|Any CPU.ActiveCfg = Release|Any CPU + {BD3733FB-B4D2-4845-8B7F-F7484CCBDCEA}.Release-NET8|Any CPU.Build.0 = Release|Any CPU + {CD3F17F5-F0C5-43C0-9AFC-25048847B89B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CD3F17F5-F0C5-43C0-9AFC-25048847B89B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CD3F17F5-F0C5-43C0-9AFC-25048847B89B}.Debug-NET10|Any CPU.ActiveCfg = Debug|Any CPU + {CD3F17F5-F0C5-43C0-9AFC-25048847B89B}.Debug-NET10|Any CPU.Build.0 = Debug|Any CPU + {CD3F17F5-F0C5-43C0-9AFC-25048847B89B}.Debug-NET8|Any CPU.ActiveCfg = Debug|Any CPU + {CD3F17F5-F0C5-43C0-9AFC-25048847B89B}.Debug-NET8|Any CPU.Build.0 = Debug|Any CPU + {CD3F17F5-F0C5-43C0-9AFC-25048847B89B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CD3F17F5-F0C5-43C0-9AFC-25048847B89B}.Release|Any CPU.Build.0 = Release|Any CPU + {CD3F17F5-F0C5-43C0-9AFC-25048847B89B}.Release-NET10|Any CPU.ActiveCfg = Release|Any CPU + {CD3F17F5-F0C5-43C0-9AFC-25048847B89B}.Release-NET10|Any CPU.Build.0 = Release|Any CPU + {CD3F17F5-F0C5-43C0-9AFC-25048847B89B}.Release-NET8|Any CPU.ActiveCfg = Release|Any CPU + {CD3F17F5-F0C5-43C0-9AFC-25048847B89B}.Release-NET8|Any CPU.Build.0 = Release|Any CPU + {FFAF9D47-4B73-4BDF-A2CB-626521DC8FA9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FFAF9D47-4B73-4BDF-A2CB-626521DC8FA9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FFAF9D47-4B73-4BDF-A2CB-626521DC8FA9}.Debug-NET10|Any CPU.ActiveCfg = Debug|Any CPU + {FFAF9D47-4B73-4BDF-A2CB-626521DC8FA9}.Debug-NET10|Any CPU.Build.0 = Debug|Any CPU + {FFAF9D47-4B73-4BDF-A2CB-626521DC8FA9}.Debug-NET8|Any CPU.ActiveCfg = Debug|Any CPU + {FFAF9D47-4B73-4BDF-A2CB-626521DC8FA9}.Debug-NET8|Any CPU.Build.0 = Debug|Any CPU + {FFAF9D47-4B73-4BDF-A2CB-626521DC8FA9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FFAF9D47-4B73-4BDF-A2CB-626521DC8FA9}.Release|Any CPU.Build.0 = Release|Any CPU + {FFAF9D47-4B73-4BDF-A2CB-626521DC8FA9}.Release-NET10|Any CPU.ActiveCfg = Release|Any CPU + {FFAF9D47-4B73-4BDF-A2CB-626521DC8FA9}.Release-NET10|Any CPU.Build.0 = Release|Any CPU + {FFAF9D47-4B73-4BDF-A2CB-626521DC8FA9}.Release-NET8|Any CPU.ActiveCfg = Release|Any CPU + {FFAF9D47-4B73-4BDF-A2CB-626521DC8FA9}.Release-NET8|Any CPU.Build.0 = Release|Any CPU + {131AD9BE-F9C6-416C-987D-E3F0AF24DB5D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {131AD9BE-F9C6-416C-987D-E3F0AF24DB5D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {131AD9BE-F9C6-416C-987D-E3F0AF24DB5D}.Debug-NET10|Any CPU.ActiveCfg = Debug|Any CPU + {131AD9BE-F9C6-416C-987D-E3F0AF24DB5D}.Debug-NET10|Any CPU.Build.0 = Debug|Any CPU + {131AD9BE-F9C6-416C-987D-E3F0AF24DB5D}.Debug-NET8|Any CPU.ActiveCfg = Debug|Any CPU + {131AD9BE-F9C6-416C-987D-E3F0AF24DB5D}.Debug-NET8|Any CPU.Build.0 = Debug|Any CPU + {131AD9BE-F9C6-416C-987D-E3F0AF24DB5D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {131AD9BE-F9C6-416C-987D-E3F0AF24DB5D}.Release|Any CPU.Build.0 = Release|Any CPU + {131AD9BE-F9C6-416C-987D-E3F0AF24DB5D}.Release-NET10|Any CPU.ActiveCfg = Release|Any CPU + {131AD9BE-F9C6-416C-987D-E3F0AF24DB5D}.Release-NET10|Any CPU.Build.0 = Release|Any CPU + {131AD9BE-F9C6-416C-987D-E3F0AF24DB5D}.Release-NET8|Any CPU.ActiveCfg = Release|Any CPU + {131AD9BE-F9C6-416C-987D-E3F0AF24DB5D}.Release-NET8|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -525,6 +581,10 @@ Global {2CC55F3E-8EA5-4305-8716-D5B944120F82} = {5726BBD8-14F9-4909-B765-3E7709223B61} {A68C90C1-AD82-40FD-A18D-F04923514743} = {8AAB1719-253A-47D2-970F-1911CFEE84B7} {C78BE7F5-2B6F-D34B-A2D9-EFA97EEF9225} = {8AAB1719-253A-47D2-970F-1911CFEE84B7} + {BD3733FB-B4D2-4845-8B7F-F7484CCBDCEA} = {C4AA9FB1-2A47-4E3A-A78C-BBE20EDCB3E1} + {CD3F17F5-F0C5-43C0-9AFC-25048847B89B} = {DC441957-AF79-423D-AA60-2F102926F6D2} + {FFAF9D47-4B73-4BDF-A2CB-626521DC8FA9} = {C4AA9FB1-2A47-4E3A-A78C-BBE20EDCB3E1} + {131AD9BE-F9C6-416C-987D-E3F0AF24DB5D} = {DC441957-AF79-423D-AA60-2F102926F6D2} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {F995719A-8D35-49A3-B271-42898A587F57} diff --git a/Orm/Xtensive.Orm.Manual/Advanced/CustomLinqCompilerTest.cs b/Orm/Xtensive.Orm.Manual/Advanced/CustomLinqCompilerTest.cs index 6ce215ca98..c2cb73a6ee 100644 --- a/Orm/Xtensive.Orm.Manual/Advanced/CustomLinqCompilerTest.cs +++ b/Orm/Xtensive.Orm.Manual/Advanced/CustomLinqCompilerTest.cs @@ -16,7 +16,6 @@ namespace Xtensive.Orm.Manual.Advanced.CustomLinqCompiler { #region Model - [Serializable] [HierarchyRoot] public class Person : Entity { diff --git a/Orm/Xtensive.Orm.Manual/Advanced/CustomSqlCompilerTest.cs b/Orm/Xtensive.Orm.Manual/Advanced/CustomSqlCompilerTest.cs index 62aeaf7b18..8db2910d59 100644 --- a/Orm/Xtensive.Orm.Manual/Advanced/CustomSqlCompilerTest.cs +++ b/Orm/Xtensive.Orm.Manual/Advanced/CustomSqlCompilerTest.cs @@ -16,7 +16,6 @@ namespace Xtensive.Orm.Manual.Advanced.CustomSqlCompiler { #region Model - [Serializable] public class Address : Structure { [Field(Length = 200)] @@ -36,7 +35,6 @@ public Address(Session session) {} } - [Serializable] [HierarchyRoot] public class Person : Entity { diff --git a/Orm/Xtensive.Orm.Manual/Advanced/JoinsAndSubqueriesTest.cs b/Orm/Xtensive.Orm.Manual/Advanced/JoinsAndSubqueriesTest.cs index d870e15be2..32eefe2016 100644 --- a/Orm/Xtensive.Orm.Manual/Advanced/JoinsAndSubqueriesTest.cs +++ b/Orm/Xtensive.Orm.Manual/Advanced/JoinsAndSubqueriesTest.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Manual.Advanced.JoinsAndSubqueriesTest { #region Model - [Serializable] [HierarchyRoot] public class Person : Entity { @@ -28,7 +27,6 @@ public Person(Session session) {} } - [Serializable] public class Employee : Person { [Field] diff --git a/Orm/Xtensive.Orm.Manual/Attributes/AttributesTest.cs b/Orm/Xtensive.Orm.Manual/Attributes/AttributesTest.cs index 69641ff417..b345b97e3e 100644 --- a/Orm/Xtensive.Orm.Manual/Attributes/AttributesTest.cs +++ b/Orm/Xtensive.Orm.Manual/Attributes/AttributesTest.cs @@ -37,7 +37,6 @@ public override Tuple GenerateKey(KeyInfo keyInfo, Session session) #region Model - [Serializable] // All descendant entities will be placed in the same table. [HierarchyRoot(InheritanceSchema = InheritanceSchema.SingleTable)] // Index on field "ISBN" that includes additiona "Title" field along with keyfield. @@ -75,7 +74,6 @@ protected Book(Session session) } } - [Serializable] // If "BookType" field contains "true" value, the entity is "SciFi" [TypeDiscriminatorValue(true)] // Index on field "SciFiDescription" that includes additional "SciFiDescriptionDate" field along with keyfield. @@ -94,7 +92,6 @@ public SciFi(Session session) } } - [Serializable] // If "BookType" field contains "false" value, the entity is "Horror" [TypeDiscriminatorValue(false)] public class Horror : Book @@ -105,7 +102,6 @@ public Horror(Session session) } } - [Serializable] // Entity "Author" will be mapped to "Persons" table. [TableMapping("Persons")] // Key will include "TypeId" field. diff --git a/Orm/Xtensive.Orm.Manual/Caching/CalculatedValueCachingTest.cs b/Orm/Xtensive.Orm.Manual/Caching/CalculatedValueCachingTest.cs index 95f1b78f4f..436a150396 100644 --- a/Orm/Xtensive.Orm.Manual/Caching/CalculatedValueCachingTest.cs +++ b/Orm/Xtensive.Orm.Manual/Caching/CalculatedValueCachingTest.cs @@ -18,7 +18,6 @@ namespace Xtensive.Orm.Manual.Caching { #region Model - [Serializable] [HierarchyRoot] public class Product : Entity { @@ -45,7 +44,6 @@ public Product(Session session) {} } - [Serializable] [HierarchyRoot] public class Order : Entity { diff --git a/Orm/Xtensive.Orm.Manual/Concurrency/LockingTest.cs b/Orm/Xtensive.Orm.Manual/Concurrency/LockingTest.cs index 839a468d14..16f2cb6660 100644 --- a/Orm/Xtensive.Orm.Manual/Concurrency/LockingTest.cs +++ b/Orm/Xtensive.Orm.Manual/Concurrency/LockingTest.cs @@ -19,7 +19,6 @@ namespace Xtensive.Orm.Manual.Concurrency.Locking { #region Model - [Serializable] [HierarchyRoot] public class Counter : Entity { diff --git a/Orm/Xtensive.Orm.Manual/Concurrency/VersionsTest.cs b/Orm/Xtensive.Orm.Manual/Concurrency/VersionsTest.cs index 354176a836..fdf7933cec 100644 --- a/Orm/Xtensive.Orm.Manual/Concurrency/VersionsTest.cs +++ b/Orm/Xtensive.Orm.Manual/Concurrency/VersionsTest.cs @@ -19,7 +19,6 @@ namespace Xtensive.Orm.Manual.Concurrency.Versions { #region Model - [Serializable] [HierarchyRoot] public class Person : Entity { @@ -66,7 +65,6 @@ public Person(Session session, string fullName) } } - [Serializable] [HierarchyRoot] public class Company : Entity { @@ -239,9 +237,6 @@ public void VersionValidatorTest() tx.Complete(); } - // Let's clone VersionSet (actually - serialize & deserialize) - versions = Cloner.Clone(versions); - // And dump it Dump(versions); using (VersionValidator.Attach(session, versions)) diff --git a/Orm/Xtensive.Orm.Manual/DomainAndSession/DomainAndSessionSample.cs b/Orm/Xtensive.Orm.Manual/DomainAndSession/DomainAndSessionSample.cs index b9f013099b..166c9f9a38 100644 --- a/Orm/Xtensive.Orm.Manual/DomainAndSession/DomainAndSessionSample.cs +++ b/Orm/Xtensive.Orm.Manual/DomainAndSession/DomainAndSessionSample.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Manual.DomainAndSession { #region Model - [Serializable] [HierarchyRoot] public class Person : Entity { diff --git a/Orm/Xtensive.Orm.Manual/Entities/TestFixture.cs b/Orm/Xtensive.Orm.Manual/Entities/TestFixture.cs index c9644a0f28..91a25a112b 100644 --- a/Orm/Xtensive.Orm.Manual/Entities/TestFixture.cs +++ b/Orm/Xtensive.Orm.Manual/Entities/TestFixture.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Manual.Entities [TestFixture] public class TestFixture { - [Serializable] [HierarchyRoot] public abstract class Document : Entity { @@ -28,7 +27,6 @@ public abstract class Document : Entity public int Number { get; set; } } - [Serializable] public class Order : Document { [Field] @@ -41,7 +39,6 @@ public class Order : Document public double Amount { get; set; } } - [Serializable] [HierarchyRoot] public class Product : Entity { diff --git a/Orm/Xtensive.Orm.Manual/EntitySets/EntitySetsTest.cs b/Orm/Xtensive.Orm.Manual/EntitySets/EntitySetsTest.cs index 974674b199..059b1bd257 100644 --- a/Orm/Xtensive.Orm.Manual/EntitySets/EntitySetsTest.cs +++ b/Orm/Xtensive.Orm.Manual/EntitySets/EntitySetsTest.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Manual.EntitySets { #region Model - [Serializable] [HierarchyRoot] public class User : Entity { @@ -53,7 +52,6 @@ public User(Session session) {} } - [Serializable] [HierarchyRoot] public class WebPage : Entity { @@ -71,7 +69,6 @@ public WebPage(Session session) {} } - [Serializable] [HierarchyRoot] public class BlogPost : Entity { @@ -92,7 +89,6 @@ public BlogPost(Session session) {} } - [Serializable] [HierarchyRoot] public class Meeting : Entity { @@ -113,7 +109,6 @@ public Meeting(Session session) {} } - [Serializable] [HierarchyRoot] public class Account : Entity { diff --git a/Orm/Xtensive.Orm.Manual/FutureQueries/FutureQueriesTest.cs b/Orm/Xtensive.Orm.Manual/FutureQueries/FutureQueriesTest.cs index deedbc0f56..542e4f035d 100644 --- a/Orm/Xtensive.Orm.Manual/FutureQueries/FutureQueriesTest.cs +++ b/Orm/Xtensive.Orm.Manual/FutureQueries/FutureQueriesTest.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Manual.FutureQueries { #region Model - [Serializable] [HierarchyRoot] public class Person : Entity { diff --git a/Orm/Xtensive.Orm.Manual/Indexes/TestFixture.cs b/Orm/Xtensive.Orm.Manual/Indexes/TestFixture.cs index 7ccbad81b6..c02924188e 100644 --- a/Orm/Xtensive.Orm.Manual/Indexes/TestFixture.cs +++ b/Orm/Xtensive.Orm.Manual/Indexes/TestFixture.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Manual.Indexes { #region Model - [Serializable] [HierarchyRoot] public class Pet : Entity { @@ -29,7 +28,6 @@ public Pet(Session session) {} } - [Serializable] [HierarchyRoot] [Index("Email", Unique = true)] [Index("FirstName", "LastName")] diff --git a/Orm/Xtensive.Orm.Manual/Intro/CheatSheetTest.cs b/Orm/Xtensive.Orm.Manual/Intro/CheatSheetTest.cs index 74c5dd5e55..842ff14fc9 100644 --- a/Orm/Xtensive.Orm.Manual/Intro/CheatSheetTest.cs +++ b/Orm/Xtensive.Orm.Manual/Intro/CheatSheetTest.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Manual.Intro.CheatSheet { #region Model - [Serializable] [HierarchyRoot] public class User : Entity { @@ -45,7 +44,6 @@ public User(Session session) {} } - [Serializable] [HierarchyRoot] public class WebPage : Entity { @@ -63,7 +61,6 @@ public WebPage(Session session) {} } - [Serializable] [HierarchyRoot] public class BlogPost : Entity { diff --git a/Orm/Xtensive.Orm.Manual/Intro/HelloWorldTest.cs b/Orm/Xtensive.Orm.Manual/Intro/HelloWorldTest.cs index 88124da74f..0639ff199d 100644 --- a/Orm/Xtensive.Orm.Manual/Intro/HelloWorldTest.cs +++ b/Orm/Xtensive.Orm.Manual/Intro/HelloWorldTest.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Manual.Intro.HelloWorld { #region Model - [Serializable] [HierarchyRoot] public class MyEntity : Entity { diff --git a/Orm/Xtensive.Orm.Manual/Legacy/CustomKeyGenerators/CustomKeyGeneratorsTest.cs b/Orm/Xtensive.Orm.Manual/Legacy/CustomKeyGenerators/CustomKeyGeneratorsTest.cs index a26d003c25..a83fc141e2 100644 --- a/Orm/Xtensive.Orm.Manual/Legacy/CustomKeyGenerators/CustomKeyGeneratorsTest.cs +++ b/Orm/Xtensive.Orm.Manual/Legacy/CustomKeyGenerators/CustomKeyGeneratorsTest.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Manual.Legacy.CustomKeyGenerators { #region Model - [Serializable] [HierarchyRoot] [KeyGenerator(Name = "Author")] public class Author : Entity @@ -45,7 +44,6 @@ public Author(Session session, int id) } } - [Serializable] [HierarchyRoot] [KeyGenerator(Name = "Book")] public class Book : Entity diff --git a/Orm/Xtensive.Orm.Manual/ModellingDomain/AuditAndOpenGenericsTest.cs b/Orm/Xtensive.Orm.Manual/ModellingDomain/AuditAndOpenGenericsTest.cs index ab36984baf..fd93d2aa79 100644 --- a/Orm/Xtensive.Orm.Manual/ModellingDomain/AuditAndOpenGenericsTest.cs +++ b/Orm/Xtensive.Orm.Manual/ModellingDomain/AuditAndOpenGenericsTest.cs @@ -18,7 +18,6 @@ namespace Xtensive.Orm.Manual.ModellingDomain.AuditAndOpenGenericsTest { #region Model - [Serializable] [HierarchyRoot] [KeyGenerator(Name = "Transaction")] // To ensure there is its own sequence [Index("Guid", Unique = true)] @@ -63,7 +62,6 @@ public enum EntityChangeType Removed } - [Serializable] [HierarchyRoot] [Index("Transaction", "EntityKey", Unique = true)] public abstract class AuditRecord : Entity @@ -91,7 +89,6 @@ protected AuditRecord(Session session) } // Unused, here it is just to show one more open generic - [Serializable] [HierarchyRoot] public sealed class SyncInfo : Entity where T: Entity @@ -105,7 +102,6 @@ public SyncInfo(Session session) {} } - [Serializable] public sealed class AuditRecord : AuditRecord where T: Entity { @@ -139,7 +135,6 @@ internal AuditRecord() } } - [Serializable] [HierarchyRoot] public class Person : Entity { @@ -163,7 +158,6 @@ public Person(Session session) {} } - [Serializable] [HierarchyRoot] public class Animal : Entity { @@ -186,7 +180,6 @@ public Animal(Session session) {} } - [Serializable] public class Cat : Animal { public Cat(Session session) @@ -194,7 +187,6 @@ public Cat(Session session) {} } - [Serializable] public class Dog : Animal { public Dog(Session session) diff --git a/Orm/Xtensive.Orm.Manual/ModellingDomain/IndexAttributeTest.cs b/Orm/Xtensive.Orm.Manual/ModellingDomain/IndexAttributeTest.cs index 23da7c36b8..62a929a057 100644 --- a/Orm/Xtensive.Orm.Manual/ModellingDomain/IndexAttributeTest.cs +++ b/Orm/Xtensive.Orm.Manual/ModellingDomain/IndexAttributeTest.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Manual.ModellingDomain.IndexAttribute_ { #region Model - [Serializable] [Index("FirstName", "LastName", Unique = true)] [Index("Age")] [HierarchyRoot] diff --git a/Orm/Xtensive.Orm.Manual/Persistent/TestFixture.cs b/Orm/Xtensive.Orm.Manual/Persistent/TestFixture.cs index 6abcefa0fb..4fd3db8159 100644 --- a/Orm/Xtensive.Orm.Manual/Persistent/TestFixture.cs +++ b/Orm/Xtensive.Orm.Manual/Persistent/TestFixture.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Manual.Persistent { - [Serializable] [HierarchyRoot] public class Person : Entity { diff --git a/Orm/Xtensive.Orm.Manual/Prefetch/PrefetchTest.cs b/Orm/Xtensive.Orm.Manual/Prefetch/PrefetchTest.cs index 7dcb610b9d..c051e69d43 100644 --- a/Orm/Xtensive.Orm.Manual/Prefetch/PrefetchTest.cs +++ b/Orm/Xtensive.Orm.Manual/Prefetch/PrefetchTest.cs @@ -17,7 +17,6 @@ namespace Xtensive.Orm.Manual.Prefetch { #region Model - [Serializable] [HierarchyRoot] public class Person : Entity { diff --git a/Orm/Xtensive.Orm.Manual/Structures/TestFixture.cs b/Orm/Xtensive.Orm.Manual/Structures/TestFixture.cs index 57197182a7..cc6e951307 100644 --- a/Orm/Xtensive.Orm.Manual/Structures/TestFixture.cs +++ b/Orm/Xtensive.Orm.Manual/Structures/TestFixture.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Manual.Structures { - [Serializable] public class Point : Structure { [Field] @@ -30,7 +29,6 @@ public Point(int x, int y) } } - [Serializable] [HierarchyRoot] public class Range : Entity { diff --git a/Orm/Xtensive.Orm.Manual/Transactions/NestedTransactionsTest.cs b/Orm/Xtensive.Orm.Manual/Transactions/NestedTransactionsTest.cs index da8c30bc62..fa84659831 100644 --- a/Orm/Xtensive.Orm.Manual/Transactions/NestedTransactionsTest.cs +++ b/Orm/Xtensive.Orm.Manual/Transactions/NestedTransactionsTest.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Manual.Transactions.NestedTransactions { #region Model - [Serializable] [HierarchyRoot] public class User : Entity { @@ -53,7 +52,6 @@ public User(Session session) {} } - [Serializable] [HierarchyRoot] public class WebPage : Entity { @@ -71,7 +69,6 @@ public WebPage(Session session) {} } - [Serializable] [HierarchyRoot] public class BlogPost : Entity { diff --git a/Orm/Xtensive.Orm.Manual/Transactions/SessionSwitchingTest.cs b/Orm/Xtensive.Orm.Manual/Transactions/SessionSwitchingTest.cs index 434654b50a..f47fc62f14 100644 --- a/Orm/Xtensive.Orm.Manual/Transactions/SessionSwitchingTest.cs +++ b/Orm/Xtensive.Orm.Manual/Transactions/SessionSwitchingTest.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Manual.Transactions.SessionSwitching { #region Model - [Serializable] [HierarchyRoot] public class Person : Entity { diff --git a/Orm/Xtensive.Orm.Manual/Upgrade/Model_1/Model.cs b/Orm/Xtensive.Orm.Manual/Upgrade/Model_1/Model.cs index adcbcee237..8d386c2415 100644 --- a/Orm/Xtensive.Orm.Manual/Upgrade/Model_1/Model.cs +++ b/Orm/Xtensive.Orm.Manual/Upgrade/Model_1/Model.cs @@ -9,7 +9,6 @@ namespace Xtensive.Orm.Manual.Upgrade.Model_1 { - [Serializable] [HierarchyRoot] public class Order : Entity { diff --git a/Orm/Xtensive.Orm.Manual/Upgrade/Model_2/Model.cs b/Orm/Xtensive.Orm.Manual/Upgrade/Model_2/Model.cs index d05c6f9a77..a679b50e4a 100644 --- a/Orm/Xtensive.Orm.Manual/Upgrade/Model_2/Model.cs +++ b/Orm/Xtensive.Orm.Manual/Upgrade/Model_2/Model.cs @@ -9,7 +9,6 @@ namespace Xtensive.Orm.Manual.Upgrade.Model_2 { - [Serializable] [HierarchyRoot] public class Order : Entity { @@ -30,7 +29,6 @@ public Order(Session session) {} } - [Serializable] [HierarchyRoot] public class Customer : Entity { diff --git a/Orm/Xtensive.Orm.Manual/Upgrade/Model_3/Model.cs b/Orm/Xtensive.Orm.Manual/Upgrade/Model_3/Model.cs index 478a26e707..89c16fd794 100644 --- a/Orm/Xtensive.Orm.Manual/Upgrade/Model_3/Model.cs +++ b/Orm/Xtensive.Orm.Manual/Upgrade/Model_3/Model.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Manual.Upgrade.Model_3 { - [Serializable] [HierarchyRoot] public class Order : Entity { @@ -31,7 +30,6 @@ public Order(Session session) {} } - [Serializable] [HierarchyRoot] public class Person : Entity { diff --git a/Orm/Xtensive.Orm.Manual/Upgrade/Model_4/Model.cs b/Orm/Xtensive.Orm.Manual/Upgrade/Model_4/Model.cs index ed00ca0278..b07ee62652 100644 --- a/Orm/Xtensive.Orm.Manual/Upgrade/Model_4/Model.cs +++ b/Orm/Xtensive.Orm.Manual/Upgrade/Model_4/Model.cs @@ -9,7 +9,6 @@ namespace Xtensive.Orm.Manual.Upgrade.Model_4 { - [Serializable] [HierarchyRoot] public class Order : Entity { @@ -35,7 +34,6 @@ public Order(Session session) {} } - [Serializable] [HierarchyRoot] public class Product : Entity { @@ -50,7 +48,6 @@ public Product(Session session) {} } - [Serializable] [HierarchyRoot] public class Person : Entity { diff --git a/Orm/Xtensive.Orm.Tests.Core/Caching/LruCacheTest.cs b/Orm/Xtensive.Orm.Tests.Core/Caching/LruCacheTest.cs index 57bc196c52..69c8e9358f 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Caching/LruCacheTest.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Caching/LruCacheTest.cs @@ -41,7 +41,6 @@ public TestClass(string text) } } - [Serializable] internal class TestClassAdvancedConverter : AdvancedConverterBase, IAdvancedConverter diff --git a/Orm/Xtensive.Orm.Tests.Core/Comparison/ComparerProviderTestModel.cs b/Orm/Xtensive.Orm.Tests.Core/Comparison/ComparerProviderTestModel.cs index f0eb32652d..95e0fd1bc8 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Comparison/ComparerProviderTestModel.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Comparison/ComparerProviderTestModel.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2007-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alex Yakunin // Created: 2007.12.17 diff --git a/Orm/Xtensive.Orm.Tests.Core/Comparison/ComparerProviderTests.cs b/Orm/Xtensive.Orm.Tests.Core/Comparison/ComparerProviderTests.cs index c558acd7c7..090c2e53d7 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Comparison/ComparerProviderTests.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Comparison/ComparerProviderTests.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2007-2021 Xtensive LLC. +// Copyright (C) 2007-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alex Yakunin @@ -25,41 +25,6 @@ public void PairComparerTest() Assert.That(AdvancedComparer>.Default, Is.Not.Null); } - [Test] - public void SerializationTest() - { - SerializationTest(); - SerializationTest(); - SerializationTest(); - SerializationTest(); - SerializationTest(); - SerializationTest(); - SerializationTest(); - SerializationTest(); - SerializationTest(); - SerializationTest(); - SerializationTest(); - SerializationTest(); - SerializationTest(); - SerializationTest(); - SerializationTest(); - SerializationTest>(); - SerializationTest(); - SerializationTest(); - SerializationTest(); - SerializationTest>(); - SerializationTest>(); - SerializationTest(); - } - - private void SerializationTest() - { - var comparer = AdvancedComparer.Default; - Assert.That(comparer.Compare, Is.Not.Null); - var deserializedComparer = Cloner.Clone(comparer); - Assert.That(deserializedComparer.Compare, Is.Not.Null); - } - [Test] [Explicit] [Category("Performance")] diff --git a/Orm/Xtensive.Orm.Tests.Core/Conversion/ConverterTest.cs b/Orm/Xtensive.Orm.Tests.Core/Conversion/ConverterTest.cs index 046e524ce0..904ad324b0 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Conversion/ConverterTest.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Conversion/ConverterTest.cs @@ -15,7 +15,7 @@ namespace Xtensive.Orm.Tests.Core.Conversion { - [TestFixture] + [TestFixture(Category = "AdvancedTypeConverters")] public class ConverterTest : ConverterTestBase { private readonly IAdvancedConverterProvider provider = AdvancedConverterProvider.Default; @@ -180,7 +180,8 @@ public void Test() converter = getConverterMethod.Invoke(provider, null); } catch { - TestLog.Info($"Conversion from {typeFrom.GetShortName()} to {typeTo.GetShortName()} is not supported"); + if (UseLog) + TestLog.Warning($"Conversion from {typeFrom.GetShortName()} to {typeTo.GetShortName()} is not supported"); } if (converter!=null) { Type maskInterface = typeof (IAdvancedConverter<,>).MakeGenericType(new Type[] {typeFrom, typeTo}); @@ -190,7 +191,8 @@ public void Test() foreach (Type type in foundInterfaces) { PropertyInfo propertyInfo = type.GetProperty("IsRough"); bool isRough = (bool) propertyInfo.GetValue(converter, null); - TestLog.Info($"Conversion from {typeFrom.GetShortName()} to {typeTo.GetShortName()} is {(isRough ? "Rough" : "Strict")}"); + if (UseLog) + TestLog.Info($"Conversion from {typeFrom.GetShortName()} to {typeTo.GetShortName()} is {(isRough ? "Rough" : "Strict")}"); } } } @@ -225,7 +227,7 @@ private void NullableTestInternal(int count, bool assertNullConversi // Random test Action nullableConverterTest = DelegateHelper.CreateDelegate>(this, GetType(), - "NullableConverterTest", fromNonNullableType, fromType, toType); + nameof(NullableConverterTest), fromNonNullableType, fromType, toType); nullableConverterTest.Invoke(advancedConverter, count); // Null test diff --git a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/BooleanConverterTest.cs b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/BooleanConverterTest.cs index a4627d588f..bda228fe71 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/BooleanConverterTest.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/BooleanConverterTest.cs @@ -1,57 +1,38 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.25 using System; +using System.Collections.Generic; using NUnit.Framework; -using Xtensive.Conversion; -using Xtensive.Reflection; namespace Xtensive.Orm.Tests.Core.Conversion { - [TestFixture] - public class BooleanConverterTest : ConverterTestBase + public class BooleanConverterTest : ConverterTestBase { private readonly bool[] constants = { false, true }; - private const int iterationCount = 100; + private readonly HashSet allowedTargetTypes = new HashSet { + // strict conversions + typeof(byte), + typeof(sbyte), + typeof(short), + typeof(ushort), + typeof(int), + typeof(uint), + typeof(long), + typeof(ulong), + typeof(float), + typeof(double), + typeof(decimal), + typeof(string), + }; - [Test] - public void CombinedTest() - { - foreach (bool constant in constants) - OneValueTest(constant, iterationCount); - foreach (bool constant in constants) - OneValueTest(constant, iterationCount); - foreach (bool constant in constants) - OneValueTest(constant, iterationCount); - foreach (bool constant in constants) - OneValueTest(constant, iterationCount); - foreach (bool constant in constants) - OneValueTest(constant, iterationCount); - foreach (bool constant in constants) - OneValueTest(constant, iterationCount); - foreach (bool constant in constants) - OneValueTest(constant, iterationCount); - foreach (bool constant in constants) - OneValueTest(constant, iterationCount); - foreach (bool constant in constants) - OneValueTest(constant, iterationCount); - foreach (bool constant in constants) - OneValueTest(constant, iterationCount); - foreach (bool constant in constants) - OneValueTest(constant, iterationCount); - foreach (bool constant in constants) - OneValueTest(constant, iterationCount); - foreach (bool constant in constants) - OneValueTest(constant, iterationCount); - foreach (bool constant in constants) - OneValueTest(constant, iterationCount); - foreach (bool constant in constants) - OneValueTest(constant, iterationCount); - foreach (bool constant in constants) - OneValueTest(constant, iterationCount); - } + /// + protected override bool[] Constants => constants; + + /// + protected override HashSet AllowedTargetTypes => allowedTargetTypes; } } diff --git a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/ByteArrayConverterTest.cs b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/ByteArrayConverterTest.cs new file mode 100644 index 0000000000..ac2150913e --- /dev/null +++ b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/ByteArrayConverterTest.cs @@ -0,0 +1,28 @@ +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Roman Churakov +// Created: 2008.01.25 + +using System; +using System.Collections.Generic; +namespace Xtensive.Orm.Tests.Core.Conversion +{ + public class ByteArrayConverterTest : ConverterTestBase + { + private readonly byte[][] constants = { + Array.Empty(), + new byte[] { 0, 1, 15, 26, 52, 75, 127}, + }; + private readonly HashSet allowedTargetTypes = new() { + // strict conversions + typeof(string), + }; + + /// + protected override byte[][] Constants => constants; + + /// + protected override HashSet AllowedTargetTypes => allowedTargetTypes; + } +} diff --git a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/ByteConverterTest.cs b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/ByteConverterTest.cs index 4f0a6b3c9d..0a7ff586f9 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/ByteConverterTest.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/ByteConverterTest.cs @@ -1,57 +1,40 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.25 using System; +using System.Collections.Generic; using NUnit.Framework; -using Xtensive.Conversion; -using Xtensive.Reflection; - namespace Xtensive.Orm.Tests.Core.Conversion { - [TestFixture] - public class ByteConverterTest : ConverterTestBase + public class ByteConverterTest : ConverterTestBase { private readonly byte[] constants = { 0, 1, 123, 0x7F, 0xFF}; - private const int iterationCount = 100; + private readonly HashSet allowedTargetTypes = new() { + // strict conversions + typeof(sbyte), + typeof(short), + typeof(ushort), + typeof(uint), + typeof(long), + typeof(ulong), + typeof(float), + typeof(double), + typeof(decimal), + typeof(DateTime), + typeof(TimeSpan), + typeof(string), + typeof(char), + // rough coversions + typeof(bool), + }; + + /// + protected override byte[] Constants => constants; - [Test] - public void CombinedTest() - { - foreach (byte constant in constants) - OneValueTest(constant, iterationCount); - foreach (byte constant in constants) - OneValueTest(constant, iterationCount); - foreach (byte constant in constants) - OneValueTest(constant, iterationCount); - foreach (byte constant in constants) - OneValueTest(constant, iterationCount); - foreach (byte constant in constants) - OneValueTest(constant, iterationCount); - foreach (byte constant in constants) - OneValueTest(constant, iterationCount); - foreach (byte constant in constants) - OneValueTest(constant, iterationCount); - foreach (byte constant in constants) - OneValueTest(constant, iterationCount); - foreach (byte constant in constants) - OneValueTest(constant, iterationCount); - foreach (byte constant in constants) - OneValueTest(constant, iterationCount); - foreach (byte constant in constants) - OneValueTest(constant, iterationCount); - foreach (byte constant in constants) - OneValueTest(constant, iterationCount); - foreach (byte constant in constants) - OneValueTest(constant, iterationCount); - foreach (byte constant in constants) - OneValueTest(constant, iterationCount); - foreach (byte constant in constants) - OneValueTest(constant, iterationCount); - foreach (byte constant in constants) - OneValueTest(constant, iterationCount); - } + /// + protected override HashSet AllowedTargetTypes => allowedTargetTypes; } } diff --git a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/CharConverterTest.cs b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/CharConverterTest.cs index 8a6467cb1b..019b28ee4b 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/CharConverterTest.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/CharConverterTest.cs @@ -1,83 +1,66 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.28 using System; +using System.Collections.Generic; using NUnit.Framework; -using Xtensive.Orm.Tests; namespace Xtensive.Orm.Tests.Core.Conversion { - [TestFixture] - public class CharConverterTest : ConverterTestBase + public class CharConverterTest : ConverterTestBase { private readonly char[] constants = { 'A', '\0', '0', (char)123, (char)0x7F, (char)0xFF, (char)0x7FFF, (char)0xFFFF, 'к'}; - private const int iterationCount = 100; + private readonly HashSet allowedTargetTypes = new() { + // strict conversions + typeof(byte), + typeof(sbyte), + typeof(short), + typeof(ushort), + typeof(int), + typeof(uint), + typeof(long), + typeof(ulong), + typeof(float), + typeof(double), + typeof(decimal), + typeof(string), + }; + + /// + protected override char[] Constants => constants; + + /// + protected override HashSet AllowedTargetTypes => allowedTargetTypes; + [Test] - public void SingleTest() + public void AdditionalFloatTest() { IInstanceGenerator generator = InstanceGeneratorProvider.Default.GetInstanceGenerator(); Random random = RandomManager.CreateRandom(1, SeedVariatorType.CallingMethod); - for (int i = 0; i < iterationCount * 100; i++) + for (int i = 0; i < IterationCount * 100; i++) OneValueTest(generator.GetInstance(random), 1); } [Test] - public void DoubleTest() + public void AddtionalDoubleTest() { IInstanceGenerator generator = InstanceGeneratorProvider.Default.GetInstanceGenerator(); Random random = RandomManager.CreateRandom(1, SeedVariatorType.CallingMethod); - for (int i = 0; i < iterationCount * 100; i++) + for (int i = 0; i < IterationCount * 100; i++) OneValueTest(generator.GetInstance(random), 1); } [Test] - public void DecimalTest() + public void AdditionalDecimalTest() { IInstanceGenerator generator = InstanceGeneratorProvider.Default.GetInstanceGenerator(); Random random = RandomManager.CreateRandom(1, SeedVariatorType.CallingMethod); - for (int i = 0; i < iterationCount * 100; i++) + for (int i = 0; i < IterationCount * 100; i++) OneValueTest(generator.GetInstance(random), 1); } - - [Test] - public void CombinedTest() - { - foreach (char constant in constants) - OneValueTest(constant, iterationCount); - foreach (char constant in constants) - OneValueTest(constant, iterationCount); - foreach (char constant in constants) - OneValueTest(constant, iterationCount); - foreach (char constant in constants) - OneValueTest(constant, iterationCount); - foreach (char constant in constants) - OneValueTest(constant, iterationCount); - foreach (char constant in constants) - OneValueTest(constant, iterationCount); - foreach (char constant in constants) - OneValueTest(constant, iterationCount); - foreach (char constant in constants) - OneValueTest(constant, iterationCount); - foreach (char constant in constants) - OneValueTest(constant, iterationCount); - foreach (char constant in constants) - OneValueTest(constant, iterationCount); - foreach (char constant in constants) - OneValueTest(constant, iterationCount); - foreach (char constant in constants) - OneValueTest(constant, iterationCount); - foreach (char constant in constants) - OneValueTest(constant, iterationCount); - foreach (char constant in constants) - OneValueTest(constant, iterationCount); - foreach (char constant in constants) - OneValueTest(constant, iterationCount); - foreach (char constant in constants) - OneValueTest(constant, iterationCount); - } } } diff --git a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/ConverterTestBase.cs b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/ConverterTestBase.cs index c0f95871cf..e7768558ce 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/ConverterTestBase.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/ConverterTestBase.cs @@ -1,20 +1,24 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.25 using System; +using System.Collections.Generic; using NUnit.Framework; using Xtensive.Conversion; using Xtensive.Reflection; namespace Xtensive.Orm.Tests.Core.Conversion { - public class ConverterTestBase + public abstract class ConverterTestBase { - protected bool UseLog; + /// + /// Defines whether tests will write output messagest to log. Default is false + /// + protected virtual bool UseLog => false; public void OneValueTest(TFrom value, int count) { @@ -26,7 +30,7 @@ public void OneValueTest(TFrom value, int count) } catch (InvalidOperationException e) { if (UseLog) - TestLog.Info($"{e.Message}"); + TestLog.Info($"{e.Message}"); } for (int i = 0; i < count; i++) { @@ -45,39 +49,280 @@ public void OneValueTest(TFrom value, int count) if (innerLogFlag) TestLog.Info($"Conversion from {typeof(TFrom).GetShortName()} to {typeof(TTo).GetShortName()} is rough."); } - else - Assert.That(reconvertedValue, Is.EqualTo(value), "reconvertedValue"); + else { + if (typeof(TFrom).IsArray) { + if (value is null) { + Assert.That(reconvertedValue, Is.Null, "reconvertedValue"); + } + + var arrayValue = value as Array; + var arrayReconverted = reconvertedValue as Array; + Assert.That(arrayReconverted.Length, Is.EqualTo(arrayValue.Length)); + for(var j = 0; j < arrayValue.Length; j++) { + Assert.That(arrayReconverted.GetValue(j), Is.EqualTo(arrayValue.GetValue(j))); + } + } + else { + Assert.That(reconvertedValue, Is.EqualTo(value), "reconvertedValue"); + } + } } catch (OverflowException e) { if (innerLogFlag) - TestLog.Info($"Reconversion of {convertedValue} of {typeof(TTo).GetShortName()} type to type {typeof(TFrom).GetShortName()} failed."); + TestLog.Error($"Reconversion of {convertedValue} of {typeof(TTo).GetShortName()} type to type {typeof(TFrom).GetShortName()} failed."); } catch (ArgumentOutOfRangeException e) { if (innerLogFlag) - TestLog.Info($"Reconversion of {convertedValue} of {typeof(TTo).GetShortName()} type to type {typeof(TFrom).GetShortName()} failed."); + TestLog.Error($"Reconversion of {convertedValue} of {typeof(TTo).GetShortName()} type to type {typeof(TFrom).GetShortName()} failed."); } catch (FormatException e) { if (innerLogFlag) - TestLog.Info($"Reconversion of {convertedValue} of {typeof(TTo).GetShortName()} type to type {typeof(TFrom).GetShortName()} failed."); + TestLog.Error($"Reconversion of {convertedValue} of {typeof(TTo).GetShortName()} type to type {typeof(TFrom).GetShortName()} failed."); } } } catch (OverflowException e) { if (innerLogFlag) - TestLog.Info($"Conversion of {value} of {typeof(TFrom).GetShortName()} type to type {typeof(TTo).GetShortName()} failed."); + TestLog.Error($"Conversion of {value} of {typeof(TFrom).GetShortName()} type to type {typeof(TTo).GetShortName()} failed."); } catch (ArgumentOutOfRangeException e) { if (innerLogFlag) - TestLog.Info($"Conversion of {value} of {typeof(TFrom).GetShortName()} type to type {typeof(TTo).GetShortName()} failed."); + TestLog.Error($"Conversion of {value} of {typeof(TFrom).GetShortName()} type to type {typeof(TTo).GetShortName()} failed."); } catch (FormatException e) { if (innerLogFlag) - TestLog.Info($"Conversion of {value} of {typeof(TFrom).GetShortName()} type to type {typeof(TTo).GetShortName()} failed."); + TestLog.Error($"Conversion of {value} of {typeof(TFrom).GetShortName()} type to type {typeof(TTo).GetShortName()} failed."); } } else if (innerLogFlag) - TestLog.Info($"Conversion from {typeof(TFrom).GetShortName()} to {typeof(TTo).GetShortName()} is not supported."); + TestLog.Warning($"Conversion from {typeof(TFrom).GetShortName()} to {typeof(TTo).GetShortName()} is not supported."); + } + } + } + + + [TestFixture(Category = "AdvancedTypeConverters")] + public abstract class ConverterTestBase : ConverterTestBase + { + /// + /// Itterations for + /// + protected virtual int IterationCount => 50; + + /// + /// Constants to test on. + /// + protected abstract TFrom[] Constants { get; } + + /// + /// Allowed target types for converston. If type is not in this collection, then test for the type will be ignored + /// + protected abstract HashSet AllowedTargetTypes { get; } + + [Test] + public void BooleanTest() + { + RequireConversionTo(); + foreach (TFrom constant in Constants) { + OneValueTest(constant, IterationCount); + } + } + + [Test] + public void ByteTest() + { + RequireConversionTo(); + + foreach (TFrom constant in Constants) { + OneValueTest(constant, IterationCount); + } + } + + [Test] + public void SByteTest() + { + RequireConversionTo(); + + foreach (TFrom constant in Constants) { + OneValueTest(constant, IterationCount); + } + } + + [Test] + public void ShortTest() + { + RequireConversionTo(); + + foreach (TFrom constant in Constants) { + OneValueTest(constant, IterationCount); + } + } + + [Test] + public void UShortTest() + { + RequireConversionTo(); + + foreach (TFrom constant in Constants) { + OneValueTest(constant, IterationCount); + } + } + + [Test] + public void IntTest() + { + RequireConversionTo(); + + foreach (TFrom constant in Constants) { + OneValueTest(constant, IterationCount); + } + } + + [Test] + public void UIntTest() + { + RequireConversionTo(); + + foreach (TFrom constant in Constants) { + OneValueTest(constant, IterationCount); + } + } + + [Test] + public void LongTest() + { + RequireConversionTo(); + + foreach (TFrom constant in Constants) { + OneValueTest(constant, IterationCount); + } + } + + [Test] + public void ULongTest() + { + RequireConversionTo(); + + foreach (TFrom constant in Constants) { + OneValueTest(constant, IterationCount); + } + } + + [Test] + public void FloatTest() + { + RequireConversionTo(); + + foreach (TFrom constant in Constants) { + OneValueTest(constant, IterationCount); + } + } + + [Test] + public void DoubleTest() + { + RequireConversionTo(); + + foreach (TFrom constant in Constants) { + OneValueTest(constant, IterationCount); + } + } + + [Test] + public void DecimalTest() + { + RequireConversionTo(); + + foreach (TFrom constant in Constants) { + OneValueTest(constant, IterationCount); + } + } + + [Test] + public void DateTimeOffsetTest() + { + RequireConversionTo(); + + foreach (TFrom constant in Constants) { + OneValueTest(constant, IterationCount); + } + } + + [Test] + public void DateTimeTest() + { + RequireConversionTo(); + + foreach (TFrom constant in Constants) { + OneValueTest(constant, IterationCount); } } + + [Test] + public void DateOnlyTest() + { + RequireConversionTo(); + + foreach (TFrom constant in Constants) { + OneValueTest(constant, IterationCount); + } + } + + [Test] + public void TimeOnlyTest() + { + RequireConversionTo(); + + foreach (TFrom constant in Constants) { + OneValueTest(constant, IterationCount); + } + } + + [Test] + public void TimeSpanTest() + { + RequireConversionTo(); + + foreach (TFrom constant in Constants) { + OneValueTest(constant, IterationCount); + } + } + + [Test] + public void GuidTest() + { + RequireConversionTo(); + + foreach (TFrom constant in Constants) { + OneValueTest(constant, IterationCount); + } + } + + [Test] + public void StringTest() + { + RequireConversionTo(); + + foreach (TFrom constant in Constants) { + OneValueTest(constant, IterationCount); + } + } + + [Test] + public void CharTest() + { + RequireConversionTo(); + + foreach (TFrom constant in Constants) { + OneValueTest(constant, IterationCount); + } + } + + private void RequireConversionTo() + { + var targetType = typeof(TTo); + if (!AllowedTargetTypes.Contains(targetType)) + throw new IgnoreException($"Conversion to {targetType.Name} is not allowed to check"); + } } } diff --git a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/DateOnlyConverterTest.cs b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/DateOnlyConverterTest.cs new file mode 100644 index 0000000000..757d48eeb1 --- /dev/null +++ b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/DateOnlyConverterTest.cs @@ -0,0 +1,46 @@ +// Copyright (C) 2003-2010 Xtensive LLC. +// All rights reserved. +// For conditions of distribution and use, see license. +// Created by: Roman Churakov +// Created: 2008.01.25 + +using System; +using System.Collections.Generic; +using NUnit.Framework; + +namespace Xtensive.Orm.Tests.Core.Conversion +{ + public class DateOnlyConverterTest : ConverterTestBase + { + private readonly DateOnly[] constants = { + DateOnly.FromDateTime(DateTime.Now.Date), + new DateOnly(2000, 1, 1), + DateOnly.FromDayNumber(0xFFFFF), + DateOnly.FromDayNumber(2237236), + DateOnly.FromDayNumber(0xFFFF), + DateOnly.FromDayNumber(3153599), + DateOnly.MinValue, DateOnly.MaxValue + }; + + private readonly HashSet allowedTargetTypes = new() { + // strict conversions + typeof(int), + typeof(uint), + typeof(long), + typeof(ulong), + typeof(decimal), + typeof(DateTime), + typeof(TimeSpan), + typeof(string), + // rough conversions + typeof(float), + typeof(double), + }; + + /// + protected override DateOnly[] Constants => constants; + + /// + protected override HashSet AllowedTargetTypes => allowedTargetTypes; + } +} diff --git a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/DateTimeConverterTest.cs b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/DateTimeConverterTest.cs index 61b9fbe52c..0ab75fb84d 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/DateTimeConverterTest.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/DateTimeConverterTest.cs @@ -1,80 +1,64 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.25 using System; +using System.Collections.Generic; using System.Globalization; using NUnit.Framework; -using Xtensive.Orm.Tests; namespace Xtensive.Orm.Tests.Core.Conversion { - [TestFixture] - public class DateTimeConverterTest : ConverterTestBase + public class DateTimeConverterTest : ConverterTestBase { private readonly DateTime[] constants = { DateTime.Now, new DateTime(2000, 1, 1, 0, 0, 0, 0, DateTimeKind.Local), - new DateTime(2000, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), - new DateTime(0x7FFFFFFF), new DateTime(223372036854714932), - new DateTime(0xFFFF), new DateTime(3155378975999999999), - DateTime.MinValue, DateTime.MaxValue}; - private const int iterationCount = 100; + new DateTime(2000, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), + new DateTime(0x7FFFFFFF), new DateTime(223372036854714932), + new DateTime(0xFFFF), new DateTime(3155378975999999999), + DateTime.MinValue, DateTime.MaxValue}; + private readonly HashSet allowedTargetTypes = new() { + // strict conversions + typeof(byte), + typeof(sbyte), + typeof(short), + typeof(ushort), + typeof(int), + typeof(uint), + typeof(long), + typeof(ulong), + typeof(decimal), + typeof(DateTime), + typeof(TimeSpan), + typeof(string), + // rough conversions + typeof(float), + typeof(double), + typeof(DateTimeOffset) + }; + + + /// + protected override DateTime[] Constants => constants; + + /// + protected override HashSet AllowedTargetTypes => allowedTargetTypes; - [Test] - public void Test() - { - TestLog.Info($"{DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss.fff %K", CultureInfo.InvariantCulture)}"); - IInstanceGenerator generator = InstanceGeneratorProvider.Default.GetInstanceGenerator(); - Random random = RandomManager.CreateRandom(1, SeedVariatorType.CallingMethod); - for (int i = 0; i < iterationCount * 1; i++) - TestLog.Info($"{generator.GetInstance(random).ToString("yyyy/MM/dd hh:mm:ss.fff %K", CultureInfo.InvariantCulture)}"); - } [Test] - public void StringTest() + public void AdditionalStringTest() { + if (UseLog) + TestLog.Info($" Format of values {DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss.fff %K", CultureInfo.InvariantCulture)}"); IInstanceGenerator generator = InstanceGeneratorProvider.Default.GetInstanceGenerator(); Random random = RandomManager.CreateRandom(1, SeedVariatorType.CallingMethod); - for (int i = 0; i < iterationCount * 100; i++) - OneValueTest(generator.GetInstance(random), 1); - } - - [Test] - public void CombinedTest() - { - foreach (DateTime constant in constants) - OneValueTest(constant, iterationCount); - foreach (DateTime constant in constants) - OneValueTest(constant, iterationCount); - foreach (DateTime constant in constants) - OneValueTest(constant, iterationCount); - foreach (DateTime constant in constants) - OneValueTest(constant, iterationCount); - foreach (DateTime constant in constants) - OneValueTest(constant, iterationCount); - foreach (DateTime constant in constants) - OneValueTest(constant, iterationCount); - foreach (DateTime constant in constants) - OneValueTest(constant, iterationCount); - foreach (DateTime constant in constants) - OneValueTest(constant, iterationCount); - foreach (DateTime constant in constants) - OneValueTest(constant, iterationCount); - foreach (DateTime constant in constants) - OneValueTest(constant, iterationCount); - foreach (DateTime constant in constants) - OneValueTest(constant, iterationCount); - foreach (DateTime constant in constants) - OneValueTest(constant, iterationCount); - foreach (DateTime constant in constants) - OneValueTest(constant, iterationCount); - foreach (DateTime constant in constants) - OneValueTest(constant, iterationCount); - foreach (DateTime constant in constants) - OneValueTest(constant, iterationCount); - foreach (DateTime constant in constants) - OneValueTest(constant, iterationCount); + for (int i = 0; i < IterationCount * 100; i++) { + var value = generator.GetInstance(random); + if (UseLog) + TestLog.Info($"Trying to convert '{generator.GetInstance(random).ToString("yyyy/MM/dd hh:mm:ss.fff %K", CultureInfo.InvariantCulture)}'"); + OneValueTest(value, 1); + } } } } diff --git a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/DateTimeOffsetConverterTest.cs b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/DateTimeOffsetConverterTest.cs new file mode 100644 index 0000000000..3e0fbba80e --- /dev/null +++ b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/DateTimeOffsetConverterTest.cs @@ -0,0 +1,49 @@ +// Copyright (C) 2003-2010 Xtensive LLC. +// All rights reserved. +// For conditions of distribution and use, see license. +// Created by: Roman Churakov +// Created: 2008.01.25 + +using System; +using System.Collections.Generic; + +namespace Xtensive.Orm.Tests.Core.Conversion +{ + public class DateTimeOffsetConverterTest : ConverterTestBase + { + private readonly DateTimeOffset[] constants = { + new DateTimeOffset(DateTime.MinValue, TimeSpan.FromHours(-3)), + new DateTimeOffset(DateTime.MaxValue, TimeSpan.FromHours(+3)), + new DateTimeOffset(new DateTime(2000, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), TimeSpan.Zero), + new DateTimeOffset(new DateTime(2000, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), TimeSpan.FromHours(-3)), + new DateTimeOffset(new DateTime(2000, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), TimeSpan.FromHours(+3)), + new DateTimeOffset(new DateTime(2000, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(2, 30, 0)), + new DateTimeOffset(new DateTime(2000, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(2, 30, 0).Negate()), + new DateTimeOffset(new DateTime(223372036854714932), TimeSpan.Zero), + new DateTimeOffset(new DateTime(223372036854714932), TimeSpan.FromHours(-3)), + new DateTimeOffset(new DateTime(223372036854714932), TimeSpan.FromHours(+3)), + new DateTimeOffset(new DateTime(223372036854714932), new TimeSpan(2, 30, 0)), + new DateTimeOffset(new DateTime(223372036854714932), new TimeSpan(2, 30, 0).Negate()), + DateTimeOffset.Now, DateTimeOffset.UtcNow, + DateTimeOffset.MinValue, DateTimeOffset.MaxValue + }; + + private readonly HashSet allowedTargetTypes = new() { + // strict conversions + typeof(string), + // rough conversions + typeof(long), + typeof(ulong), + typeof(decimal), + typeof(DateTime), + typeof(TimeSpan) + }; + + + protected override DateTimeOffset[] Constants => constants; + + protected override HashSet AllowedTargetTypes => allowedTargetTypes; + + protected override int IterationCount => 10; + } +} diff --git a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/DecimalConverterTest.cs b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/DecimalConverterTest.cs index 87cec752b4..a0566ae553 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/DecimalConverterTest.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/DecimalConverterTest.cs @@ -1,67 +1,59 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.25 using System; +using System.Collections.Generic; using NUnit.Framework; -using Xtensive.Orm.Tests; namespace Xtensive.Orm.Tests.Core.Conversion { - [TestFixture] - public class DecimalConverterTest : ConverterTestBase + public class DecimalConverterTest : ConverterTestBase { - private readonly decimal[] constants = { 0x7FFFFFFFFFFF1234, 0, 123, 0x7F, 0xFF, 0x7FFFFFFF, -9223372036854714932, - 0xFFFF, 0x7FFF, 0xFFFFFFFF, 0xFFFFFFFFFFFFFF, -72057594037927935, decimal.MinValue, decimal.MaxValue, - (decimal)2.5, (decimal)1.6E-308d, (decimal)234.14748366, (decimal)-0.4503599627370496}; - private const int iterationCount = 100; + private readonly decimal[] constants = { + 0x7FFFFFFFFFFF1234, 0, 123, 0x7F, 0xFF, 0x7FFFFFFF, -9223372036854714932, + 0xFFFF, 0x7FFF, 0xFFFFFFFF, 0xFFFFFFFFFFFFFF, -72057594037927935, decimal.MinValue, decimal.MaxValue, + (decimal)2.5, (decimal)1.6E-308d, (decimal)234.14748366, (decimal)-0.4503599627370496 + }; + + private readonly HashSet allowedTargetTypes = new() { + // strict conversions + typeof(string), + // rough coversions + typeof(bool), + typeof(byte), + typeof(sbyte), + typeof(short), + typeof(ushort), + typeof(int), + typeof(uint), + typeof(long), + typeof(ulong), + typeof(float), + typeof(double), + typeof(DateTimeOffset), + typeof(DateTime), + typeof(DateOnly), + typeof(TimeOnly), + typeof(TimeSpan), + typeof(char), + }; + + /// + protected override decimal[] Constants => constants; + + /// + protected override HashSet AllowedTargetTypes => allowedTargetTypes; [Test] - public void StringTest() + public void AdditionaStringTest() { IInstanceGenerator generator = InstanceGeneratorProvider.Default.GetInstanceGenerator(); Random random = RandomManager.CreateRandom(1, SeedVariatorType.CallingMethod); - for (int i = 0; i < iterationCount*1000; i++) + for (int i = 0; i < IterationCount * 100; i++) OneValueTest(generator.GetInstance(random), 1); } - - [Test] - public void CombinedTest() - { - foreach (decimal constant in constants) - OneValueTest(constant, iterationCount); - foreach (decimal constant in constants) - OneValueTest(constant, iterationCount); - foreach (decimal constant in constants) - OneValueTest(constant, iterationCount); - foreach (decimal constant in constants) - OneValueTest(constant, iterationCount); - foreach (decimal constant in constants) - OneValueTest(constant, iterationCount); - foreach (decimal constant in constants) - OneValueTest(constant, iterationCount); - foreach (decimal constant in constants) - OneValueTest(constant, iterationCount); - foreach (decimal constant in constants) - OneValueTest(constant, iterationCount); - foreach (decimal constant in constants) - OneValueTest(constant, iterationCount); - foreach (decimal constant in constants) - OneValueTest(constant, iterationCount); - foreach (decimal constant in constants) - OneValueTest(constant, iterationCount); - foreach (decimal constant in constants) - OneValueTest(constant, iterationCount); - foreach (decimal constant in constants) - OneValueTest(constant, iterationCount); - foreach (decimal constant in constants) - OneValueTest(constant, iterationCount); - foreach (decimal constant in constants) - OneValueTest(constant, iterationCount); - foreach (decimal constant in constants) - OneValueTest(constant, iterationCount); - } } } diff --git a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/DoubleConverterTest.cs b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/DoubleConverterTest.cs index f0981b78a0..55e2e80c9e 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/DoubleConverterTest.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/DoubleConverterTest.cs @@ -1,17 +1,16 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.25 using System; +using System.Collections.Generic; using NUnit.Framework; -using Xtensive.Orm.Tests; namespace Xtensive.Orm.Tests.Core.Conversion { - [TestFixture] - public class DoubleConverterTest : ConverterTestBase + public class DoubleConverterTest : ConverterTestBase { private readonly double[] constants = { 0x7FFFFFFFFFFF1234, 0, 123, 0x7F, 0xFF, 0x7FFFFFFF, -9223372036854714932, @@ -21,52 +20,42 @@ public class DoubleConverterTest : ConverterTestBase 2.14748366E+11d, 2.14748366E+12d, 2.14748366E+13d, 2.14748366E+14d, 2.14748366E+15d, 2.14748366E+16d, 1.6E+308d, 2.14748366E+37d, 0.4503599627370496 }; - private const int iterationCount = 100; + private readonly HashSet allowedTargetTypes = new HashSet() { + // strict conversions + typeof(string), + // rough coversions + typeof(bool), + typeof(byte), + typeof(sbyte), + typeof(short), + typeof(ushort), + typeof(int), + typeof(uint), + typeof(long), + typeof(ulong), + typeof(float), + typeof(decimal), + typeof(DateTime), + typeof(DateOnly), + typeof(TimeOnly), + typeof(TimeSpan), + typeof(char), + }; + + /// + protected override double[] Constants => constants; + + /// + protected override HashSet AllowedTargetTypes => allowedTargetTypes; + [Test] - public void StringTest() + public void AdditionalStringTest() { IInstanceGenerator generator = InstanceGeneratorProvider.Default.GetInstanceGenerator(); Random random = RandomManager.CreateRandom(1, SeedVariatorType.CallingMethod); - for (int i = 0; i < iterationCount * 10000; i++) + for (int i = 0; i < IterationCount * 100; i++) OneValueTest(generator.GetInstance(random), 1); } - - [Test] - public void CombinedTest() - { - foreach (double constant in constants) - OneValueTest(constant, iterationCount); - foreach (double constant in constants) - OneValueTest(constant, iterationCount); - foreach (double constant in constants) - OneValueTest(constant, iterationCount); - foreach (double constant in constants) - OneValueTest(constant, iterationCount); - foreach (double constant in constants) - OneValueTest(constant, iterationCount); - foreach (double constant in constants) - OneValueTest(constant, iterationCount); - foreach (double constant in constants) - OneValueTest(constant, iterationCount); - foreach (double constant in constants) - OneValueTest(constant, iterationCount); - foreach (double constant in constants) - OneValueTest(constant, iterationCount); - foreach (double constant in constants) - OneValueTest(constant, iterationCount); - foreach (double constant in constants) - OneValueTest(constant, iterationCount); - foreach (double constant in constants) - OneValueTest(constant, iterationCount); - foreach (double constant in constants) - OneValueTest(constant, iterationCount); - foreach (double constant in constants) - OneValueTest(constant, iterationCount); - foreach (double constant in constants) - OneValueTest(constant, iterationCount); - foreach (double constant in constants) - OneValueTest(constant, iterationCount); - } } } diff --git a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/GuidConverterTest.cs b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/GuidConverterTest.cs index fe65a29422..6cd916ceb7 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/GuidConverterTest.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/GuidConverterTest.cs @@ -1,72 +1,30 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.25 - using System; +using System.Collections.Generic; using NUnit.Framework; -using Xtensive.Orm.Tests; namespace Xtensive.Orm.Tests.Core.Conversion { - [TestFixture] - public class GuidConverterTest : ConverterTestBase + public class GuidConverterTest : ConverterTestBase { - private Guid[] constants; - private const int iterationCount = 100; - - [Test] - public void StringTest() - { - IInstanceGenerator generator = InstanceGeneratorProvider.Default.GetInstanceGenerator(); - Random random = RandomManager.CreateRandom(1, SeedVariatorType.CallingMethod); - for (int i = 0; i < iterationCount * 100; i++) - OneValueTest(generator.GetInstance(random), 1); - } + private readonly Guid[] constants = new Guid[] { + Guid.NewGuid(), Guid.NewGuid(), + Guid.NewGuid(), Guid.NewGuid(), + Guid.NewGuid(), Guid.NewGuid(), + Guid.NewGuid(), Guid.NewGuid(), + Guid.NewGuid(), Guid.NewGuid(), + }; + private readonly HashSet allowedTargetTypes = new() { typeof(string) }; - [Test] - public void CombinedTest() - { - constants = new Guid[10]; - IInstanceGenerator generator = InstanceGeneratorProvider.Default.GetInstanceGenerator(); - Random random = RandomManager.CreateRandom(1, SeedVariatorType.CallingMethod); - for (int i = 0; i < 10; i++) - constants[i] = generator.GetInstance(random); + /// + protected override Guid[] Constants => constants; - foreach (Guid constant in constants) - OneValueTest(constant, iterationCount); - foreach (Guid constant in constants) - OneValueTest(constant, iterationCount); - foreach (Guid constant in constants) - OneValueTest(constant, iterationCount); - foreach (Guid constant in constants) - OneValueTest(constant, iterationCount); - foreach (Guid constant in constants) - OneValueTest(constant, iterationCount); - foreach (Guid constant in constants) - OneValueTest(constant, iterationCount); - foreach (Guid constant in constants) - OneValueTest(constant, iterationCount); - foreach (Guid constant in constants) - OneValueTest(constant, iterationCount); - foreach (Guid constant in constants) - OneValueTest(constant, iterationCount); - foreach (Guid constant in constants) - OneValueTest(constant, iterationCount); - foreach (Guid constant in constants) - OneValueTest(constant, iterationCount); - foreach (Guid constant in constants) - OneValueTest(constant, iterationCount); - foreach (Guid constant in constants) - OneValueTest(constant, iterationCount); - foreach (Guid constant in constants) - OneValueTest(constant, iterationCount); - foreach (Guid constant in constants) - OneValueTest(constant, iterationCount); - foreach (Guid constant in constants) - OneValueTest(constant, iterationCount); - } + /// + protected override HashSet AllowedTargetTypes => allowedTargetTypes; } } diff --git a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/Int16ConverterTest.cs b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/Int16ConverterTest.cs index 6638568a76..5a7ea61ab6 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/Int16ConverterTest.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/Int16ConverterTest.cs @@ -1,57 +1,41 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.25 using System; +using System.Collections.Generic; using NUnit.Framework; -using Xtensive.Conversion; -using Xtensive.Reflection; - namespace Xtensive.Orm.Tests.Core.Conversion { - [TestFixture] - public class Int16ConverterTest : ConverterTestBase + public class Int16ConverterTest : ConverterTestBase { private readonly short[] constants = { 0, -1, 1, 123, 0x7F, 0xFF, 0x7FFF, -32768 }; - private const int iterationCount = 100; + private readonly HashSet allowedTargetTypes = new HashSet() { + // strict conversions + typeof(byte), + typeof(sbyte), + typeof(ushort), + typeof(int), + typeof(uint), + typeof(long), + typeof(ulong), + typeof(float), + typeof(double), + typeof(decimal), + typeof(DateTime), + typeof(TimeSpan), + typeof(string), + typeof(char), + // rough coversions + typeof(bool), + }; + + /// + protected override short[] Constants => constants; - [Test] - public void CombinedTest() - { - foreach (short constant in constants) - OneValueTest(constant, iterationCount); - foreach (short constant in constants) - OneValueTest(constant, iterationCount); - foreach (short constant in constants) - OneValueTest(constant, iterationCount); - foreach (short constant in constants) - OneValueTest(constant, iterationCount); - foreach (short constant in constants) - OneValueTest(constant, iterationCount); - foreach (short constant in constants) - OneValueTest(constant, iterationCount); - foreach (short constant in constants) - OneValueTest(constant, iterationCount); - foreach (short constant in constants) - OneValueTest(constant, iterationCount); - foreach (short constant in constants) - OneValueTest(constant, iterationCount); - foreach (short constant in constants) - OneValueTest(constant, iterationCount); - foreach (short constant in constants) - OneValueTest(constant, iterationCount); - foreach (short constant in constants) - OneValueTest(constant, iterationCount); - foreach (short constant in constants) - OneValueTest(constant, iterationCount); - foreach (short constant in constants) - OneValueTest(constant, iterationCount); - foreach (short constant in constants) - OneValueTest(constant, iterationCount); - foreach (short constant in constants) - OneValueTest(constant, iterationCount); - } + /// + protected override HashSet AllowedTargetTypes => allowedTargetTypes; } } diff --git a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/Int32ConverterTest.cs b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/Int32ConverterTest.cs index 5ba19cc727..ae93ba4698 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/Int32ConverterTest.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/Int32ConverterTest.cs @@ -1,57 +1,43 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.25 using System; +using System.Collections.Generic; using NUnit.Framework; -using Xtensive.Conversion; -using Xtensive.Reflection; namespace Xtensive.Orm.Tests.Core.Conversion { - [TestFixture] - public class Int32ConverterTest : ConverterTestBase + public class Int32ConverterTest : ConverterTestBase { private readonly int[] constants = { 0, 1, 123, 0x7F, 0xFF, 0x7FFFFFFF, -2147483648, 0xFFFF, 0x7FFF }; - private const int iterationCount = 100; + private readonly HashSet allowedTargetTypes = new HashSet() { + // strict conversions + typeof (byte), + typeof (sbyte), + typeof (short), + typeof (ushort), + typeof (uint), + typeof (long), + typeof (ulong), + typeof (double), + typeof (decimal), + typeof (DateTime), + typeof (DateOnly), + typeof (TimeSpan), + typeof (string), + typeof (char), + // rough coversions + typeof (bool), + typeof (float), + }; - [Test] - public void CombinedTest() - { - foreach (int constant in constants) - OneValueTest(constant, iterationCount); - foreach (int constant in constants) - OneValueTest(constant, iterationCount); - foreach (int constant in constants) - OneValueTest(constant, iterationCount); - foreach (int constant in constants) - OneValueTest(constant, iterationCount); - foreach (int constant in constants) - OneValueTest(constant, iterationCount); - foreach (int constant in constants) - OneValueTest(constant, iterationCount); - foreach (int constant in constants) - OneValueTest(constant, iterationCount); - foreach (int constant in constants) - OneValueTest(constant, iterationCount); - foreach (int constant in constants) - OneValueTest(constant, iterationCount); - foreach (int constant in constants) - OneValueTest(constant, iterationCount); - foreach (int constant in constants) - OneValueTest(constant, iterationCount); - foreach (int constant in constants) - OneValueTest(constant, iterationCount); - foreach (int constant in constants) - OneValueTest(constant, iterationCount); - foreach (int constant in constants) - OneValueTest(constant, iterationCount); - foreach (int constant in constants) - OneValueTest(constant, iterationCount); - foreach (int constant in constants) - OneValueTest(constant, iterationCount); - } + /// + protected override int[] Constants => constants; + + /// + protected override HashSet AllowedTargetTypes => allowedTargetTypes; } } diff --git a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/Int64ConverterTest.cs b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/Int64ConverterTest.cs index 94b3672ac9..3a8861dfe1 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/Int64ConverterTest.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/Int64ConverterTest.cs @@ -1,60 +1,48 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.25 using System; +using System.Collections.Generic; using NUnit.Framework; -using Xtensive.Conversion; -using Xtensive.Reflection; namespace Xtensive.Orm.Tests.Core.Conversion { - [TestFixture] - public class Int64ConverterTest : ConverterTestBase + public class Int64ConverterTest : ConverterTestBase { private readonly long[] constants = { 0x7FFFFFFFFFFF1234, 0, 123, 0x7F, 0xFF, 0x7FFFFFFF, -9223372036854714932, 0xFFFF, 0x7FFF, 0xFFFFFFFF, 0xFFFFFFFFFFFFFF, -72057594037927935 }; - private const int iterationCount = 100; + private readonly HashSet allowedTargetTypes = new() { + // strict conversions + typeof(byte), + typeof(sbyte), + typeof(short), + typeof(ushort), + typeof(int), + typeof(uint), + typeof(ulong), + typeof(decimal), + typeof(DateTime), + typeof(DateOnly), + typeof(TimeOnly), + typeof(TimeSpan), + typeof(string), + typeof(char), + // rough coversions + typeof(bool), + typeof(float), + typeof(double), + typeof(DateTimeOffset) + }; + + /// + protected override long[] Constants => constants; - [Test] - public void MainTest () - { - foreach (long constant in constants) - OneValueTest(constant, iterationCount); - foreach (long constant in constants) - OneValueTest(constant, iterationCount); - foreach (long constant in constants) - OneValueTest(constant, iterationCount); - foreach (long constant in constants) - OneValueTest(constant, iterationCount); - foreach (long constant in constants) - OneValueTest(constant, iterationCount); - foreach (long constant in constants) - OneValueTest(constant, iterationCount); - foreach (long constant in constants) - OneValueTest(constant, iterationCount); - foreach (long constant in constants) - OneValueTest(constant, iterationCount); - foreach (long constant in constants) - OneValueTest(constant, iterationCount); - foreach (long constant in constants) - OneValueTest(constant, iterationCount); - foreach (long constant in constants) - OneValueTest(constant, iterationCount); - foreach (long constant in constants) - OneValueTest(constant, iterationCount); - foreach (long constant in constants) - OneValueTest(constant, iterationCount); - foreach (long constant in constants) - OneValueTest(constant, iterationCount); - foreach (long constant in constants) - OneValueTest(constant, iterationCount); - foreach (long constant in constants) - OneValueTest(constant, iterationCount); - } + /// + protected override HashSet AllowedTargetTypes => allowedTargetTypes; } } diff --git a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/SByteConverterTest.cs b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/SByteConverterTest.cs index 63f6a048af..a8bff2e3e3 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/SByteConverterTest.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/SByteConverterTest.cs @@ -1,57 +1,42 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.25 using System; +using System.Collections.Generic; using NUnit.Framework; -using Xtensive.Conversion; -using Xtensive.Reflection; namespace Xtensive.Orm.Tests.Core.Conversion { - [TestFixture] - public class SByteConverterTest : ConverterTestBase + public class SByteConverterTest : ConverterTestBase { private readonly sbyte[] constants = { 0, -1, 1, 123, 0x7F, -128 }; - private const int iterationCount = 100; + private readonly HashSet allowedTargetTypes = new() { + // strict conversions + typeof(byte), + typeof(short), + typeof(ushort), + typeof(int), + typeof(uint), + typeof(long), + typeof(ulong), + typeof(float), + typeof(double), + typeof(decimal), + typeof(DateTime), + typeof(TimeSpan), + typeof(string), + typeof(char), + // rough coversions + typeof(bool), + }; - [Test] - public void CombinedTest() - { - foreach (sbyte constant in constants) - OneValueTest(constant, iterationCount); - foreach (sbyte constant in constants) - OneValueTest(constant, iterationCount); - foreach (sbyte constant in constants) - OneValueTest(constant, iterationCount); - foreach (sbyte constant in constants) - OneValueTest(constant, iterationCount); - foreach (sbyte constant in constants) - OneValueTest(constant, iterationCount); - foreach (sbyte constant in constants) - OneValueTest(constant, iterationCount); - foreach (sbyte constant in constants) - OneValueTest(constant, iterationCount); - foreach (sbyte constant in constants) - OneValueTest(constant, iterationCount); - foreach (sbyte constant in constants) - OneValueTest(constant, iterationCount); - foreach (sbyte constant in constants) - OneValueTest(constant, iterationCount); - foreach (sbyte constant in constants) - OneValueTest(constant, iterationCount); - foreach (sbyte constant in constants) - OneValueTest(constant, iterationCount); - foreach (sbyte constant in constants) - OneValueTest(constant, iterationCount); - foreach (sbyte constant in constants) - OneValueTest(constant, iterationCount); - foreach (sbyte constant in constants) - OneValueTest(constant, iterationCount); - foreach (sbyte constant in constants) - OneValueTest(constant, iterationCount); - } + /// + protected override sbyte[] Constants => constants; + + /// + protected override HashSet AllowedTargetTypes => allowedTargetTypes; } } diff --git a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/SingleConverterTest.cs b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/SingleConverterTest.cs index 8b2fc6a2aa..9250853016 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/SingleConverterTest.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/SingleConverterTest.cs @@ -1,17 +1,16 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.25 using System; +using System.Collections.Generic; using NUnit.Framework; -using Xtensive.Orm.Tests; namespace Xtensive.Orm.Tests.Core.Conversion { - [TestFixture] - public class SingleConverterTest : ConverterTestBase + public class SingleConverterTest : ConverterTestBase { private readonly float[] constants = { 0x7FFFFFFFFFFF1234, 0, 123, 0x7F, 0xFF, 0x7FFFFFFF, -9223372036854714932, @@ -20,62 +19,51 @@ public class SingleConverterTest : ConverterTestBase 2.14748366E+09f, 2.14748366E+11f, 2.14748366E+12f, 2.14748366E+13f, 2.14748366E+14f, 2.14748366E+15f, 2.14748366E+16f, 2.14748366E+38f, 2.14748366E+37f }; - private const int iterationCount = 100; + private readonly HashSet allowedTargetTypes = new() { + // strict conversions + typeof(string), + // rough coversions + typeof(bool), + typeof(byte), + typeof(sbyte), + typeof(short), + typeof(ushort), + typeof(int), + typeof(uint), + typeof(long), + typeof(ulong), + typeof(double), + typeof(decimal), + typeof(DateTime), + typeof(TimeOnly), + typeof(DateOnly), + typeof(TimeSpan), + typeof(char), + }; + + /// + protected override float[] Constants => constants; + + /// + protected override HashSet AllowedTargetTypes => allowedTargetTypes; [Test] - public void StringTest() + public void AdditionalStringTest() { IInstanceGenerator generator = InstanceGeneratorProvider.Default.GetInstanceGenerator(); Random random = RandomManager.CreateRandom(1, SeedVariatorType.CallingMethod); - for (int i = 0; i < iterationCount * 10000; i++) + for (int i = 0; i < IterationCount * 100; i++) OneValueTest(generator.GetInstance(random), 1); } // Proves that float-to-double is a rough conversion. [Test] - public void DoubleTest() + public void AdditionalDoubleTest() { IInstanceGenerator generator = InstanceGeneratorProvider.Default.GetInstanceGenerator(); Random random = RandomManager.CreateRandom(1, SeedVariatorType.CallingMethod); - for (int i = 0; i < iterationCount * 10000; i++) + for (int i = 0; i < IterationCount * 100; i++) OneValueTest(generator.GetInstance(random), 1); } - - [Test] - public void CombinedTest() - { - foreach (float constant in constants) - OneValueTest(constant, iterationCount); - foreach (float constant in constants) - OneValueTest(constant, iterationCount); - foreach (float constant in constants) - OneValueTest(constant, iterationCount); - foreach (float constant in constants) - OneValueTest(constant, iterationCount); - foreach (float constant in constants) - OneValueTest(constant, iterationCount); - foreach (float constant in constants) - OneValueTest(constant, iterationCount); - foreach (float constant in constants) - OneValueTest(constant, iterationCount); - foreach (float constant in constants) - OneValueTest(constant, iterationCount); - foreach (float constant in constants) - OneValueTest(constant, iterationCount); - foreach (float constant in constants) - OneValueTest(constant, iterationCount); - foreach (float constant in constants) - OneValueTest(constant, iterationCount); - foreach (float constant in constants) - OneValueTest(constant, iterationCount); - foreach (float constant in constants) - OneValueTest(constant, iterationCount); - foreach (float constant in constants) - OneValueTest(constant, iterationCount); - foreach (float constant in constants) - OneValueTest(constant, iterationCount); - foreach (float constant in constants) - OneValueTest(constant, iterationCount); - } } } diff --git a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/StringConverterTest.cs b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/StringConverterTest.cs index b9403634e8..58c8979c33 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/StringConverterTest.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/StringConverterTest.cs @@ -1,16 +1,15 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.26 using System; using NUnit.Framework; -using Xtensive.Orm.Tests; namespace Xtensive.Orm.Tests.Core.Conversion { - [TestFixture] + [TestFixture(Category = "AdvancedTypeConverters")] public class StringConverterTest : ConverterTestBase { private readonly string[] numericConstants = { @@ -23,7 +22,27 @@ public class StringConverterTest : ConverterTestBase }; private readonly string[] guidConstants = { "12345678-9012-3456-78990-123456789022" }; private readonly string[] booleanConstants = {"false", "FALSE", "true", "tRue"}; - private readonly string[] dateTimeConstants = {}; + private readonly string[] dateTimeOffsetConstants = { + "0001/01/01 12:00:00.0000000 AM -03:00", + "9999/12/31 11:59:59.9999999 PM +03:00", + "2026/09/04 12:00:00.0000000 AM +01:00 ", + "2026/09/08 07:06:05.0000000 AM +02:50", + "2026/09/08 07:06:05.4433221 AM -02:50" + }; + private readonly string[] dateTimeConstants = { + "0001/01/01 12:00:00.0000000 AM ", + "9999/12/31 11:59:59.9999999 PM ", + "2026/09/04 12:00:00.0000000 AM Z ", + "2026/09/08 07:06:05.0000000 AM ", + "2026/09/08 07:06:05.4433221 AM " }; + private readonly string[] dateOnlyConstants = { "0001/01/01", "9999/12/31", "2026/09/08" }; + private readonly string[] timeOnlyConstants = { + "12:00:00.0000000 AM", + "11:59:59.9999999 PM", + "01:35:00.0000000 PM", + "01:35:28.0000000 PM", + "01:35:18.7630000 PM", + "01:35:15.7636578 PM",}; private const int iterationCount = 100; [Test] @@ -73,6 +92,13 @@ public void FractionalTest() OneValueTest(constant, iterationCount); } + [Test] + public void DateTimeOffsetTest() + { + foreach (string constant in dateTimeOffsetConstants) + OneValueTest(constant, iterationCount); + } + [Test] public void DateTimeTest() { @@ -80,6 +106,20 @@ public void DateTimeTest() OneValueTest(constant, iterationCount); } + [Test] + public void DateOnlyTest() + { + foreach (string constant in dateOnlyConstants) + OneValueTest(constant, iterationCount); + } + + [Test] + public void TimeOnlyTest() + { + foreach (string constant in timeOnlyConstants) + OneValueTest(constant, iterationCount); + } + [Test] public void GuidTest() { diff --git a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/TimeOnlyConverterTest.cs b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/TimeOnlyConverterTest.cs new file mode 100644 index 0000000000..84b5709906 --- /dev/null +++ b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/TimeOnlyConverterTest.cs @@ -0,0 +1,49 @@ +// Copyright (C) 2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System; +using System.Collections.Generic; +using NUnit.Framework; + +namespace Xtensive.Orm.Tests.Core.Conversion +{ + public class TimeOnlyConverterTest : ConverterTestBase + { + private const long SecondMultiplier = 1_0000000; + private const long MinuteMultiplier = 60_0000000; + private const long HourMultiplier = 3600_0000000; + + private readonly TimeOnly[] constants = { + new TimeOnly(1, 15), + new TimeOnly(1, 15, 18), + new TimeOnly(1, 15, 18, 192, 021), + new TimeOnly(18 * HourMultiplier), + new TimeOnly(11 * HourMultiplier + 22 * MinuteMultiplier), + new TimeOnly(9 * HourMultiplier + 22 * MinuteMultiplier + 46 * SecondMultiplier), + new TimeOnly(3 * HourMultiplier + 22 * MinuteMultiplier + 46 * SecondMultiplier + 7848942), + TimeOnly.MinValue, TimeOnly.MaxValue + }; + + private readonly HashSet allowedTargetTypes = new() { + // strict conversions + typeof(int), + typeof(uint), + typeof(long), + typeof(ulong), + typeof(decimal), + typeof(DateTime), + typeof(TimeSpan), + typeof(string), + // rough conversions + typeof(float), + typeof(double), + }; + + /// + protected override TimeOnly[] Constants => constants; + + /// + protected override HashSet AllowedTargetTypes => allowedTargetTypes; + } +} diff --git a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/TimeSpanConverterTest.cs b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/TimeSpanConverterTest.cs index fa8f8ce847..9e702ef987 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/TimeSpanConverterTest.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/TimeSpanConverterTest.cs @@ -1,63 +1,51 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Elena Vakhtina // Created: 2008.11.12 using System; -using System.Globalization; +using System.Collections.Generic; using NUnit.Framework; -using Xtensive.Orm.Tests; namespace Xtensive.Orm.Tests.Core.Conversion { - [TestFixture] - public class TimeSpanConverterTest : ConverterTestBase + public class TimeSpanConverterTest : ConverterTestBase { - private readonly TimeSpan[] constants = { new TimeSpan( 1 ), - new TimeSpan( 10, 20, 30, 40, 50 ), - new TimeSpan( 1111, 2222, 3333, 4444, 5555 ), - TimeSpan.FromDays( 20.84745602 ), - new TimeSpan(0x7FFFFFFF), new TimeSpan(223372036854714932), - new TimeSpan(0xFFFF), new TimeSpan(3155378975999999999), - TimeSpan.MinValue, TimeSpan.MaxValue}; - private const int iterationCount = 100; + private readonly TimeSpan[] constants = new TimeSpan[] { new TimeSpan(1), + new TimeSpan(10, 20, 30, 40, 50), + new TimeSpan(1111, 2222, 3333, 4444, 5555), + TimeSpan.FromDays(20.84745602), + new TimeSpan(0x7FFFFFFF), new TimeSpan(223372036854714932), + new TimeSpan(0xFFFF), new TimeSpan(3155378975999999999), + TimeSpan.MinValue, TimeSpan.MaxValue + }; + private readonly HashSet allowedTargetTypes = new HashSet { + // strict conversions + typeof(byte), + typeof(sbyte), + typeof(short), + typeof(ushort), + typeof(int), + typeof(uint), + typeof(long), + typeof(ulong), + typeof(decimal), + typeof(TimeOnly), + typeof(TimeSpan), + typeof(string), + // rough coversions + typeof(float), + typeof(double), + typeof(DateOnly), + typeof(DateTimeOffset) + }; + + /// + protected override TimeSpan[] Constants => constants; + + /// + protected override HashSet AllowedTargetTypes => allowedTargetTypes; - [Test] - public void CombinedTest() - { - foreach (TimeSpan constant in constants) - OneValueTest(constant, iterationCount); - foreach (TimeSpan constant in constants) - OneValueTest(constant, iterationCount); - foreach (TimeSpan constant in constants) - OneValueTest(constant, iterationCount); - foreach (TimeSpan constant in constants) - OneValueTest(constant, iterationCount); - foreach (TimeSpan constant in constants) - OneValueTest(constant, iterationCount); - foreach (TimeSpan constant in constants) - OneValueTest(constant, iterationCount); - foreach (TimeSpan constant in constants) - OneValueTest(constant, iterationCount); - foreach (TimeSpan constant in constants) - OneValueTest(constant, iterationCount); - foreach (TimeSpan constant in constants) - OneValueTest(constant, iterationCount); - foreach (TimeSpan constant in constants) - OneValueTest(constant, iterationCount); - foreach (TimeSpan constant in constants) - OneValueTest(constant, iterationCount); - foreach (TimeSpan constant in constants) - OneValueTest(constant, iterationCount); - foreach (TimeSpan constant in constants) - OneValueTest(constant, iterationCount); - foreach (TimeSpan constant in constants) - OneValueTest(constant, iterationCount); - foreach (TimeSpan constant in constants) - OneValueTest(constant, iterationCount); - foreach (TimeSpan constant in constants) - OneValueTest(constant, iterationCount); - } } } diff --git a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/UInt16ConverterTest.cs b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/UInt16ConverterTest.cs index 9a10e2af4c..a02d938d8f 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/UInt16ConverterTest.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/UInt16ConverterTest.cs @@ -1,57 +1,42 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.25 using System; +using System.Collections.Generic; using NUnit.Framework; -using Xtensive.Conversion; -using Xtensive.Reflection; namespace Xtensive.Orm.Tests.Core.Conversion { - [TestFixture] - public class UInt16ConverterTest : ConverterTestBase + public class UInt16ConverterTest : ConverterTestBase { - private readonly ushort[] constants = { 0, 1, 123, 0x7F, 0xFF, 0xFFFF, 0x7FFF }; - private const int iterationCount = 100; + private readonly ushort[] constants = new ushort[] { 0, 1, 123, 0x7F, 0xFF, 0xFFFF, 0x7FFF }; + private readonly HashSet allowedTargetTypes = new() { + // strict conversions + typeof(byte), + typeof(sbyte), + typeof(short), + typeof(int), + typeof(uint), + typeof(long), + typeof(ulong), + typeof(float), + typeof(double), + typeof(decimal), + typeof(DateTime), + typeof(TimeSpan), + typeof(string), + typeof(char), + // rough coversions + typeof(bool) + }; - [Test] - public void CombinedTest() - { - foreach (ushort constant in constants) - OneValueTest(constant, iterationCount); - foreach (ushort constant in constants) - OneValueTest(constant, iterationCount); - foreach (ushort constant in constants) - OneValueTest(constant, iterationCount); - foreach (ushort constant in constants) - OneValueTest(constant, iterationCount); - foreach (ushort constant in constants) - OneValueTest(constant, iterationCount); - foreach (ushort constant in constants) - OneValueTest(constant, iterationCount); - foreach (ushort constant in constants) - OneValueTest(constant, iterationCount); - foreach (ushort constant in constants) - OneValueTest(constant, iterationCount); - foreach (ushort constant in constants) - OneValueTest(constant, iterationCount); - foreach (ushort constant in constants) - OneValueTest(constant, iterationCount); - foreach (ushort constant in constants) - OneValueTest(constant, iterationCount); - foreach (ushort constant in constants) - OneValueTest(constant, iterationCount); - foreach (ushort constant in constants) - OneValueTest(constant, iterationCount); - foreach (ushort constant in constants) - OneValueTest(constant, iterationCount); - foreach (ushort constant in constants) - OneValueTest(constant, iterationCount); - foreach (ushort constant in constants) - OneValueTest(constant, iterationCount); - } + /// + protected override ushort[] Constants => constants; + + /// + protected override HashSet AllowedTargetTypes => allowedTargetTypes; } } diff --git a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/UInt32converterTest.cs b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/UInt32converterTest.cs index 7573abf531..521ce497a9 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/UInt32converterTest.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/UInt32converterTest.cs @@ -1,57 +1,43 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.25 using System; +using System.Collections.Generic; using NUnit.Framework; -using Xtensive.Conversion; -using Xtensive.Reflection; namespace Xtensive.Orm.Tests.Core.Conversion { - [TestFixture] - public class UInt32ConverterTest : ConverterTestBase + public class UInt32ConverterTest : ConverterTestBase { private readonly uint[] constants = { 0, 1, 123, 0x7F, 0xFF, 0x7FFFFFFF, 0xFFFF, 0x7FFF, 0xFFFFFFFF }; - private const int iterationCount = 100; + private readonly HashSet allowedTargetTypes = new() { + // strict conversions + typeof(byte), + typeof(sbyte), + typeof(short), + typeof(ushort), + typeof(int), + typeof(long), + typeof(ulong), + typeof(double), + typeof(decimal), + typeof(DateTime), + typeof(DateOnly), + typeof(TimeSpan), + typeof(string), + typeof(char), + // rough coversions + typeof(bool), + typeof(float), + }; - [Test] - public void CombinedTest() - { - foreach (uint constant in constants) - OneValueTest(constant, iterationCount); - foreach (uint constant in constants) - OneValueTest(constant, iterationCount); - foreach (uint constant in constants) - OneValueTest(constant, iterationCount); - foreach (uint constant in constants) - OneValueTest(constant, iterationCount); - foreach (uint constant in constants) - OneValueTest(constant, iterationCount); - foreach (uint constant in constants) - OneValueTest(constant, iterationCount); - foreach (uint constant in constants) - OneValueTest(constant, iterationCount); - foreach (uint constant in constants) - OneValueTest(constant, iterationCount); - foreach (uint constant in constants) - OneValueTest(constant, iterationCount); - foreach (uint constant in constants) - OneValueTest(constant, iterationCount); - foreach (uint constant in constants) - OneValueTest(constant, iterationCount); - foreach (uint constant in constants) - OneValueTest(constant, iterationCount); - foreach (uint constant in constants) - OneValueTest(constant, iterationCount); - foreach (uint constant in constants) - OneValueTest(constant, iterationCount); - foreach (uint constant in constants) - OneValueTest(constant, iterationCount); - foreach (uint constant in constants) - OneValueTest(constant, iterationCount); - } + /// + protected override uint[] Constants => constants; + + /// + protected override HashSet AllowedTargetTypes => allowedTargetTypes; } } diff --git a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/UInt64ConverterTest.cs b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/UInt64ConverterTest.cs index c83e401999..3c5fb35612 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/UInt64ConverterTest.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Conversion/Internals/UInt64ConverterTest.cs @@ -1,60 +1,49 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.25 using System; +using System.Collections.Generic; using NUnit.Framework; -using Xtensive.Conversion; -using Xtensive.Reflection; namespace Xtensive.Orm.Tests.Core.Conversion { - [TestFixture] - public class UInt64ConverterTest : ConverterTestBase + public class UInt64ConverterTest : ConverterTestBase { - private readonly ulong[] constants = { + private readonly ulong[] constants = new ulong[] { 0x7FFFFFFFFFFF1234, 0, 123, 0x7F, 0xFF, 0x7FFFFFFF, 0x800000000000EDCC, 0xFFFF, 0x7FFF, 0xFFFFFFFF, 0xFFFFFFFFFFFFFF, 0xFFFFFFFFFFFF1234 }; - private const int iterationCount = 100; - [Test] - public void CombinedTest() - { - foreach (ulong constant in constants) - OneValueTest(constant, iterationCount); - foreach (ulong constant in constants) - OneValueTest(constant, iterationCount); - foreach (ulong constant in constants) - OneValueTest(constant, iterationCount); - foreach (ulong constant in constants) - OneValueTest(constant, iterationCount); - foreach (ulong constant in constants) - OneValueTest(constant, iterationCount); - foreach (ulong constant in constants) - OneValueTest(constant, iterationCount); - foreach (ulong constant in constants) - OneValueTest(constant, iterationCount); - foreach (ulong constant in constants) - OneValueTest(constant, iterationCount); - foreach (ulong constant in constants) - OneValueTest(constant, iterationCount); - foreach (ulong constant in constants) - OneValueTest(constant, iterationCount); - foreach (ulong constant in constants) - OneValueTest(constant, iterationCount); - foreach (ulong constant in constants) - OneValueTest(constant, iterationCount); - foreach (ulong constant in constants) - OneValueTest(constant, iterationCount); - foreach (ulong constant in constants) - OneValueTest(constant, iterationCount); - foreach (ulong constant in constants) - OneValueTest(constant, iterationCount); - foreach (ulong constant in constants) - OneValueTest(constant, iterationCount); - } + private readonly HashSet allowedTargetTypes = new() { + // strict conversions + typeof(byte), + typeof(sbyte), + typeof(short), + typeof(ushort), + typeof(int), + typeof(uint), + typeof(long), + typeof(decimal), + typeof(DateTime), + typeof(DateOnly), + typeof(TimeOnly), + typeof(TimeSpan), + typeof(string), + typeof(char), + // rough coversions + typeof(float), + typeof(double), + typeof(bool), + typeof(DateTimeOffset) + }; + + /// + protected override ulong[] Constants => constants; + + /// + protected override HashSet AllowedTargetTypes => allowedTargetTypes; } } diff --git a/Orm/Xtensive.Orm.Tests.Core/DotNetFramework/AllocationTest.cs b/Orm/Xtensive.Orm.Tests.Core/DotNetFramework/AllocationTest.cs index 423bf40805..94d8e87802 100644 --- a/Orm/Xtensive.Orm.Tests.Core/DotNetFramework/AllocationTest.cs +++ b/Orm/Xtensive.Orm.Tests.Core/DotNetFramework/AllocationTest.cs @@ -5,10 +5,7 @@ // Created: 2008.04.17 using System; -using System.Runtime.Serialization; using NUnit.Framework; -using Xtensive.Reflection; -using Xtensive.Orm.Tests; namespace Xtensive.Orm.Tests.Core.DotNetFramework { diff --git a/Orm/Xtensive.Orm.Tests.Core/Linq/ExpressionTestBase.cs b/Orm/Xtensive.Orm.Tests.Core/Linq/ExpressionTestBase.cs index fa4e6ed369..e3d37a21da 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Linq/ExpressionTestBase.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Linq/ExpressionTestBase.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Core.Linq { - [Serializable] public class ExpressionTestBase { public LambdaExpression[] Expressions { get; private set; } diff --git a/Orm/Xtensive.Orm.Tests.Core/Linq/SerializableExpressionsTest.cs b/Orm/Xtensive.Orm.Tests.Core/Linq/SerializableExpressionsTest.cs deleted file mode 100644 index e9ea57cea1..0000000000 --- a/Orm/Xtensive.Orm.Tests.Core/Linq/SerializableExpressionsTest.cs +++ /dev/null @@ -1,1034 +0,0 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. -// Created by: Denis Krjuchkov -// Created: 2009.05.13 - -using System; -using System.IO; -using System.Linq; -using System.Runtime.Serialization; -using System.Runtime.Serialization.Formatters.Binary; -using System.Runtime.Serialization.Formatters; -using NUnit.Framework; -using Xtensive.Core; -using Xtensive.Linq; -using Xtensive.Linq.SerializableExpressions; -using System.Collections.Generic; -using System.Linq.Expressions; -using Xtensive.Reflection; - -namespace Xtensive.Orm.Tests.Core.Linq -{ - [TestFixture] - public class SerializableExpressionsTest : ExpressionTestBase - { - #region Nested Types - [Serializable] - internal class Foo - { - public int IntField; - public int IntProperty { get; set; } - public List ListProperty { get; set; } - - public Foo() { } - } - - [Serializable] - internal class Address - { - public string City { get; set; } - public string ZipCode { get; set; } - - public Address() { } - - public Address(string city, string zipCode) - { - City = city; - ZipCode = zipCode; - } - } - - [Serializable] - internal class Person - { - public Address HomeAddress { get; set; } - public string Name { get; set; } - } - #endregion - - - public IEnumerable SerializableExpressionTypes - { - get { - yield return typeof(SerializableBinaryExpression); - yield return typeof(SerializableConditionalExpression); - yield return typeof(SerializableConstantExpression); - yield return typeof(SerializableDefaultExpression); - yield return typeof(SerializableElementInit); - yield return typeof(SerializableExpression); - yield return typeof(SerializableInvocationExpression); - yield return typeof(SerializableLambdaExpression); - yield return typeof(SerializableListInitExpression); - yield return typeof(SerializableMemberAssignment); - yield return typeof(SerializableMemberBinding); - yield return typeof(SerializableMemberExpression); - yield return typeof(SerializableMemberInitExpression); - yield return typeof(SerializableMemberListBinding); - yield return typeof(SerializableMemberMemberBinding); - yield return typeof(SerializableMethodCallExpression); - yield return typeof(SerializableNewArrayExpression); - yield return typeof(SerializableNewExpression); - yield return typeof(SerializableParameterExpression); - yield return typeof(SerializableTypeBinaryExpression); - yield return typeof(SerializableUnaryExpression); - } - } - - #region Test Data - - public ConstantExpression[] ConstantExpressions { get; private set; } - public DefaultExpression[] DefaultExpressions { get; private set; } - public ParameterExpression[] ParameterExpressions { get; private set; } - public ParameterExpression[] VariableExpressions { get; private set; } - public BinaryExpression[] BinaryExpressions { get; private set; } - public ConditionalExpression[] ConditionalExpressions { get; private set; } - public InvocationExpression[] InvocationExpressions { get; private set; } - public ListInitExpression[] ListInitExpressions { get; private set; } - public MemberExpression[] MemberExpressions { get; private set; } - public MemberInitExpression[] MemberInitExpressions { get; private set; } - public MethodCallExpression[] MethodCallExpressions { get; private set; } - public NewArrayExpression[] NewArrayExpressions { get; private set; } - public TypeBinaryExpression[] TypeBinaryExpressions { get; private set; } - public UnaryExpression[] UnaryExpressions { get; private set; } - public NewExpression[] NewExpressions { get; private set; } - - #endregion - - public override void TestFixtureSetUp() - { - base.TestFixtureSetUp(); - ConstantExpressions = GetTestConstantExpressions(); - DefaultExpressions = GetTestDefaultExpressions(); - ParameterExpressions = GetTestParameterExpressions(); - VariableExpressions = GetTestVariableExpressions(); - BinaryExpressions = GetTestBinaryExpressions(); - ConditionalExpressions = GetTestConditionalExpressions(); - InvocationExpressions = GetTestInvocationExpressions(); - ListInitExpressions = GetTestListInitExpressions(); - MemberExpressions = GetTestMemberExpressions(); - NewExpressions = GetTestNewExpressions(); - MemberInitExpressions = GetTestMemberInitExressions(); - MethodCallExpressions = GetTestMethodCallExpressions(); - NewArrayExpressions = GetTestNewArrayExpressions(); - TypeBinaryExpressions = GetTestTypeBinaryExpressions(); - UnaryExpressions = GetTestUnaryExpressions(); - } - - - [Test] - public void ConstantExpressionTest() - { - foreach(var origin in ConstantExpressions) { - Console.WriteLine(origin.ToString(true)); - var converted = origin.ToSerializableExpression().ToExpression(); - Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); - Console.WriteLine("OK"); - } - } - - [Test] - public void ConstantExpressionBinaryCloneTest() - { - RunSerializeTest(new BinaryFormatter(), ConstantExpressions); - } - - [Test] - public void ConstantExpressionNonBinaryCloneTest() - { - var list = SerializableExpressionTypes.ToList(); - var settings = new DataContractSerializerSettings { - KnownTypes = list.Union(new[] { typeof(int[]), typeof(string[]) }), - PreserveObjectReferences = true - }; - RunSerializeTest(new DataContractSerializer(typeof(SerializableExpression), settings), ConstantExpressions); - } - - - [Test] - public void DefaultExpressionTest() - { - foreach (var origin in DefaultExpressions) { - Console.WriteLine(origin.ToString(true)); - var converted = origin.ToSerializableExpression().ToExpression(); - Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); - Console.WriteLine("OK"); - } - } - - [Test] - public void DefaultExpressionBinaryCloneTest() - { - RunSerializeTest(new BinaryFormatter(), DefaultExpressions); - } - - [Test] - public void DefaultExpressionNonBinaryCloneTest() - { - var list = SerializableExpressionTypes.ToList(); - var settings = new DataContractSerializerSettings { - KnownTypes = list, - PreserveObjectReferences = true - }; - RunSerializeTest(new DataContractSerializer(typeof(SerializableExpression), settings), DefaultExpressions); - } - - [Test] - public void ParameterExpressionTest() - { - foreach (var origin in ParameterExpressions) { - Console.WriteLine(origin.ToString(true)); - var converted = origin.ToSerializableExpression().ToExpression(); - Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); - Console.WriteLine("OK"); - } - - foreach (var origin in VariableExpressions) { - Console.WriteLine(origin.ToString(true)); - var converted = origin.ToSerializableExpression().ToExpression(); - Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); - Console.WriteLine("OK"); - } - } - - [Test] - public void ParameterExpressionBinaryCloneTest() - { - RunSerializeTest(new BinaryFormatter(), ParameterExpressions); - RunSerializeTest(new BinaryFormatter(), VariableExpressions); - } - - [Test] - public void ParameterExpressionNonBinaryCloneTest() - { - var list = SerializableExpressionTypes.ToList(); - var settings = new DataContractSerializerSettings { - KnownTypes = list, - PreserveObjectReferences = true - }; - RunSerializeTest(new DataContractSerializer(typeof(SerializableExpression), settings), ParameterExpressions); - RunSerializeTest(new DataContractSerializer(typeof(SerializableExpression), settings), VariableExpressions); - } - - [Test] - public void BinaryExpressionTest() - { - foreach (var origin in BinaryExpressions) { - Console.WriteLine(origin.ToString(true)); - var converted = origin.ToSerializableExpression().ToExpression(); - Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); - Console.WriteLine("OK"); - } - } - - [Test] - public void BinaryExpressionBinaryCloneTest() - { - RunSerializeTest(new BinaryFormatter(), BinaryExpressions); - } - - [Test] - public void BinaryExpressionNonBinaryCloneTest() - { - var list = SerializableExpressionTypes.ToList(); - var settings = new DataContractSerializerSettings { - KnownTypes = list.Union(new[] { typeof(int[]) }), - PreserveObjectReferences = true - }; - RunSerializeTest(new DataContractSerializer(typeof(SerializableExpression), settings), BinaryExpressions); - } - - [Test] - public void ConditionalExpressionTest() - { - foreach (var origin in ConditionalExpressions) { - Console.WriteLine(origin.ToString(true)); - var converted = origin.ToSerializableExpression().ToExpression(); - Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); - Console.WriteLine("OK"); - } - } - - [Test] - public void ConditionalExpressionBinaryCloneTest() - { - RunSerializeTest(new BinaryFormatter(), ConditionalExpressions); - } - - [Test] - public void ConditionalExpressionNonBinaryCloneTest() - { - var list = SerializableExpressionTypes.ToList(); - var settings = new DataContractSerializerSettings { - KnownTypes = list, - PreserveObjectReferences = true - }; - RunSerializeTest(new DataContractSerializer(typeof(SerializableExpression), settings), ConditionalExpressions); - } - - [Test] - public void ListInitExpressionTest() - { - foreach (var origin in ListInitExpressions) { - Console.WriteLine(origin.ToString(true)); - var converted = origin.ToSerializableExpression().ToExpression(); - Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); - Console.WriteLine("OK"); - } - } - - [Test] - public void ListInitExpressionBinaryCloneTest() - { - RunSerializeTest(new BinaryFormatter(), ListInitExpressions); - } - - [Test] - public void ListInitExpressionNonBinaryCloneTest() - { - var list = SerializableExpressionTypes.ToList(); - var settings = new DataContractSerializerSettings { - KnownTypes = list, - PreserveObjectReferences = true - }; - RunSerializeTest(new DataContractSerializer(typeof(SerializableExpression), settings), ListInitExpressions); - } - - [Test] - public void MemberExpressionTest() - { - foreach (var origin in MemberExpressions) { - Console.WriteLine(origin.ToString(true)); - var converted = origin.ToSerializableExpression().ToExpression(); - Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); - Console.WriteLine("OK"); - } - } - - [Test] - public void MemberExpressionBinaryCloneTest() - { - RunSerializeTest(new BinaryFormatter(), MemberExpressions); - } - - [Test] - public void MemberExpressionNonBinaryCloneTest() - { - var list = SerializableExpressionTypes.ToList(); - var settings = new DataContractSerializerSettings { - KnownTypes = list.Union(new[] { typeof(Foo) }), - PreserveObjectReferences = true - }; - RunSerializeTest(new DataContractSerializer(typeof(SerializableExpression), settings), MemberExpressions); - } - - [Test] - public void NewExpressionTest() - { - foreach (var origin in NewExpressions) { - Console.WriteLine(origin.ToString(true)); - var converted = origin.ToSerializableExpression().ToExpression(); - Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); - Console.WriteLine("OK"); - } - } - - [Test] - public void NewExpressionBinaryCloneTest() - { - RunSerializeTest(new BinaryFormatter(), NewExpressions); - } - - [Test] - public void NewExpressionNonBinaryCloneTest() - { - var list = SerializableExpressionTypes.ToList(); - var settings = new DataContractSerializerSettings { - KnownTypes = list, - PreserveObjectReferences = true - }; - RunSerializeTest(new DataContractSerializer(typeof(SerializableExpression), settings), NewExpressions); - } - - [Test] - public void MemberInitExpressionTest() - { - foreach (var origin in MemberInitExpressions) { - Console.WriteLine(origin.ToString(true)); - var converted = origin.ToSerializableExpression().ToExpression(); - Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); - Console.WriteLine("OK"); - } - } - - [Test] - public void MemberInitExpressionBinaryCloneTest() - { - RunSerializeTest(new BinaryFormatter(), MemberInitExpressions); - } - - [Test] - public void MemberInitExpressionNonBinaryCloneTest() - { - var list = SerializableExpressionTypes.ToList(); - var settings = new DataContractSerializerSettings { - KnownTypes = list, - PreserveObjectReferences = true - }; - RunSerializeTest(new DataContractSerializer(typeof(SerializableExpression), settings), MemberInitExpressions); - } - - [Test] - public void MethodCallExpressionTest() - { - foreach (var origin in MethodCallExpressions) { - Console.WriteLine(origin.ToString(true)); - var converted = origin.ToSerializableExpression().ToExpression(); - Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); - Console.WriteLine("OK"); - } - } - - [Test] - public void MethodCallExpressionBinaryCloneTest() - { - RunSerializeTest(new BinaryFormatter(), MethodCallExpressions); - } - - [Test] - public void MethodCallExpressionNonBinaryCloneTest() - { - var list = SerializableExpressionTypes.ToList(); - var settings = new DataContractSerializerSettings { - KnownTypes = list.Union(new[] { typeof(int[]) }), - PreserveObjectReferences = true - }; - RunSerializeTest(new DataContractSerializer(typeof(SerializableExpression), settings), MethodCallExpressions); - } - - [Test] - public void NewArrayExpressionTest() { - foreach (var origin in NewArrayExpressions) { - Console.WriteLine(origin.ToString(true)); - var converted = origin.ToSerializableExpression().ToExpression(); - Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); - Console.WriteLine("OK"); - } - } - - [Test] - public void NewArrayExpressionBinaryCloneTest() - { - RunSerializeTest(new BinaryFormatter(), NewArrayExpressions); - } - - [Test] - public void NewArrayExpressionNonBinaryCloneTest() - { - var list = SerializableExpressionTypes.ToList(); - var settings = new DataContractSerializerSettings { - KnownTypes = list, - PreserveObjectReferences = true - }; - RunSerializeTest(new DataContractSerializer(typeof(SerializableExpression), settings), NewArrayExpressions); - } - - [Test] - public void TypeBinaryExpressionTest() { - foreach (var origin in TypeBinaryExpressions) { - Console.WriteLine(origin.ToString(true)); - var converted = origin.ToSerializableExpression().ToExpression(); - Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); - Console.WriteLine("OK"); - } - } - - [Test] - public void TypeBinaryExpressionBinaryCloneTest() - { - RunSerializeTest(new BinaryFormatter(), TypeBinaryExpressions); - } - - [Test] - public void TypeBinaryExpressionNonBinaryCloneTest() - { - var list = SerializableExpressionTypes.ToList(); - var settings = new DataContractSerializerSettings { - KnownTypes = list, - PreserveObjectReferences = true - }; - RunSerializeTest(new DataContractSerializer(typeof(SerializableExpression), settings), TypeBinaryExpressions); - } - - [Test] - public void UnaryExpressionsTest() - { - foreach (var origin in UnaryExpressions) { - Console.WriteLine(origin.ToString(true)); - var converted = origin.ToSerializableExpression().ToExpression(); - Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); - Console.WriteLine("OK"); - } - } - - [Test] - public void UnaryExpressionBinaryCloneTest() - { - RunSerializeTest(new BinaryFormatter(), UnaryExpressions); - } - - [Test] - public void UnaryExpressionNonBinaryCloneTest() - { - var list = SerializableExpressionTypes.ToList(); - var settings = new DataContractSerializerSettings { - KnownTypes = list.Union(new[] { typeof(int[]) }), - PreserveObjectReferences = true - }; - RunSerializeTest(new DataContractSerializer(typeof(SerializableExpression), settings), UnaryExpressions); - } - - [Test] - public void InvocationExpressionTest() - { - foreach (var origin in InvocationExpressions) { - Console.WriteLine(origin.ToString(true)); - var converted = origin.ToSerializableExpression().ToExpression(); - Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); - Console.WriteLine("OK"); - } - } - - [Test] - public void InvocationExpressionBinaryCloneTest() - { - RunSerializeTest(new BinaryFormatter(), InvocationExpressions); - } - - [Test] - public void InvocationExpressionNonBinaryCloneTest() - { - var list = SerializableExpressionTypes.ToList(); - var settings = new DataContractSerializerSettings { - KnownTypes = list, - PreserveObjectReferences = true - }; - RunSerializeTest(new DataContractSerializer(typeof(SerializableExpression), settings), InvocationExpressions); - } - - [Test] - public void LambdaExpressionTest() - { - foreach (var origin in Expressions) { - Console.WriteLine(origin.ToString(true)); - var converted = origin.ToSerializableExpression().ToExpression(); - Assert.That(converted.ToExpressionTree(), Is.EqualTo(origin.ToExpressionTree())); - Console.WriteLine("OK"); - } - } - - [Test] - public void LambdaExpressionBinaryCloneTest() - { - RunSerializeTest(new BinaryFormatter(), Expressions); - } - - [Test] - public void LambdaExpressionNonBinaryCloneTest() - { - var list = SerializableExpressionTypes.ToList(); - var settings = new DataContractSerializerSettings { - KnownTypes = list, - PreserveObjectReferences = true - }; - RunSerializeTest(new DataContractSerializer(typeof(SerializableExpression), settings), Expressions); - } - - private void RunSerializeTest(XmlObjectSerializer serializer, IEnumerable expressions) - { - using (var stream = new MemoryStream()) { - foreach (var expression in expressions) { - Console.WriteLine(expression.ToString(true)); - serializer.WriteObject(stream, expression.ToSerializableExpression()); - _ = stream.Seek(0, SeekOrigin.Begin); - var serialized = (SerializableExpression) serializer.ReadObject(stream); - stream.SetLength(0); - CompareExpressions(expression, serialized.ToExpression()); - Console.WriteLine("OK"); - } - } - } - - private void RunSerializeTest(IFormatter serializer, IEnumerable expressions) - { - using (var stream = new MemoryStream()) { - foreach (var expression in expressions) { - Console.WriteLine(expression.ToString(true)); - serializer.Serialize(stream, expression.ToSerializableExpression()); - _ = stream.Seek(0, SeekOrigin.Begin); - var serialized = (SerializableExpression) serializer.Deserialize(stream); - stream.SetLength(0); - CompareExpressions(expression, serialized.ToExpression()); - Console.WriteLine("OK"); - } - } - } - - private void CompareExpressions(Expression expression, Expression serialized) - { - if (expression is ConstantExpression cExpressions) - CompareConstants(cExpressions, (ConstantExpression) serialized); - else if (expression is MemberExpression mExpression) - CompareMemberExpressions(mExpression, (MemberExpression) serialized); - else if (expression is BinaryExpression bExpression && bExpression.NodeType == ExpressionType.ArrayIndex) - CompareArrayIndex(bExpression, (BinaryExpression) serialized); - else if (expression is UnaryExpression uExpression && uExpression.NodeType == ExpressionType.ArrayLength) - CompareArrayLength(uExpression, (UnaryExpression) serialized); - else - Assert.That(serialized.ToExpressionTree(), Is.EqualTo(expression.ToExpressionTree())); - } - - private void CompareMemberExpressions(MemberExpression origin, MemberExpression clone) - { - Assert.That(clone.Type, Is.EqualTo(origin.Type)); - - var instanceOrig = origin.Expression as ConstantExpression; - var instanceClone = clone.Expression as ConstantExpression; - - Assert.That(instanceClone.Type, Is.EqualTo(instanceOrig.Type)); - - var instValueOrig = instanceOrig.Value as Foo; - var instValueClone = instanceClone.Value as Foo; - - Assert.That(instValueClone.IntField, Is.EqualTo(instValueOrig.IntField)); - Assert.That(instValueClone.IntProperty, Is.EqualTo(instValueOrig.IntProperty)); - - Assert.That(clone.Member, Is.EqualTo(origin.Member)); - } - - private void CompareArrayIndex(BinaryExpression origin, BinaryExpression clone) - { - if (origin.NodeType != ExpressionType.ArrayIndex) - throw new ArgumentException(); - - Assert.That(clone.Type, Is.EqualTo(origin.Type)); - - CompareConstants((ConstantExpression) origin.Left, (ConstantExpression) clone.Left); - CompareConstants((ConstantExpression) origin.Right, (ConstantExpression) clone.Right); - - } - - private void CompareArrayLength(UnaryExpression origin, UnaryExpression clone) - { - if (origin.NodeType != ExpressionType.ArrayLength) - throw new ArgumentException(); - - Assert.That(clone.Type, Is.EqualTo(origin.Type)); - - var instanceOrig = (origin.Operand as ConstantExpression); - var instanceClone = (clone.Operand as ConstantExpression); - - CompareConstants(instanceOrig, instanceClone); - } - - private void CompareConstants(ConstantExpression origin, ConstantExpression clone) - { - Assert.That(clone.Type, Is.EqualTo(origin.Type)); - - if (origin.Type.IsArray) { - Assert.That(origin.Value, Is.Not.Null); - Assert.That(clone.Value, Is.Not.Null); - Assert.That(clone.Value, Is.EquivalentTo(origin.Value as Array)); - } - else { - Assert.That(clone.Value, Is.EqualTo(origin.Value)); - } - } - - #region Performance test - - private const int warmUpOperationCount = 10; - private const int actualOperationCount = 10000; - - [Test] - [Category("Performance")] - [Explicit] - public void SerializeBenchmarkTest() - { - var list = SerializableExpressionTypes.ToList(); - var settings = new DataContractSerializerSettings(); - settings.KnownTypes = list; - settings.PreserveObjectReferences = true; - - RunSerializeBenchmark(new DataContractSerializer(typeof (SerializableExpression), settings), true); - RunSerializeBenchmark(new DataContractSerializer(typeof (SerializableExpression), settings), false); - } - - private void RunSerializeBenchmark(XmlObjectSerializer serializer, bool warmUp) - { - int operationCount = warmUp ? warmUpOperationCount : actualOperationCount; - using (var stream = new MemoryStream()) { - int operation = 0; - long length = 0; - using (CreateMeasurement(warmUp, serializer.GetType().Name, operationCount)) - while (operation < operationCount) { - foreach (var expression in Expressions) { - operation++; - if (operation > operationCount) - break; - serializer.WriteObject(stream, expression.ToSerializableExpression()); - length += stream.Position; - stream.Seek(0, SeekOrigin.Begin); - var serialized = (SerializableExpression) serializer.ReadObject(stream); - stream.SetLength(0); - } - } - // for (int i = 0; i < operationCount; i++) { - // serializer.Serialize(stream, Expressions[expressionIndex].ToSerializableExpression()); - // length += stream.Length; - // stream.SetLength(0); - // } - Console.Out.WriteLine($"Stream size: {length / 1024} Kb"); - } - } - - private static IDisposable CreateMeasurement(bool warmUp, string name, int operationCount) - { - return warmUp - ? new Measurement(name, MeasurementOptions.None, operationCount) - : new Measurement(name, operationCount); - } - - #endregion - - #region Test Data initializers - private ConstantExpression[] GetTestConstantExpressions() - { - return new ConstantExpression[] { - Expression.Constant(false, typeof(bool)), - Expression.Constant(true, typeof(bool)), - Expression.Constant((byte) 64, typeof(byte)), - Expression.Constant((sbyte) -64, typeof(sbyte)), - Expression.Constant((short) -128, typeof(short)), - Expression.Constant((ushort) 128, typeof(ushort)), - Expression.Constant((int) -256, typeof(int)), - Expression.Constant((uint) 256, typeof(uint)), - Expression.Constant((long) -512, typeof(long)), - Expression.Constant((ulong) 512, typeof(ulong)), - Expression.Constant((float) 6.283185307f, typeof(float)), - Expression.Constant((double) 6.283185307179586476925, typeof(double)), - Expression.Constant((decimal) 6.2895762354m, typeof(decimal)), - Expression.Constant(TimeSpan.FromSeconds(1024), typeof(TimeSpan)), - Expression.Constant(new DateTime(2018, 9, 27, 18, 55, 56), typeof(DateTime)), - Expression.Constant(null, typeof(string)), - Expression.Constant(string.Empty, typeof(string)), - Expression.Constant("DBC", typeof(string)), - Expression.Constant(new[] { 1, 2, 3 }), - Expression.Constant(new[] { "1", "2", "3" }) - }; - } - - private DefaultExpression[] GetTestDefaultExpressions() - { - return new[] { - Expression.Default(typeof(bool)), - Expression.Default(typeof(byte)), - Expression.Default(typeof(sbyte)), - Expression.Default(typeof(short)), - Expression.Default(typeof(ushort)), - Expression.Default(typeof(int)), - Expression.Default(typeof(uint)), - Expression.Default(typeof(long)), - Expression.Default(typeof(ulong)), - Expression.Default(typeof(float)), - Expression.Default(typeof(double)), - Expression.Default(typeof(decimal)), - Expression.Default(typeof(TimeSpan)), - Expression.Default(typeof(DateTime)), - Expression.Default(typeof(string)), - }; - } - - private ParameterExpression[] GetTestParameterExpressions() - { - return new[] { - Expression.Parameter(typeof(bool)), Expression.Parameter(typeof(bool), "boolP"), - Expression.Parameter(typeof(byte)), Expression.Parameter(typeof(byte), "byteP"), - Expression.Parameter(typeof(sbyte)), Expression.Parameter(typeof(sbyte), "sbyteP"), - Expression.Parameter(typeof(short)), Expression.Parameter(typeof(short), "shortP"), - Expression.Parameter(typeof(ushort)), Expression.Parameter(typeof(ushort), "ushortP"), - Expression.Parameter(typeof(int)), Expression.Parameter(typeof(int), "intP"), - Expression.Parameter(typeof(uint)), Expression.Parameter(typeof(uint), "uintP"), - Expression.Parameter(typeof(long)), Expression.Parameter(typeof(long), "longP"), - Expression.Parameter(typeof(ulong)), Expression.Parameter(typeof(ulong), "ulongP"), - Expression.Parameter(typeof(float)), Expression.Parameter(typeof(float), "floatP"), - Expression.Parameter(typeof(double)), Expression.Parameter(typeof(double), "doubleP"), - Expression.Parameter(typeof(decimal)), Expression.Parameter(typeof(decimal), "decimalP"), - Expression.Parameter(typeof(TimeSpan)), Expression.Parameter(typeof(TimeSpan), "timespanP"), - Expression.Parameter(typeof(DateTime)), Expression.Parameter(typeof(DateTime), "datetimeP"), - Expression.Parameter(typeof(string)), Expression.Parameter(typeof(string), "stringP"), - }; - } - - private ParameterExpression[] GetTestVariableExpressions() - { - return new[] { - Expression.Variable(typeof(bool)), Expression.Variable(typeof(bool), "boolP"), - Expression.Variable(typeof(byte)), Expression.Variable(typeof(byte), "byteP"), - Expression.Variable(typeof(sbyte)), Expression.Variable(typeof(sbyte), "sbyteP"), - Expression.Variable(typeof(short)), Expression.Variable(typeof(short), "shortP"), - Expression.Variable(typeof(ushort)), Expression.Variable(typeof(ushort), "ushortP"), - Expression.Variable(typeof(int)), Expression.Variable(typeof(int), "intP"), - Expression.Variable(typeof(uint)), Expression.Variable(typeof(uint), "uintP"), - Expression.Variable(typeof(long)), Expression.Variable(typeof(long), "longP"), - Expression.Variable(typeof(ulong)), Expression.Variable(typeof(ulong), "ulongP"), - Expression.Variable(typeof(float)), Expression.Variable(typeof(float), "floatP"), - Expression.Variable(typeof(double)), Expression.Variable(typeof(double), "doubleP"), - Expression.Variable(typeof(decimal)), Expression.Variable(typeof(decimal), "decimalP"), - Expression.Variable(typeof(TimeSpan)), Expression.Variable(typeof(TimeSpan), "timespanP"), - Expression.Variable(typeof(DateTime)), Expression.Variable(typeof(DateTime), "datetimeP"), - Expression.Variable(typeof(string)), Expression.Variable(typeof(string), "stringP"), - }; - } - - private BinaryExpression[] GetTestBinaryExpressions() - { - return new[] { - //Expression.Add(Expression.Constant(1), Expression.Constant(2)), - //Expression.AddChecked(Expression.Constant(2), Expression.Constant(3)), - //Expression.Subtract(Expression.Constant(4), Expression.Constant(2)), - //Expression.SubtractChecked(Expression.Constant(5), Expression.Constant(6)), - //Expression.Divide(Expression.Constant(2), Expression.Constant(1)), - //Expression.Multiply(Expression.Constant(3), Expression.Constant(5)), - //Expression.MultiplyChecked(Expression.Constant(4), Expression.Constant(4)), - //Expression.Modulo(Expression.Constant(5), Expression.Constant(2)), - Expression.Power(Expression.Constant(2.0), Expression.Constant(4.0)), - - Expression.And(Expression.Constant(10), Expression.Constant(6)), - Expression.Or(Expression.Constant(10), Expression.Constant(6)), - Expression.ExclusiveOr(Expression.Constant(10), Expression.Constant(6)), - Expression.LeftShift(Expression.Constant(256), Expression.Constant(2)), - Expression.RightShift(Expression.Constant(256), Expression.Constant(2)), - - Expression.Equal(Expression.Constant(256), Expression.Constant(2)), - Expression.NotEqual(Expression.Constant(256), Expression.Constant(2)), - Expression.GreaterThan(Expression.Constant(256), Expression.Constant(2)), - Expression.GreaterThanOrEqual(Expression.Constant(256), Expression.Constant(2)), - Expression.LessThan(Expression.Constant(256), Expression.Constant(2)), - Expression.LessThanOrEqual(Expression.Constant(256), Expression.Constant(2)), - - Expression.AndAlso(Expression.Equal(Expression.Constant(256), Expression.Constant(2)), Expression.NotEqual(Expression.Constant(256), Expression.Constant(3))), - Expression.OrElse(Expression.Equal(Expression.Constant(256), Expression.Constant(2)), Expression.NotEqual(Expression.Constant(256), Expression.Constant(3))), - - Expression.Assign(Expression.Variable(typeof(int), "addAssignVar"), Expression.Constant(111)), - - Expression.Coalesce(Expression.Constant("abc"), Expression.Constant("default")), - Expression.ArrayIndex(Expression.Constant( new[] { 2, 8, 7 }), Expression.Constant(2)) - }; - } - - private ConditionalExpression[] GetTestConditionalExpressions() - { - return new[] { - Expression.Condition( - Expression.Equal(Expression.Constant(12), Expression.Constant(12)), - Expression.Constant(111), - Expression.Constant(222)), - Expression.IfThen( - Expression.Equal(Expression.Constant(13), Expression.Constant(13)), - Expression.Constant(333)), - Expression.IfThenElse( - Expression.Equal(Expression.Constant(14), Expression.Constant(14)), - Expression.Constant(222), - Expression.Constant(444)) - }; - } - - private InvocationExpression[] GetTestInvocationExpressions() - { - Expression> largeSumTest = (num1, num2) => (num1 + num2) > 1000; - return new[] { - Expression.Invoke( - largeSumTest, - Expression.Constant(539), - Expression.Constant(281)) - }; - } - - private ListInitExpression[] GetTestListInitExpressions() - { - var listType = typeof(List); - var constructor = listType.GetConstructor(Type.EmptyTypes); - var newListExpression = Expression.New(constructor); - var addMethod = listType.GetMethod("Add"); - return new[] { - Expression.ListInit( - newListExpression, - Expression.ElementInit(addMethod, Expression.Constant("Apple", typeof(string))), - Expression.ElementInit(addMethod, Expression.Constant("Banana", typeof(string))), - Expression.ElementInit(addMethod, Expression.Constant("Cherry", typeof(string))) - ) - }; - } - - private MemberExpression[] GetTestMemberExpressions() - { - var fooType = typeof(Foo); - var prop = fooType.GetProperty(nameof(Foo.IntProperty)); - var field = fooType.GetField(nameof(Foo.IntField)); - - var instance = new Foo() { IntField = 123, IntProperty = 234 }; - - var instanceExp = Expression.Constant(instance); - - return new[] { - Expression.Field(instanceExp, nameof(Foo.IntField)), - Expression.Field(instanceExp, field), - Expression.Property(instanceExp, nameof(Foo.IntProperty)), - Expression.Property(instanceExp, prop), - }; - } - - private NewExpression[] GetTestNewExpressions() - { - var addressType = typeof(Address); - var addressCtor1 = addressType.GetConstructor(Type.EmptyTypes); - var addressCtor2 = addressType.GetConstructor(new Type[] { typeof(string), typeof(string) }); - - var cityProp = addressType.GetProperty("City"); - var zipCodeProp = addressType.GetProperty("ZipCode"); - - var dateTimeType = typeof(DateTime); - var dateTimeCtor1 = dateTimeType.GetConstructor(new[] { typeof(long) }); - var dateTimeCtor2 = dateTimeType.GetConstructor(new[] { typeof(int), typeof(int), typeof(int) }); - - return new[] { - Expression.New(addressCtor1), - Expression.New(addressCtor2, Expression.Constant("City"), Expression.Constant("ZipCode")), - Expression.New(dateTimeCtor1, Expression.Constant(1224585425L)), - Expression.New(dateTimeCtor2, Expression.Constant(21), Expression.Constant(24), Expression.Constant(26)) - }; - } - - private MemberInitExpression[] GetTestMemberInitExressions() - { - var listType = typeof(List); - var constructor = listType.GetConstructor(Type.EmptyTypes); - var newListExpression = Expression.New(constructor); - var addMethod = listType.GetMethod("Add"); - - var fooType = typeof(Foo); - var prop = fooType.GetProperty(nameof(Foo.IntProperty)); - var field = fooType.GetField(nameof(Foo.IntField)); - - var parameter = Expression.Parameter(typeof(int), "i"); - var newExpression1 = Expression.New(fooType); - var binding = Expression.Bind(prop, parameter); - - var init1 = Expression.ElementInit(addMethod, Expression.Constant("Hello")); - var init2 = Expression.ElementInit(addMethod, Expression.Constant("World")); - - var messagesProperty = fooType.GetProperty(nameof(Foo.ListProperty)); - MemberListBinding listBinding = Expression.ListBind(messagesProperty, init1, init2); - NewExpression newExpression2 = Expression.New(fooType); - - var personType = typeof(Person); - var addressType = typeof(Address); - - var homeAddressMember = personType.GetProperty(nameof(Person.HomeAddress)); - var nameMember = personType.GetProperty(nameof(Person.Name)); - var cityMember = addressType.GetProperty(nameof(Address.City)); - var zipCodeMember = addressType.GetProperty(nameof(Address.ZipCode)); - - var cityAssignment = Expression.Bind(cityMember, Expression.Constant("New York")); - var zipCodeAssignment = Expression.Bind(zipCodeMember, Expression.Constant("10001")); - - var addressBinding = Expression.MemberBind(homeAddressMember, cityAssignment, zipCodeAssignment); - var nameAssignment = Expression.Bind(nameMember, Expression.Constant("John Doe")); - - var newPerson = Expression.New(personType); - - return new[] { - Expression.MemberInit(newExpression1, new[] { binding }), - Expression.MemberInit(newExpression2, new MemberBinding[] { listBinding }), - Expression.MemberInit(newPerson, addressBinding, nameAssignment) - }; - } - - private MethodCallExpression[] GetTestMethodCallExpressions() - { - var param1 = Expression.Constant(2, typeof(int)); - var param2 = Expression.Constant(3L, typeof(long)); - var thisType = this.GetType(); - - var nonpublicMethods = thisType.GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); - var publicMethods = thisType.GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); - - var staticLocalMethod = nonpublicMethods - .FirstOrDefault(m => m.Name.StartsWith($"<{nameof(GetTestMethodCallExpressions)}>g__{nameof(SDummyMethod)}")); - - var publicStaticMethod = publicMethods - .FirstOrDefault(m => m.Name.StartsWith($"{nameof(SFromCloneMethodCallExpressionDummy)}")); - - var privateStaticMethod = nonpublicMethods - .FirstOrDefault(m => m.Name.StartsWith($"{nameof(PSFromCloneMethodCallExpressionDummy)}")); - - return new[] { - Expression.Call(publicStaticMethod, param1, param2), - Expression.Call(privateStaticMethod, param1, param2), - Expression.Call(staticLocalMethod, param1, param2), - }; - - static void SDummyMethod(int a, long b) - { } - } - - private NewArrayExpression[] GetTestNewArrayExpressions() - { - return new[] { - Expression.NewArrayBounds(typeof(string), Expression.Constant(1)), - Expression.NewArrayBounds(typeof(string), Expression.Constant(2), Expression.Constant(3)), - Expression.NewArrayInit(typeof(string), Expression.Constant("ABC"), Expression.Constant("DEF")), - }; - } - - private TypeBinaryExpression[] GetTestTypeBinaryExpressions() - { - return new[] { - Expression.TypeIs(Expression.Constant(DateTime.UtcNow), typeof(DateTime)), - Expression.TypeEqual(Expression.Constant(DateTime.UtcNow), typeof(DateTime)) - }; - } - - private UnaryExpression[] GetTestUnaryExpressions() - { - return new[] { - Expression.ArrayLength(Expression.Constant(new int[] { 1,2,3 })), - Expression.Convert(Expression.Constant(23), typeof(long)), - Expression.ConvertChecked(Expression.Constant(23), typeof(long)), - Expression.Decrement(Expression.Constant(24)), - Expression.Increment(Expression.Constant(25)), - Expression.IsFalse(Expression.Constant(true)), - Expression.IsTrue(Expression.Constant(true)), - Expression.Negate(Expression.Constant(-25)), - Expression.NegateChecked(Expression.Constant(-25)), - Expression.Not(Expression.Constant(true)), - Expression.OnesComplement(Expression.Constant(123)), - }; - } - - public static void SFromCloneMethodCallExpressionDummy(int a, long b) { } - private static void PSFromCloneMethodCallExpressionDummy(int a, long b) { } - } - #endregion -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Database.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Database.cs index 435b0edc1f..1513360d63 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Database.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Database.cs @@ -10,7 +10,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.DatabaseModel { - [Serializable] public sealed class Database : NodeBase { private User owner; diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/DatabaseCollection.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/DatabaseCollection.cs index 1d5d328e7c..5797700179 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/DatabaseCollection.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/DatabaseCollection.cs @@ -10,7 +10,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.DatabaseModel { - [Serializable] public sealed class DatabaseCollection : NodeCollectionBase, IUnorderedNodeCollection { diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Index.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Index.cs index 84452cc475..a6c34f76d3 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Index.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Index.cs @@ -10,7 +10,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.DatabaseModel { - [Serializable] public abstract class Index : NodeBase { private bool isPrimary; diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/IndexCollection.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/IndexCollection.cs index a2052e80d7..d64747059e 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/IndexCollection.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/IndexCollection.cs @@ -10,7 +10,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.DatabaseModel { - [Serializable] public sealed class SecondaryIndexCollection : NodeCollectionBase, IUnorderedNodeCollection { diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/NodeBase.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/NodeBase.cs index 48eb02d0b9..10f24d7aae 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/NodeBase.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/NodeBase.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.DatabaseModel { - [Serializable] public abstract class NodeBase : Node where TParent : Node { diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/NodeCollectionBase.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/NodeCollectionBase.cs index 3d8839313f..6d5e8d4ac9 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/NodeCollectionBase.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/NodeCollectionBase.cs @@ -9,7 +9,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.DatabaseModel { - [Serializable] public class NodeCollectionBase : NodeCollection where TNode : Node where TParent : Node diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/PrimaryIndex.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/PrimaryIndex.cs index 75c205e02d..bb18b3e453 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/PrimaryIndex.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/PrimaryIndex.cs @@ -10,7 +10,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.DatabaseModel { - [Serializable] public sealed class PrimaryIndex : Index { protected override Nesting CreateNesting() diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Ref.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Ref.cs index 1eee59cc92..89a1d444e1 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Ref.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Ref.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.DatabaseModel { - [Serializable] public abstract class Ref : NodeBase, INodeReference where TTarget : Node diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Role.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Role.cs index f004264e18..15a7176693 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Role.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Role.cs @@ -9,7 +9,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.DatabaseModel { - [Serializable] public sealed class Role : NodeBase { protected override Nesting CreateNesting() diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/RoleCollection.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/RoleCollection.cs index 0eecf9fa92..9a76ddd06f 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/RoleCollection.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/RoleCollection.cs @@ -10,7 +10,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.DatabaseModel { - [Serializable] public sealed class RoleCollection : NodeCollectionBase, IUnorderedNodeCollection { diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/RoleRef.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/RoleRef.cs index 427f86f72a..5c3e9bcdb1 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/RoleRef.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/RoleRef.cs @@ -10,7 +10,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.DatabaseModel { - [Serializable] public sealed class RoleRef : Ref, IUnnamedNode { diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/RoleRefCollection.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/RoleRefCollection.cs index adda544c0f..34a8359596 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/RoleRefCollection.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/RoleRefCollection.cs @@ -10,7 +10,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.DatabaseModel { - [Serializable] public sealed class RoleRefCollection : NodeCollectionBase, IUnorderedNodeCollection { diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Schema.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Schema.cs index 5a8dd1c827..743675b0fe 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Schema.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Schema.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.DatabaseModel { - [Serializable] public sealed class Schema : NodeBase { [Property] diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/SchemaCollection.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/SchemaCollection.cs index 651a456b21..4984a8ed00 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/SchemaCollection.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/SchemaCollection.cs @@ -10,7 +10,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.DatabaseModel { - [Serializable] public sealed class SchemaCollection : NodeCollectionBase, IUnorderedNodeCollection { diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/SecondaryIndex.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/SecondaryIndex.cs index 51439de0cc..6d6d5c377a 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/SecondaryIndex.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/SecondaryIndex.cs @@ -10,7 +10,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.DatabaseModel { - [Serializable] public sealed class SecondaryIndex : Index { protected override Nesting CreateNesting() diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Security.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Security.cs index 77199376c9..8508f29532 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Security.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Security.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.DatabaseModel { - [Serializable] public sealed class Security : NodeBase { [Property(Priority = 100)] diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Server.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Server.cs index 0bafffe518..4258c5f2ba 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Server.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Server.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.DatabaseModel { - [Serializable] public sealed class Server : NodeBase, IModel { diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Table.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Table.cs index 8e7b59e6ea..46c9d3f4d0 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Table.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/Table.cs @@ -10,7 +10,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.DatabaseModel { - [Serializable] public sealed class Table : NodeBase { private PrimaryIndex primaryIndex; diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/TableCollection.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/TableCollection.cs index 7c5b0182b1..dbc94b4331 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/TableCollection.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/TableCollection.cs @@ -10,7 +10,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.DatabaseModel { - [Serializable] public sealed class TableCollection : NodeCollectionBase, IUnorderedNodeCollection { diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/User.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/User.cs index 53f13312c2..0328fee44e 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/User.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/User.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.DatabaseModel { - [Serializable] public sealed class User : NodeBase { private string password; diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/UserCollection.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/UserCollection.cs index 2683106acc..2d3ee205f4 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/UserCollection.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModel/UserCollection.cs @@ -9,7 +9,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.DatabaseModel { - [Serializable] public sealed class UserCollection : NodeCollectionBase { internal UserCollection(Security parent) diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModelTest.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModelTest.cs index 9f93edd8b2..cf85f5e2e6 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModelTest.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/DatabaseModelTest.cs @@ -66,15 +66,6 @@ public void Setup() _ = new SecondaryIndex(t2, "SI_t2ab"); } - [Test] - [Ignore("TODO: AY check it ASAP")] - public void SerializationTest() - { - var clone = Cloner.Clone(srv); -// clone.Dump(); - clone.Validate(); - } - [Test] public void CloneTest() { diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ColumnInfo.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ColumnInfo.cs index d47c3b9dae..6b756e01e0 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ColumnInfo.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ColumnInfo.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// Column. /// - [Serializable] public sealed class ColumnInfo: NodeBase { private TypeInfo type; diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ColumnInfoCollection.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ColumnInfoCollection.cs index 7011fd26aa..ae31dcb401 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ColumnInfoCollection.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ColumnInfoCollection.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// Column collection. /// - [Serializable] public sealed class ColumnInfoCollection : NodeCollectionBase { // Constructors diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ColumnInfoRef.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ColumnInfoRef.cs index 7fe17fe2d3..af902f295f 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ColumnInfoRef.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ColumnInfoRef.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// An abstract base class for all columns refs. /// - [Serializable] public abstract class ColumnInfoRef: Ref where TParent: Node { diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/Exceptions/ValidationException.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/Exceptions/ValidationException.cs index a6647d965d..dc62849449 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/Exceptions/ValidationException.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/Exceptions/ValidationException.cs @@ -5,9 +5,6 @@ // Created: 2009.03.23 using System; -using System.Runtime.Serialization; -using System.Security; -using System.Security.Permissions; using Xtensive.Modelling; namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel @@ -16,7 +13,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// Describes errors detected during /// . execution. /// - [Serializable] public class ValidationException : Exception { /// @@ -49,29 +45,5 @@ public ValidationException(string message, string nodePath) { NodePath = nodePath; } - - #region Serializing members - - /// -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - protected ValidationException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - NodePath = info.GetString("NodePath"); - } - - /// - [SecurityCritical] -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue("NodePath", NodePath); - } - - #endregion } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ForeignKeyCollection.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ForeignKeyCollection.cs index 9c02cab018..773c8b3a33 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ForeignKeyCollection.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ForeignKeyCollection.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// Foreign key collection. /// - [Serializable] public sealed class ForeignKeyCollection : NodeCollectionBase, IUnorderedNodeCollection { diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ForeignKeyColumnCollection.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ForeignKeyColumnCollection.cs index 6b91936604..65bf3713f3 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ForeignKeyColumnCollection.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ForeignKeyColumnCollection.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// A collection of instances. /// - [Serializable] public sealed class ForeignKeyColumnCollection : NodeCollectionBase { /// diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ForeignKeyColumnRef.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ForeignKeyColumnRef.cs index 7f469190d0..7ef9f7168d 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ForeignKeyColumnRef.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ForeignKeyColumnRef.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// References to foreign key column. /// - [Serializable] public sealed class ForeignKeyColumnRef : Ref { protected override Nesting CreateNesting() diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ForeignKeyInfo.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ForeignKeyInfo.cs index c34be4bd48..7ea6bb06f6 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ForeignKeyInfo.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ForeignKeyInfo.cs @@ -16,7 +16,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// Foreign key. /// - [Serializable] [DataDependent] public sealed class ForeignKeyInfo : NodeBase { diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/FullTextColumnRef.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/FullTextColumnRef.cs index c30dca295b..1d7fcf2d11 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/FullTextColumnRef.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/FullTextColumnRef.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// Reference to full-text column. /// - [Serializable] public sealed class FullTextColumnRef : ColumnInfoRef { [Property(Priority = -1100)] diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/FullTextColumnRefCollection.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/FullTextColumnRefCollection.cs index bec3e5c118..24e80a6f4d 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/FullTextColumnRefCollection.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/FullTextColumnRefCollection.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// A collection of instances. /// - [Serializable] public sealed class FullTextColumnRefCollection : NodeCollectionBase { diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/FullTextIndexInfo.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/FullTextIndexInfo.cs index 2409eea7cf..4623dea442 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/FullTextIndexInfo.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/FullTextIndexInfo.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// Full-text index. /// - [Serializable] public sealed class FullTextIndexInfo : NodeBase { /// diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/IncludedColumnRef.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/IncludedColumnRef.cs index 75fbaffe6e..6e719616ca 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/IncludedColumnRef.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/IncludedColumnRef.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// References to included column. /// - [Serializable] public sealed class IncludedColumnRef : ColumnInfoRef { /// diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/IncludedColumnRefCollection.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/IncludedColumnRefCollection.cs index 3f4e5288c7..9ff6e02b50 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/IncludedColumnRefCollection.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/IncludedColumnRefCollection.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// A collection of instances. /// - [Serializable] public sealed class IncludedColumnRefCollection: NodeCollectionBase { // Constructors diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/IndexInfo.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/IndexInfo.cs index 6224231d9c..e624b69584 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/IndexInfo.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/IndexInfo.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// The base abstract class for all indexes. /// - [Serializable] public abstract class IndexInfo : NodeBase { private bool isUnique; diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/KeyColumnRef.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/KeyColumnRef.cs index 8d1bb3b135..459044bdb4 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/KeyColumnRef.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/KeyColumnRef.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// References to key column. /// - [Serializable] public sealed class KeyColumnRef: KeyColumnRef { /// diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/KeyColumnRefCollection.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/KeyColumnRefCollection.cs index 504a90d3d7..f181c6f2f4 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/KeyColumnRefCollection.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/KeyColumnRefCollection.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// A collection of instances. /// - [Serializable] public sealed class KeyColumnRefCollection : NodeCollectionBase { // Constructors diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/KeyColumnRef{TParent}.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/KeyColumnRef{TParent}.cs index deb0282563..4f2ac4d89a 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/KeyColumnRef{TParent}.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/KeyColumnRef{TParent}.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// References to key column. /// - [Serializable] public abstract class KeyColumnRef: ColumnInfoRef where TParent: IndexInfo { diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/NodeBase.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/NodeBase.cs index 91ec83affc..9122abbc71 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/NodeBase.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/NodeBase.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// A base class for all nodes in storage model. /// /// The type of the parent node. - [Serializable] public abstract class NodeBase : Node where TParent : Node { diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/NodeCollectionBase.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/NodeCollectionBase.cs index bbb648a25a..ef2ae4a509 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/NodeCollectionBase.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/NodeCollectionBase.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// The type of the node. /// The type of the parent node. - [Serializable] public abstract class NodeCollectionBase : NodeCollection where TNode : Node where TParent : Node diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/PrimaryIndexInfo.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/PrimaryIndexInfo.cs index bb7c60550d..d5e178a5b2 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/PrimaryIndexInfo.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/PrimaryIndexInfo.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// Primary index. /// - [Serializable] public sealed class PrimaryIndexInfo : IndexInfo { /// diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/PrimaryKeyColumnRef.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/PrimaryKeyColumnRef.cs index 191a50fbe2..4f326b9262 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/PrimaryKeyColumnRef.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/PrimaryKeyColumnRef.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// References to key column. /// - [Serializable] public sealed class PrimaryKeyColumnRef: KeyColumnRef { /// diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/PrimaryKeyColumnRefCollection.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/PrimaryKeyColumnRefCollection.cs index 844273704e..9e10c34f6b 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/PrimaryKeyColumnRefCollection.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/PrimaryKeyColumnRefCollection.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// A collection of instances. /// - [Serializable] public sealed class PrimaryKeyColumnRefCollection : NodeCollectionBase { // Constructors diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/Ref.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/Ref.cs index cd8e86d985..397476918d 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/Ref.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/Ref.cs @@ -16,7 +16,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// The type of the target node. /// The type of the parent node. - [Serializable] public abstract class Ref : NodeBase, IUnnamedNode, INodeReference diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ReferentialAction.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ReferentialAction.cs index 36a0342367..4c992648e0 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ReferentialAction.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ReferentialAction.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// Referential integrity maintenance actions. /// - [Serializable] public enum ReferentialAction { /// diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/SecondaryIndexInfo.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/SecondaryIndexInfo.cs index 2265f09144..cde617ea43 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/SecondaryIndexInfo.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/SecondaryIndexInfo.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// Secondary index. /// - [Serializable] public sealed class SecondaryIndexInfo : IndexInfo { /// diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/SecondaryIndexInfoCollection.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/SecondaryIndexInfoCollection.cs index 1975d2e956..540223bce7 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/SecondaryIndexInfoCollection.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/SecondaryIndexInfoCollection.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// A collection of secondary indexes. /// - [Serializable] public sealed class SecondaryIndexInfoCollection : NodeCollectionBase, IUnorderedNodeCollection { diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/StorageInfo.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/StorageInfo.cs index 8f59c25582..4e80778276 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/StorageInfo.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/StorageInfo.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// Indexing storage. /// - [Serializable] public sealed class StorageInfo : NodeBase, IModel { diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/TableInfo.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/TableInfo.cs index 296d2a8178..7613db519a 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/TableInfo.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/TableInfo.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// Table. /// - [Serializable] public sealed class TableInfo : NodeBase { private PrimaryIndexInfo primaryIndex; diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/TableInfoCollection.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/TableInfoCollection.cs index a0a66c6bd1..6f7f96c1b6 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/TableInfoCollection.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/TableInfoCollection.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// A collection of instances. /// - [Serializable] public sealed class TableInfoCollection: NodeCollectionBase, IUnorderedNodeCollection { diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/TypeInfo.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/TypeInfo.cs index 9fd0c3101e..2379106c15 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/TypeInfo.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/TypeInfo.cs @@ -16,7 +16,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// Type of table column. /// - [Serializable] public sealed class TypeInfo : IEquatable, IValidatable, ICloneable diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ValueColumnRef.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ValueColumnRef.cs index 68b09354e7..04c8968541 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ValueColumnRef.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ValueColumnRef.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// References to value column. /// - [Serializable] public sealed class ValueColumnRef : ColumnInfoRef { /// diff --git a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ValueColumnRefCollection.cs b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ValueColumnRefCollection.cs index 59036d095d..f7df019e45 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ValueColumnRefCollection.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ValueColumnRefCollection.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel /// /// A collection of instances. /// - [Serializable] public sealed class ValueColumnRefCollection: NodeCollectionBase { // Constructors diff --git a/Orm/Xtensive.Orm.Tests.Core/Tuples/LongTupleTest.cs b/Orm/Xtensive.Orm.Tests.Core/Tuples/LongTupleTest.cs index eac608a888..fdf1b650bf 100644 --- a/Orm/Xtensive.Orm.Tests.Core/Tuples/LongTupleTest.cs +++ b/Orm/Xtensive.Orm.Tests.Core/Tuples/LongTupleTest.cs @@ -43,13 +43,6 @@ public void CombinedTest() // Testing reads (untyped) for (int j = 0; j < count; j++) Assert.That(tuple.GetValue(j), Is.EqualTo(data[j])); - // Testing serialization - var tuple2 = Cloner.Clone(tuple); - Assert.That(tuple2, Is.EqualTo(tuple)); - Assert.That(tuple2.Descriptor, Is.EqualTo(tuple.Descriptor)); - // Testing reads (untyped)); - for (int j = 0; j < count; j++) - Assert.That(tuple2.GetValue(j), Is.EqualTo(data[j])); } { diff --git a/Orm/Xtensive.Orm.Tests.Core/Tuples/TupleFormatAndParseTest.cs b/Orm/Xtensive.Orm.Tests.Core/Tuples/TupleFormatAndParseTest.cs new file mode 100644 index 0000000000..065c9f0076 --- /dev/null +++ b/Orm/Xtensive.Orm.Tests.Core/Tuples/TupleFormatAndParseTest.cs @@ -0,0 +1,178 @@ +// Copyright (C) 2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System; +using Xtensive.Tuples; +using NUnit.Framework; +using Tuple = Xtensive.Tuples.Tuple; +using System.Linq; + +namespace Xtensive.Orm.Tests.Core.Tuples +{ + [TestFixture] + public class TupleFormatAndParseTest + { + // The test contains cases of types which can be in tuple in real usage, + // basically all the type which have map in any of storage. + // No exotic cases. + + [Test] + public void BoolValueTest() + { + var tuple = Xtensive.Tuples.Tuple.Create(true, true, false, true, false, false); + + TestTuple(tuple); + } + + [Test] + public void CharValueTest() + { + var tuple = Xtensive.Tuples.Tuple.Create('s', 'q', 'd'); + TestTuple(tuple); + } + + [Test] + public void NumbericValuesTest() + { + var tuple = Tuple.Create(byte.MinValue, byte.MaxValue, 254, sbyte.MinValue, sbyte.MaxValue, 127); + TestTuple(tuple); + + tuple = Tuple.Create(short.MinValue, short.MaxValue, 23859, ushort.MinValue, ushort.MaxValue, 58994); + TestTuple(tuple); + + tuple = Tuple.Create(int.MinValue, int.MaxValue, 578621485, uint.MinValue, uint.MaxValue, 545564624); + TestTuple(tuple); + + tuple = Tuple.Create( + long.MinValue, long.MaxValue, 5468546548746545465, ulong.MinValue, ulong.MaxValue, 8868768654687865456); + TestTuple(tuple); + + tuple = Tuple.Create( + float.MinValue, float.MaxValue, float.E, float.NaN, float.Pi, float.Tau); + TestTuple(tuple); + + tuple = Tuple.Create( + 2f, 3.000057f, 4.5678911f); + TestTuple(tuple); + + tuple = Tuple.Create( + double.MinValue, double.MaxValue, double.E, double.Epsilon, double.NaN, double.Pi); + TestTuple(tuple); + + tuple = Tuple.Create(double.Tau, 1, 2.487987484654987); + TestTuple(tuple); + + tuple = Tuple.Create( + decimal.MinValue, decimal.MaxValue, decimal.One, decimal.Zero, decimal.One, decimal.MinusOne); + TestTuple(tuple); + + tuple = Tuple.Create( + 1m, 0m, -1m, 20746875411587982147878187855m, 0.18775548545212454615315465325m); + TestTuple(tuple); + } + + [Test] + public void StringValuesTest() + { + var tuple = Tuple.Create("", "bdc", string.Empty); + TestTuple(tuple); + } + + [Test] + public void TimeSpanValueTest() + { + var tuple = Tuple.Create( + TimeSpan.MinValue, TimeSpan.MaxValue, TimeSpan.Zero, + TimeSpan.FromMicroseconds(6060123456), + TimeSpan.FromTicks(70701234567)); + TestTuple(tuple); + } + + [Test] + public void DateTimeValueTest() + { + var tuple = Tuple.Create( + DateTime.MinValue, + DateTime.MaxValue, + DateTime.Now, + DateTime.UtcNow, + new DateTime(2018, 7, 15, 12, 13, 14, 152, 168), + new DateTime(1_000_000_000 + 1234567) + ); + TestTuple(tuple); + } + + [Test] + public void DateOnlyValueTest() + { + var tuple = Tuple.Create( + DateOnly.MinValue, + DateOnly.MaxValue, + DateOnly.FromDayNumber(6584)); + TestTuple(tuple); + } + + [Test] + public void TimeOnlyValueTest() + { + var tuple = Tuple.Create( + TimeOnly.MinValue, + TimeOnly.MaxValue, + new TimeOnly(12,13,14,152,168), + new TimeOnly(12132_3456789)); + TestTuple(tuple); + } + + [Test] + public void DateTimeOffsetValueTest() + { + var tuple = Tuple.Create( + DateTimeOffset.MinValue, + DateTimeOffset.MaxValue, + DateTimeOffset.Now, + DateTimeOffset.UtcNow, + new DateTimeOffset(new DateTime(2018, 7, 15, 12, 13, 14, 152, 168), TimeSpan.FromHours(3)), + new DateTimeOffset(new DateTime(1_000_000_000_000 + 1234567), TimeSpan.FromHours(2))); + + TestTuple(tuple); + + } + + [Test] + public void GuidValueTest() + { + var tuple = Tuple.Create(Guid.Empty, Guid.NewGuid()); + TestTuple(tuple); + } + + [Test] + public void ByteArrayValueTest() + { + var tuple = Tuple.Create(new byte[0], new byte[] { 2, 18, 35, 75, 92, 120, 150, 254 } ); + + var descriptor = tuple.Descriptor; + var stringTuple = tuple.Format(); + + var parsedTuple = Tuple.Parse(descriptor, stringTuple); + Assert.That(parsedTuple.Count, Is.EqualTo(tuple.Count)); + for (var i = 0; i < parsedTuple.Count; i++) { + var original = (byte[]) tuple.GetValue(i, out var _); + var parsed = (byte[]) parsedTuple.GetValue(i, out var _); + + Assert.That(original, Is.Not.Null); + Assert.That(parsed, Is.Not.Null); + Assert.That(parsed.SequenceEqual(parsed), Is.True); + } + } + + private static void TestTuple(RegularTuple tuple) + { + var descriptor = tuple.Descriptor; + var stringTuple = tuple.Format(); + + var parsedTuple = Tuple.Parse(descriptor, stringTuple); + Assert.That(parsedTuple.Equals(tuple), Is.True); + } + } +} diff --git a/Orm/Xtensive.Orm.Tests.Core/Tuples/TupleSerializationTest.cs b/Orm/Xtensive.Orm.Tests.Core/Tuples/TupleSerializationTest.cs deleted file mode 100644 index 92d39a739a..0000000000 --- a/Orm/Xtensive.Orm.Tests.Core/Tuples/TupleSerializationTest.cs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. -// Created by: Alex Yakunin -// Created: 2008.08.27 - -using NUnit.Framework; -using Xtensive.Core; -using Xtensive.Orm.Tests; -using Xtensive.Tuples; - -namespace Xtensive.Orm.Tests.Core.Tuples -{ - [TestFixture] - public class TupleSerializationTest - { - [Test] - public void BaseTest() - { - var tuple = Tuple.Create(1, false); - var clone = CloneBySerialization(tuple); - Assert.That(clone==null, Is.False); - Assert.That(clone, Is.EqualTo(tuple)); - } - - [Test] - public void CombinedTest() - { - var t = Tuple.Create(1, false); - Assert.That(CloneBySerialization(t), Is.EqualTo(t)); - - t = Tuple.Create(t.Descriptor); - t.SetValue(1, true); - Assert.That(CloneBySerialization(t), Is.EqualTo(t)); - } - - [Test] - public void SerializationWithNullValuesTest() - { - var t = Tuple.Create(typeof (string), typeof (int)); - t.SetValue(0, null); - t.SetValue(1, null); - - Assert.That(CloneBySerialization(t), Is.EqualTo(t)); - } - - [Test] - public void DifferentialTupleSerializationTest() - { - var origin = Tuple.Create(1, 2); - var dt1 = new DifferentialTuple(origin); - dt1.SetValue(1,3); - var dt2 = new DifferentialTuple(origin); - dt1.SetValue(1,4); - var all = new[] {dt1, dt2}; - - var clone = Cloner.Clone(all); - AssertEx.HasSameElements(all, clone); - - var dt1Clone = clone[0]; - var dt2Clone = clone[1]; - var originClone = dt1Clone.Origin; - Assert.That(dt2Clone.Origin, Is.SameAs(originClone)); - originClone.SetValue(0,2); - Assert.That(dt1Clone.GetValue(0), Is.EqualTo(2)); - Assert.That(dt2Clone.GetValue(0), Is.EqualTo(2)); - } - - private static Tuple CloneBySerialization(Tuple source) - { - return Cloner.Clone(source); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Core/UrlInfoTest.cs b/Orm/Xtensive.Orm.Tests.Core/UrlInfoTest.cs index ec11fb2914..d64e628870 100644 --- a/Orm/Xtensive.Orm.Tests.Core/UrlInfoTest.cs +++ b/Orm/Xtensive.Orm.Tests.Core/UrlInfoTest.cs @@ -4,6 +4,9 @@ // Created by: Alexander Ilyin // Created: 2007.07.18 +using System.Linq; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Json; using NUnit.Framework; namespace Xtensive.Orm.Tests.Core @@ -11,13 +14,17 @@ namespace Xtensive.Orm.Tests.Core [TestFixture] public class UrlInfoTest { + private const string TestUrl1 = "tcp://user:password@someHost:1000/someUrl/someUrl?someParameter=someValue&someParameter2=someValue2"; + private const string TestUrl2 = "tcp://user:password@someHost:1000/someUrl/someUrl?someParameter2=someValue2&someParameter=someValue"; + private const string TestUrl3 = "tcp://user:password@someHost:1000/someUrl/someUrl"; + [Test] public void CombinedTest() { - UrlInfo a1 = UrlInfo.Parse("tcp://user:password@someHost:1000/someUrl/someUrl?someParameter=someValue&someParameter2=someValue2"); - UrlInfo a2 = UrlInfo.Parse("tcp://user:password@someHost:1000/someUrl/someUrl?someParameter=someValue&someParameter2=someValue2"); - UrlInfo aX = UrlInfo.Parse("tcp://user:password@someHost:1000/someUrl/someUrl?someParameter2=someValue2&someParameter=someValue"); - UrlInfo b = UrlInfo.Parse("tcp://user:password@someHost:1000/someUrl/someUrl"); + UrlInfo a1 = UrlInfo.Parse(TestUrl1); + UrlInfo a2 = UrlInfo.Parse(TestUrl1); + UrlInfo aX = UrlInfo.Parse(TestUrl2); + UrlInfo b = UrlInfo.Parse(TestUrl3); Assert.That(a1.GetHashCode()==a2.GetHashCode(), Is.True); Assert.That(a1.GetHashCode()!=aX.GetHashCode(), Is.True); diff --git a/Orm/Xtensive.Orm.Tests.Framework/Cloner.cs b/Orm/Xtensive.Orm.Tests.Framework/Cloner.cs index a213a7e527..0f895f95dd 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Cloner.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Cloner.cs @@ -1,12 +1,19 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2025 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alex Yakunin // Created: 2009.05.05 +using System; +using System.Collections.Generic; using System.IO; +using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; +using System.Runtime.Serialization.Json; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; namespace Xtensive.Orm.Tests { @@ -15,19 +22,141 @@ namespace Xtensive.Orm.Tests /// public static class Cloner { - private static readonly IFormatter Formatter = new BinaryFormatter(); + public static class SerializationDomains + { + public static readonly Lazy> System = new Lazy>( + () => [ + typeof(DateOnly), typeof(DateOnly?), typeof(DateOnly[]), typeof(DateOnly?[]), + typeof(TimeOnly), typeof(TimeOnly?), typeof(TimeOnly[]), typeof(TimeOnly?[]), + typeof(DateTime), typeof(DateTime?), typeof(DateTime[]), typeof(DateTime?[]), + typeof(TimeSpan), typeof(TimeSpan?), typeof(TimeSpan[]), typeof(TimeSpan?[]), + typeof(DateTimeOffset), typeof(DateTimeOffset?), typeof(DateTimeOffset[]), typeof(DateTimeOffset?[]), + typeof(Type), typeof(Type[]), + typeof(MethodInfo), typeof(MethodInfo[]), + typeof(MemberInfo), typeof(MemberInfo[]), + typeof(ConstructorInfo), typeof(ConstructorInfo[]), + typeof(bool?), typeof(bool[]), typeof(bool?[]), + typeof(byte?), typeof(byte[]), typeof(byte?[]), + typeof(sbyte?), typeof(sbyte[]), typeof(sbyte?[]), + typeof(short?), typeof(short[]), typeof(short?[]), + typeof(ushort?), typeof(ushort[]), typeof(ushort?[]), + typeof(int?), typeof(int[]), typeof(int?[]), + typeof(uint?), typeof(uint[]), typeof(uint?[]), + typeof(long?), typeof(long[]), typeof(long?[]), + typeof(ulong?), typeof(ulong[]), typeof(ulong?[]), + typeof(float?), typeof(float[]), typeof(float?[]), + typeof(double?), typeof(double[]), typeof(double?[]), + typeof(decimal?), typeof(decimal[]), typeof(decimal?[]), + typeof(string[]), + ]); + } /// - /// Clones the using - /// provided . + /// Clones the via . /// - /// The source to clone. - public static T Clone(T source) + /// The type of instance. + /// The instance to clone. + /// The known type to pass into the serializer. + /// Cloned instance. + public static T CloneViaXmlSerialization(T source, IEnumerable knownTypes) { - using (var stream = new MemoryStream()) { - Formatter.Serialize(stream, source); - stream.Position = 0; - return (T) Formatter.Deserialize(stream); + var settings = new DataContractSerializerSettings { KnownTypes = knownTypes, PreserveObjectReferences = true }; + return CloneViaXmlSerialization(source, settings); + } + + /// + /// Clones the via . + /// + /// The type of instance. + /// The instance to clone. + /// The settings for the serializer. + /// Cloned instance. + public static T CloneViaXmlSerialization(T source, DataContractSerializerSettings settings) + { + using (var mStream = new MemoryStream()) { + var dcSerializer = new DataContractSerializer(typeof(T), settings); + dcSerializer.WriteObject(mStream, source); +#if DEBUG + var data = mStream.ToArray(); + var serializedVersion = Encoding.UTF8.GetString(data); +#endif + _ = mStream.Seek(0, SeekOrigin.Begin); + return (T) dcSerializer.ReadObject(mStream); + } + } + + /// + /// Clones the via . + /// + /// The type of instance. + /// The instance to clone. + /// The known type to pass into the serializer. + /// Cloned instance. + public static T CloneViaJsonSerialization(T source, IEnumerable knownTypes) + { + var settings = new DataContractJsonSerializerSettings { KnownTypes = knownTypes }; + return CloneViaJsonSerialization(source, settings); + } + + /// + /// Clones the via . + /// + /// The type of instance. + /// The instance to clone. + /// The settings for the serializer. + /// Cloned instance. + public static T CloneViaJsonSerialization(T source, DataContractJsonSerializerSettings settings) + { + using (var mStream = new MemoryStream()) { + var dcSerializer = new DataContractJsonSerializer(typeof(T), settings); + dcSerializer.WriteObject(mStream, source); +#if DEBUG + var data = mStream.ToArray(); + var serializedVersion = Encoding.UTF8.GetString(data); +#endif + _ = mStream.Seek(0, SeekOrigin.Begin); + return (T) dcSerializer.ReadObject(mStream); + } + } + + /// + /// Clones via with indentation and reference preservation. + /// + /// Type of object. + /// The object to clone. + /// Options for . + /// Cloned object + public static T CloneViaJsonSerialization(T source, bool useDataContract = false) + { + if (useDataContract) { + var settings = new DataContractJsonSerializerSettings(); + return CloneViaJsonSerialization(source, settings); + } + else { + var settings = new JsonSerializerOptions { WriteIndented = true, ReferenceHandler = ReferenceHandler.Preserve }; + return CloneViaJsonSerialization(source, settings); + } + } + + /// + /// Clones via . + /// + /// Type of object. + /// The object to clone. + /// Options for . + /// Cloned object + public static T CloneViaJsonSerialization(T source, JsonSerializerOptions options) + { + using (var mStream = new MemoryStream()) { + + JsonSerializer.Serialize(mStream, source, options); +#if DEBUG + var data = mStream.ToArray(); + var serializedVersion = Encoding.UTF8.GetString(data); +#endif + _ = mStream.Seek(0, SeekOrigin.Begin); + return JsonSerializer.Deserialize(mStream, options); + } } } diff --git a/Orm/Xtensive.Orm.Tests.Framework/InstanceGeneratorProvider.cs b/Orm/Xtensive.Orm.Tests.Framework/InstanceGeneratorProvider.cs index 89fea6a73d..29ec0d5b92 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/InstanceGeneratorProvider.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/InstanceGeneratorProvider.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Gamzov // Created: 2008.01.17 @@ -15,41 +15,35 @@ namespace Xtensive.Orm.Tests /// Default provider. /// Provides default instance generator for the specified type. /// - [Serializable] public class InstanceGeneratorProvider : AssociateProvider, IInstanceGeneratorProvider { - private static readonly InstanceGeneratorProvider @default = new InstanceGeneratorProvider(); - private ConcurrentDictionary<(Type, InstanceGeneratorProvider), Lazy> generators = - new ConcurrentDictionary<(Type, InstanceGeneratorProvider), Lazy>(); + private readonly ConcurrentDictionary<(Type, InstanceGeneratorProvider), Lazy> generators = new(); public static InstanceGeneratorProvider Default { [DebuggerStepThrough] - get { return @default; } - } + get; + } = new InstanceGeneratorProvider(); #region IInstanceGeneratorProvider members /// - public virtual IInstanceGenerator GetInstanceGenerator() - { - return GetAssociate, IInstanceGenerator>(); - } + public virtual IInstanceGenerator GetInstanceGenerator() => GetAssociate, IInstanceGenerator>(); /// public IInstanceGeneratorBase GetInstanceGenerator(Type type) { + return generators.GetOrAdd((type, this), InstanceGeneratorFactory).Value; + static Lazy InstanceGeneratorFactory((Type, InstanceGeneratorProvider) tuple) { var (_type, _this) = tuple; return new Lazy(() => _this.GetType() - .GetMethod("GetInstanceGenerator", Array.Empty()) + .GetMethod(nameof(GetInstanceGenerator), Array.Empty()) .GetGenericMethodDefinition() .MakeGenericMethod(new[] { _type }) .Invoke(_this, null) as IInstanceGeneratorBase); - }; - - return generators.GetOrAdd((type, this), InstanceGeneratorFactory).Value; + } } #endregion @@ -60,8 +54,8 @@ static Lazy InstanceGeneratorFactory((Type, InstanceGene protected InstanceGeneratorProvider() { - TypeSuffixes = new[] {"InstanceGenerator"}; - Type t = typeof (InstanceGeneratorProvider); + TypeSuffixes = ["InstanceGenerator"]; + var t = typeof (InstanceGeneratorProvider); AddHighPriorityLocation(t.Assembly, t.Namespace); } } diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/ArrayInstanceGenerator.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/ArrayInstanceGenerator.cs index 44cc5d9604..b2f3b6efd5 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/ArrayInstanceGenerator.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/ArrayInstanceGenerator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alex Yakunin // Created: 2008.01.25 @@ -10,22 +10,20 @@ namespace Xtensive.Orm.Tests { - [Serializable] - internal class KeyValuePairInstanceGenerator: WrappingInstanceGenerator, T1, T2> + internal sealed class ArrayInstanceGenerator(IInstanceGeneratorProvider provider) + : WrappingInstanceGenerator(provider) { - public override KeyValuePair GetInstance(Random random) - { - return new KeyValuePair( - BaseGenerator1.GetInstance(random), - BaseGenerator2.GetInstance(random)); - } - - - // Constructors + public const int ArrayLength = 100; - public KeyValuePairInstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) + public override T[] GetInstance(Random random) { + T[] result = new T[ArrayLength]; + int i = 0; + foreach (T t in BaseGenerator.GetInstances(random, ArrayLength)) { + result[i] = t; + i++; + } + return result; } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/BooleanInstanceGenerator.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/BooleanInstanceGenerator.cs index 744082c6b8..fd6771d1c8 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/BooleanInstanceGenerator.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/BooleanInstanceGenerator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.18 @@ -9,8 +9,8 @@ namespace Xtensive.Orm.Tests { - [Serializable] - internal class BooleanInstanceGenerator : InstanceGeneratorBase + internal class BooleanInstanceGenerator(IInstanceGeneratorProvider provider) + : InstanceGeneratorBase(provider) { public override bool GetInstance(Random random) { @@ -20,13 +20,5 @@ public override bool GetInstance(Random random) return BitConverter.ToBoolean(randomByte, 0); } } - - - // Constructors - - public BooleanInstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/ByteInstanceGenerator.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/ByteInstanceGenerator.cs index 211add9df5..9c3ea6981b 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/ByteInstanceGenerator.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/ByteInstanceGenerator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.18 @@ -9,20 +9,9 @@ namespace Xtensive.Orm.Tests { - [Serializable] - internal class ByteInstanceGenerator : InstanceGeneratorBase + internal class ByteInstanceGenerator(IInstanceGeneratorProvider provider) + : InstanceGeneratorBase(provider) { - public override byte GetInstance(Random random) - { - return (byte)random.Next(byte.MinValue, byte.MaxValue + 1); - } - - - // Constructors - - public ByteInstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - } + public override byte GetInstance(Random random) => (byte) random.Next(byte.MinValue, byte.MaxValue + 1); } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/CharInstanceGenerator.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/CharInstanceGenerator.cs index 07df3e2936..3885b623a0 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/CharInstanceGenerator.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/CharInstanceGenerator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.18 @@ -9,25 +9,17 @@ namespace Xtensive.Orm.Tests { - [Serializable] - internal class CharInstanceGenerator : InstanceGeneratorBase + internal sealed class CharInstanceGenerator(IInstanceGeneratorProvider provider) + : InstanceGeneratorBase(provider) { public override char GetInstance(Random random) { - char instance = (char)random.Next(char.MinValue, char.MaxValue + 1); + var instance = (char)random.Next(char.MinValue, char.MaxValue + 1); // Prevent surrogate characters. while(char.IsSurrogate(instance)) { instance = (char)random.Next(char.MinValue, char.MaxValue + 1); } return instance; } - - - // Constructors - - public CharInstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/DateTimeInstanceGenerator.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/DateTimeInstanceGenerator.cs index bafd787548..87d6fe9ec2 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/DateTimeInstanceGenerator.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/DateTimeInstanceGenerator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.22 @@ -9,29 +9,20 @@ namespace Xtensive.Orm.Tests { - [Serializable] - internal class DateTimeInstanceGenerator : InstanceGeneratorBase + internal sealed class DateTimeInstanceGenerator(IInstanceGeneratorProvider provider) + : InstanceGeneratorBase(provider) { - private readonly IInstanceGenerator longInstanceGeneratorProvider; + private readonly IInstanceGenerator longInstanceGeneratorProvider = provider.GetInstanceGenerator(); public override DateTime GetInstance(Random random) { - long randomLong = long.MinValue; + var randomLong = longInstanceGeneratorProvider.GetInstance(random); // MinValue must be excluded while (randomLong == long.MinValue) randomLong = longInstanceGeneratorProvider.GetInstance(random); - long correctDateTime = Math.Abs(Math.Abs(randomLong) %(DateTime.MaxValue - DateTime.MinValue).Ticks + DateTime.MinValue.Ticks); + var correctDateTime = Math.Abs(Math.Abs(randomLong) %(DateTime.MaxValue - DateTime.MinValue).Ticks + DateTime.MinValue.Ticks); return new DateTime(correctDateTime); } - - - // Constructors - - public DateTimeInstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - longInstanceGeneratorProvider = provider.GetInstanceGenerator(); - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/DateTimeOffsetInstanceGenerator.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/DateTimeOffsetInstanceGenerator.cs index e71e815929..14f48e6337 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/DateTimeOffsetInstanceGenerator.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/DateTimeOffsetInstanceGenerator.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2021 Xtensive LLC. +// Copyright (C) 2021-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. @@ -6,10 +6,10 @@ namespace Xtensive.Orm.Tests { - [Serializable] - internal class DateTimeOffsetInstanceGenerator : InstanceGeneratorBase + internal sealed class DateTimeOffsetInstanceGenerator(IInstanceGeneratorProvider provider) + : InstanceGeneratorBase(provider) { - private readonly IInstanceGenerator dateTimeInstanceGenerator; + private readonly IInstanceGenerator dateTimeInstanceGenerator = provider.GetInstanceGenerator(); public override DateTimeOffset GetInstance(Random random) { @@ -22,11 +22,5 @@ public override DateTimeOffset GetInstance(Random random) return new DateTimeOffset(randomDateTime, randomTimeSpan); } - - public DateTimeOffsetInstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - dateTimeInstanceGenerator = provider.GetInstanceGenerator(); - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/DecimalInstanceGenerator.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/DecimalInstanceGenerator.cs index 2111598314..f52bcaf58a 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/DecimalInstanceGenerator.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/DecimalInstanceGenerator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Gamzov // Created: 2008.01.24 @@ -8,8 +8,8 @@ namespace Xtensive.Orm.Tests { - [Serializable] - internal class DecimalInstanceGenerator : InstanceGeneratorBase + internal sealed class DecimalInstanceGenerator(IInstanceGeneratorProvider provider) + : InstanceGeneratorBase(provider) { public override decimal GetInstance(Random random) { @@ -18,13 +18,5 @@ public override decimal GetInstance(Random random) (random.Next() % 2 == 0), (byte)(random.Next() % 29)); } } - - - // Constructors - - public DecimalInstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/DoubleInstanceGenerator.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/DoubleInstanceGenerator.cs index 25af52d410..a646b8077e 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/DoubleInstanceGenerator.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/DoubleInstanceGenerator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.18 @@ -9,20 +9,9 @@ namespace Xtensive.Orm.Tests { - [Serializable] - internal class DoubleInstanceGenerator : InstanceGeneratorBase + internal sealed class DoubleInstanceGenerator(IInstanceGeneratorProvider provider) + : InstanceGeneratorBase(provider) { - public override double GetInstance(Random random) - { - return random.NextDouble(); - } - - - // Constructors - - public DoubleInstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - } + public override double GetInstance(Random random) => random.NextDouble(); } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/EnumInstanceGenerator.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/EnumInstanceGenerator.cs index d401809c28..0b9a6c7b14 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/EnumInstanceGenerator.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/EnumInstanceGenerator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alex Yakunin // Created: 2008.01.23 @@ -9,24 +9,13 @@ namespace Xtensive.Orm.Tests { - [Serializable] - internal class EnumInstanceGenerator : WrappingInstanceGenerator + internal class EnumInstanceGenerator(IInstanceGeneratorProvider provider) + : WrappingInstanceGenerator(provider) where TEnum: struct where TSystem: struct { private static readonly Array values = Enum.GetValues(typeof(TEnum)); - public override TEnum GetInstance(Random random) - { - return (TEnum) values.GetValue(random.Next(values.Length)); - } - - - // Constructors - - public EnumInstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - } + public override TEnum GetInstance(Random random) => (TEnum) values.GetValue(random.Next(values.Length)); } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/GuidInstanceGenerator.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/GuidInstanceGenerator.cs index 7d0d3743bb..5a1ac366ce 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/GuidInstanceGenerator.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/GuidInstanceGenerator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.22 @@ -9,8 +9,8 @@ namespace Xtensive.Orm.Tests { - [Serializable] - internal class GuidInstanceGenerator : InstanceGeneratorBase + internal sealed class GuidInstanceGenerator(IInstanceGeneratorProvider provider) + : InstanceGeneratorBase(provider) { public override Guid GetInstance(Random random) { @@ -18,13 +18,5 @@ public override Guid GetInstance(Random random) random.NextBytes(byteBuffer); return new Guid(byteBuffer); } - - - // Constructors - - public GuidInstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/InstanceGeneratorBase.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/InstanceGeneratorBase.cs index 107244d5e4..f24b8fa455 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/InstanceGeneratorBase.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/InstanceGeneratorBase.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Gamzov // Created: 2008.01.21 @@ -16,18 +16,19 @@ namespace Xtensive.Orm.Tests /// Base class for any random generator. /// /// Type of instances to generate. - [Serializable] - public abstract class InstanceGeneratorBase: - IInstanceGenerator + /// + /// Initializes a new instance of this type. + /// + /// Instance generator provider this generator is bound to. + public abstract class InstanceGeneratorBase(IInstanceGeneratorProvider provider) + : IInstanceGenerator { - private IInstanceGeneratorProvider provider; - /// public IInstanceGeneratorProvider Provider { [DebuggerStepThrough] - get { return provider; } - } + get; + } = provider ?? throw new ArgumentNullException(nameof(provider)); /// public abstract T GetInstance(Random random); @@ -35,43 +36,19 @@ public IInstanceGeneratorProvider Provider /// public IEnumerable GetInstances(Random random, int? count) { - for (int i = 0; !count.HasValue || i - object IInstanceGeneratorBase.GetInstance(Random random) - { - return GetInstance(random); - } + object IInstanceGeneratorBase.GetInstance(Random random) => GetInstance(random); /// - IEnumerable IInstanceGeneratorBase.GetInstances(Random random, int? count) - { - return GetInstances(random, count); - } + IEnumerable IInstanceGeneratorBase.GetInstances(Random random, int? count) => GetInstances(random, count); #endregion - - - // Constructors - - /// - /// Initializes a new instance of this type. - /// - /// Instance generator provider this generator is bound to. - public InstanceGeneratorBase(IInstanceGeneratorProvider provider) - { - ArgumentNullException.ThrowIfNull(provider); - this.provider = provider; - } - - public virtual void OnDeserialization(object sender) - { - if (provider==null || provider.GetType()==typeof (InstanceGeneratorProvider)) - provider = InstanceGeneratorProvider.Default; - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/Int16InstanceGenerator.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/Int16InstanceGenerator.cs index c2b638adf5..917109f88b 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/Int16InstanceGenerator.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/Int16InstanceGenerator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.18 @@ -9,20 +9,10 @@ namespace Xtensive.Orm.Tests { - [Serializable] - internal class Int16InstanceGenerator : InstanceGeneratorBase + internal sealed class Int16InstanceGenerator(IInstanceGeneratorProvider provider) + : InstanceGeneratorBase(provider) { public override short GetInstance(Random random) - { - return (short)random.Next(short.MinValue, short.MaxValue + 1); - } - - - // Constructors - - public Int16InstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - } + => (short) random.Next(short.MinValue, short.MaxValue + 1); } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/Int32InstanceGenerator.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/Int32InstanceGenerator.cs index 8c79942cb3..74f14f6bc8 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/Int32InstanceGenerator.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/Int32InstanceGenerator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.18 @@ -9,20 +9,10 @@ namespace Xtensive.Orm.Tests { - [Serializable] - internal class Int32InstanceGenerator : InstanceGeneratorBase + internal class Int32InstanceGenerator(IInstanceGeneratorProvider provider) + : InstanceGeneratorBase(provider) { public override int GetInstance(Random random) - { - return random.Next(int.MinValue, int.MaxValue); - } - - - // Constructors - - public Int32InstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - } + => random.Next(int.MinValue, int.MaxValue); } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/Int64InstanceGenerator.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/Int64InstanceGenerator.cs index 5810ab70f8..a94709a679 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/Int64InstanceGenerator.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/Int64InstanceGenerator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.18 @@ -9,26 +9,9 @@ namespace Xtensive.Orm.Tests { - [Serializable] - internal class Int64InstanceGenerator : InstanceGeneratorBase + internal sealed class Int64InstanceGenerator(IInstanceGeneratorProvider provider) + : InstanceGeneratorBase(provider) { - public override long GetInstance(Random random) - { - byte[] byteBuffer = new byte[8]; - random.NextBytes(byteBuffer); - long result = 0; - for (int i = 0; i < 8; i++) { - result = (result << 8) | byteBuffer[i]; - } - return result; - } - - - // Constructors - - public Int64InstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - } + public override long GetInstance(Random random) => random.NextInt64(); } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/KeyValuePairInstanceGenerator.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/KeyValuePairInstanceGenerator.cs index 79e6124325..23e0e784cd 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/KeyValuePairInstanceGenerator.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/KeyValuePairInstanceGenerator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alex Yakunin // Created: 2008.01.25 @@ -10,28 +10,10 @@ namespace Xtensive.Orm.Tests { - [Serializable] - internal class ArrayInstanceGenerator: WrappingInstanceGenerator + internal sealed class KeyValuePairInstanceGenerator(IInstanceGeneratorProvider provider) + : WrappingInstanceGenerator, T1, T2>(provider) { - public const int ArrayLength = 100; - - public override T[] GetInstance(Random random) - { - T[] result = new T[ArrayLength]; - int i = 0; - foreach (T t in BaseGenerator.GetInstances(random, ArrayLength)) { - result[i] = t; - i++; - } - return result; - } - - - // Constructors - - public ArrayInstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - } + public override KeyValuePair GetInstance(Random random) + => new(BaseGenerator1.GetInstance(random), BaseGenerator2.GetInstance(random)); } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/NullableInstanceGenerator.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/NullableInstanceGenerator.cs index f895aa9fef..c2a70370e6 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/NullableInstanceGenerator.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/NullableInstanceGenerator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alex Yakunin // Created: 2008.01.23 @@ -9,26 +9,15 @@ namespace Xtensive.Orm.Tests { - [Serializable] - internal class NullableInstanceGenerator : WrappingInstanceGenerator + internal sealed class NullableInstanceGenerator(IInstanceGeneratorProvider provider) + : WrappingInstanceGenerator(provider) where T: struct { - private const int nullProbabilityFactor = 100; + private const int NullProbabilityFactor = 100; - public override T? GetInstance(Random random) - { - if (random.Next(nullProbabilityFactor)==0) - return default(T); - else - return BaseGenerator.GetInstance(random); - } - - - // Constructors - - public NullableInstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - } + public override T? GetInstance(Random random) => + random.Next(NullProbabilityFactor) == 0 + ? default + : BaseGenerator.GetInstance(random); } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/PairInstanceGenerator.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/PairInstanceGenerator.cs index 7727f29a86..f0adcdcccd 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/PairInstanceGenerator.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/PairInstanceGenerator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alex Yakunin // Created: 2008.01.25 @@ -10,22 +10,10 @@ namespace Xtensive.Orm.Tests { - [Serializable] - internal class PairInstanceGenerator: WrappingInstanceGenerator, T1, T2> + internal sealed class PairInstanceGenerator(IInstanceGeneratorProvider provider) + : WrappingInstanceGenerator, T1, T2>(provider) { public override Pair GetInstance(Random random) - { - return new Pair( - BaseGenerator1.GetInstance(random), - BaseGenerator2.GetInstance(random)); - } - - - // Constructors - - public PairInstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - } + => new (BaseGenerator1.GetInstance(random), BaseGenerator2.GetInstance(random)); } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/SByteInstanceGenerator.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/SByteInstanceGenerator.cs index 0d6f8c6862..4aead80d20 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/SByteInstanceGenerator.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/SByteInstanceGenerator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.18 @@ -9,10 +9,10 @@ namespace Xtensive.Orm.Tests { - [Serializable] - internal class SByteInstanceGenerator : InstanceGeneratorBase + internal sealed class SByteInstanceGenerator(IInstanceGeneratorProvider provider) + : InstanceGeneratorBase(provider) { - private readonly IInstanceGenerator byteItemGenerator; + private readonly IInstanceGenerator byteItemGenerator = provider.GetInstanceGenerator(); public override sbyte GetInstance(Random random) { @@ -20,14 +20,5 @@ public override sbyte GetInstance(Random random) return (sbyte)byteItemGenerator.GetInstance(random); } } - - - // Constructors - - public SByteInstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - byteItemGenerator = provider.GetInstanceGenerator(); - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/SingleInstanceGenerator.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/SingleInstanceGenerator.cs index fdbaac7554..fadf8d66e3 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/SingleInstanceGenerator.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/SingleInstanceGenerator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.18 @@ -9,23 +9,14 @@ namespace Xtensive.Orm.Tests { - [Serializable] - internal class SingleInstanceGenerator : InstanceGeneratorBase + internal sealed class SingleInstanceGenerator(IInstanceGeneratorProvider provider) + : InstanceGeneratorBase(provider) { - public override float GetInstance(Random random) { unchecked { return (float)random.NextDouble(); } } - - - // Constructors - - public SingleInstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/StringInstanceGenerator.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/StringInstanceGenerator.cs index 9800e7ca33..dc35afd43d 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/StringInstanceGenerator.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/StringInstanceGenerator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.22 @@ -9,20 +9,12 @@ namespace Xtensive.Orm.Tests { - [Serializable] - internal class StringInstanceGenerator : InstanceGeneratorBase + internal sealed class StringInstanceGenerator(IInstanceGeneratorProvider provider) + : InstanceGeneratorBase(provider) { public override string GetInstance(Random random) { return "Random String " + random.Next(); } - - - // Constructors - - public StringInstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/TupleInstanceGenerator.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/TupleInstanceGenerator.cs index ff5ab8e455..3085b3f3d2 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/TupleInstanceGenerator.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/TupleInstanceGenerator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Gamzov // Created: 2008.01.30 @@ -12,12 +12,12 @@ namespace Xtensive.Orm.Tests { - [Serializable] - internal class TupleInstanceGenerator : InstanceGeneratorBase + internal class TupleInstanceGenerator(IInstanceGeneratorProvider provider) + : InstanceGeneratorBase(provider) { - private static readonly Dictionary descriptors = new Dictionary(); // Descriptor - probability + private static readonly Dictionary Descriptors = new Dictionary(); // Descriptor - probability private static readonly int commonProbability; - private readonly IInstanceGeneratorProvider provider; + private readonly IInstanceGeneratorProvider provider = provider; internal struct TupleGeneratorData { @@ -36,7 +36,7 @@ public TupleGeneratorData(IInstanceGeneratorProvider provider, Tuples.Tuple tupl public override Tuples.Tuple GetInstance(Random random) { int position = random.Next(0, commonProbability); - foreach (KeyValuePair descriptor in descriptors) { + foreach (KeyValuePair descriptor in Descriptors) { if (position <= descriptor.Value) { Type[] types = descriptor.Key; Tuples.Tuple tuple = Tuples.Tuple.Create(types); @@ -53,24 +53,12 @@ public override Tuples.Tuple GetInstance(Random random) return null; } - - // Constructors - - public TupleInstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - this.provider = provider; - } - static TupleInstanceGenerator() { -// descriptors.Add(new Type[] {typeof (int)}, 20); -// descriptors.Add(new Type[] {typeof (Guid)}, 20); - descriptors.Add(new Type[] {typeof (long), typeof(int), typeof(string), typeof(bool), typeof(decimal)}, 50); -// descriptors.Add(new Type[] {typeof (long), typeof (Guid)}, 20); -// descriptors.Add(new Type[] {typeof (long), typeof (Guid), typeof (byte)}, 10); - foreach (KeyValuePair descriptor in descriptors) + Descriptors.Add([typeof (long), typeof(int), typeof(string), typeof(bool), typeof(decimal)], 50); + foreach (KeyValuePair descriptor in Descriptors) { commonProbability += descriptor.Value; + } } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/UInt16InstanceGenerator.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/UInt16InstanceGenerator.cs index aa9573ebb1..408ae643e1 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/UInt16InstanceGenerator.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/UInt16InstanceGenerator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.18 @@ -9,8 +9,8 @@ namespace Xtensive.Orm.Tests { - [Serializable] - internal class UInt16InstanceGenerator : WrappingInstanceGenerator + internal sealed class UInt16InstanceGenerator(IInstanceGeneratorProvider provider) + : WrappingInstanceGenerator(provider) { public override ushort GetInstance(Random random) { @@ -18,13 +18,5 @@ public override ushort GetInstance(Random random) return (ushort)BaseGenerator.GetInstance(random); } } - - - // Constructors - - public UInt16InstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - } - } + } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/UInt32InstanceGenerator.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/UInt32InstanceGenerator.cs index 82b895543f..0af18b6b09 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/UInt32InstanceGenerator.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/UInt32InstanceGenerator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.18 @@ -9,8 +9,8 @@ namespace Xtensive.Orm.Tests { - [Serializable] - internal class UInt32InstanceGenerator : WrappingInstanceGenerator + internal sealed class UInt32InstanceGenerator(IInstanceGeneratorProvider provider) + : WrappingInstanceGenerator(provider) { public override uint GetInstance(Random random) { @@ -18,13 +18,5 @@ public override uint GetInstance(Random random) return (uint)BaseGenerator.GetInstance(random); } } - - - // Constructors - - public UInt32InstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/Internals/UInt64InstanceGenerator.cs b/Orm/Xtensive.Orm.Tests.Framework/Internals/UInt64InstanceGenerator.cs index e39c8fbdc7..ef06aaea05 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/Internals/UInt64InstanceGenerator.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/Internals/UInt64InstanceGenerator.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.18 @@ -10,8 +10,8 @@ namespace Xtensive.Orm.Tests { - [Serializable] - internal class UInt64InstanceGenerator : WrappingInstanceGenerator + internal sealed class UInt64InstanceGenerator(IInstanceGeneratorProvider provider) + : WrappingInstanceGenerator(provider) { public override ulong GetInstance(Random random) { @@ -19,13 +19,5 @@ public override ulong GetInstance(Random random) return (ulong)BaseGenerator.GetInstance(random); } } - - - // Constructors - - public UInt64InstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/WrappingInstanceGenerator{T,TBase1,TBase2, TBase3}.cs b/Orm/Xtensive.Orm.Tests.Framework/WrappingInstanceGenerator{T,TBase1,TBase2, TBase3}.cs index 40747900a8..3e4c1899da 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/WrappingInstanceGenerator{T,TBase1,TBase2, TBase3}.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/WrappingInstanceGenerator{T,TBase1,TBase2, TBase3}.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alex Yakunin // Created: 2008.01.21 @@ -15,37 +15,26 @@ namespace Xtensive.Orm.Tests /// First base (wrapped) type. /// Second base (wrapped) type. /// Third base (wrapped) type. - [Serializable] - public abstract class WrappingInstanceGenerator : InstanceGeneratorBase + /// + /// + /// + /// Instance generator provider this generator is bound to. + public abstract class WrappingInstanceGenerator(IInstanceGeneratorProvider provider) + : InstanceGeneratorBase(provider) { /// /// Generator for the first base (wrapped) type. /// - protected readonly IInstanceGenerator BaseGenerator1; + protected readonly IInstanceGenerator BaseGenerator1 = provider.GetInstanceGenerator(); /// /// Generator for the second base (wrapped) type. /// - protected readonly IInstanceGenerator BaseGenerator2; + protected readonly IInstanceGenerator BaseGenerator2 = provider.GetInstanceGenerator(); /// /// Generator for the third base (wrapped) type. /// - protected readonly IInstanceGenerator BaseGenerator3; - - - // Constructors - - /// - /// - /// - /// Instance generator provider this generator is bound to. - public WrappingInstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - BaseGenerator1 = provider.GetInstanceGenerator(); - BaseGenerator2 = provider.GetInstanceGenerator(); - BaseGenerator3 = provider.GetInstanceGenerator(); - } + protected readonly IInstanceGenerator BaseGenerator3 = provider.GetInstanceGenerator(); } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/WrappingInstanceGenerator{T,TBase1,TBase2}.cs b/Orm/Xtensive.Orm.Tests.Framework/WrappingInstanceGenerator{T,TBase1,TBase2}.cs index 2c9fdd6537..c4b546e22d 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/WrappingInstanceGenerator{T,TBase1,TBase2}.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/WrappingInstanceGenerator{T,TBase1,TBase2}.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alex Yakunin // Created: 2008.01.21 @@ -14,31 +14,21 @@ namespace Xtensive.Orm.Tests /// The type to generate random instances for. /// First base (wrapped) type. /// Second base (wrapped) type. - [Serializable] - public abstract class WrappingInstanceGenerator : InstanceGeneratorBase + /// + /// + /// + /// Instance generator provider this generator is bound to. + public abstract class WrappingInstanceGenerator(IInstanceGeneratorProvider provider) + : InstanceGeneratorBase(provider) { /// /// Generator for the first base (wrapped) type. /// - protected readonly IInstanceGenerator BaseGenerator1; + protected readonly IInstanceGenerator BaseGenerator1 = provider.GetInstanceGenerator(); /// /// Generator for the first base (wrapped) type. /// - protected readonly IInstanceGenerator BaseGenerator2; - - - // Constructors - - /// - /// - /// - /// Instance generator provider this generator is bound to. - public WrappingInstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - BaseGenerator1 = provider.GetInstanceGenerator(); - BaseGenerator2 = provider.GetInstanceGenerator(); - } + protected readonly IInstanceGenerator BaseGenerator2 = provider.GetInstanceGenerator(); } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Framework/WrappingInstanceGenerator{T,TBase}.cs b/Orm/Xtensive.Orm.Tests.Framework/WrappingInstanceGenerator{T,TBase}.cs index 40529e185d..38a983518e 100644 --- a/Orm/Xtensive.Orm.Tests.Framework/WrappingInstanceGenerator{T,TBase}.cs +++ b/Orm/Xtensive.Orm.Tests.Framework/WrappingInstanceGenerator{T,TBase}.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alex Yakunin // Created: 2008.01.21 @@ -13,25 +13,16 @@ namespace Xtensive.Orm.Tests /// /// The type to generate random instances for. /// Base (wrapped) type. - [Serializable] - public abstract class WrappingInstanceGenerator : InstanceGeneratorBase + /// + /// + /// + /// Instance generator provider this generator is bound to. + public abstract class WrappingInstanceGenerator(IInstanceGeneratorProvider provider) + : InstanceGeneratorBase(provider) { /// /// Generator for base (wrapped) type. /// - protected readonly IInstanceGenerator BaseGenerator; - - - // Constructors - - /// - /// - /// - /// Instance generator provider this generator is bound to. - public WrappingInstanceGenerator(IInstanceGeneratorProvider provider) - : base(provider) - { - BaseGenerator = provider.GetInstanceGenerator(); - } + protected readonly IInstanceGenerator BaseGenerator = provider.GetInstanceGenerator(); } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests.Sql/IndexTest.cs b/Orm/Xtensive.Orm.Tests.Sql/IndexTest.cs index 7b8c146d12..04af6345cd 100644 --- a/Orm/Xtensive.Orm.Tests.Sql/IndexTest.cs +++ b/Orm/Xtensive.Orm.Tests.Sql/IndexTest.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Sql { - [Serializable] [TestFixture] public abstract class IndexTest : SqlTest { diff --git a/Orm/Xtensive.Orm.Tests.Sql/MySQL/MiscTests.cs b/Orm/Xtensive.Orm.Tests.Sql/MySQL/MiscTests.cs index 875ccd4f52..89cb5ee080 100644 --- a/Orm/Xtensive.Orm.Tests.Sql/MySQL/MiscTests.cs +++ b/Orm/Xtensive.Orm.Tests.Sql/MySQL/MiscTests.cs @@ -1,18 +1,12 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2011-2025 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Malisa Ncube // Created: 2011.03.17 using System; -using System.Collections.Generic; -using System.Data; using System.Data.Common; -using System.Diagnostics; -using System.IO; using System.Linq; -using System.Runtime.Serialization.Formatters.Binary; -using System.Text; using NUnit.Framework; using Xtensive.Collections; using Xtensive.Sql; @@ -60,22 +54,15 @@ public void ImplicitConversionTest() } [Test] - public void ArrayTest()//TODO: Find reason why this pattern is structured like this.(Malisa) + public void ArrayTest() { SqlArray i = SqlDml.Array(new int[] { 1, 2 }); i.Values[0] = 10; SqlSelect select = SqlDml.Select(); select.Where = SqlDml.In(1, i); - using (var mStream = new MemoryStream()) { - var formatter = new BinaryFormatter(); - formatter.Serialize(mStream, select); - - _ = mStream.Seek(0, SeekOrigin.Begin); - select = (SqlSelect) formatter.Deserialize(mStream); - } - Console.WriteLine(SqlDriver.Compile(select).GetCommandText()); + } [Test] diff --git a/Orm/Xtensive.Orm.Tests.Sql/SqlServer/IndexTest.cs b/Orm/Xtensive.Orm.Tests.Sql/SqlServer/IndexTest.cs index 79560215fd..578ffe5085 100644 --- a/Orm/Xtensive.Orm.Tests.Sql/SqlServer/IndexTest.cs +++ b/Orm/Xtensive.Orm.Tests.Sql/SqlServer/IndexTest.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Sql.SqlServer { - [Serializable] public class IndexTest2005 : IndexTest { protected override void CreateTable() diff --git a/Orm/Xtensive.Orm.Tests.Sql/SqlServer/MiscTests.cs b/Orm/Xtensive.Orm.Tests.Sql/SqlServer/MiscTests.cs index a8e1e014ed..9ead6b1cf2 100644 --- a/Orm/Xtensive.Orm.Tests.Sql/SqlServer/MiscTests.cs +++ b/Orm/Xtensive.Orm.Tests.Sql/SqlServer/MiscTests.cs @@ -4,14 +4,11 @@ using System; using System.Data; -using System.IO; -using System.Runtime.Serialization.Formatters.Binary; using NUnit.Framework; using Xtensive.Collections; using Xtensive.Sql; using Xtensive.Sql.Compiler; using Xtensive.Sql.Dml; -using System.Data.Common; using System.Linq; using Xtensive.Sql.Model; @@ -71,14 +68,6 @@ public void ArrayTest() SqlSelect select = SqlDml.Select(); select.Where = SqlDml.In(1, i); - using (var mStream = new MemoryStream()) { - var formatter = new BinaryFormatter(); - formatter.Serialize(mStream, select); - - _ = mStream.Seek(0, SeekOrigin.Begin); - select = (SqlSelect) formatter.Deserialize(mStream); - } - Console.WriteLine(sqlDriver.Compile(select).GetCommandText()); } @@ -139,7 +128,7 @@ public void CircularReferencesTest() SqlBinary rb = b + 3; rb.Left.ReplaceWith(rb); select.Where = rb > 1; - Assert.Throws(() => Console.WriteLine(sqlDriver.Compile(select).GetCommandText())); + _ = Assert.Throws(() => Console.WriteLine(sqlDriver.Compile(select).GetCommandText())); } [Test] diff --git a/Orm/Xtensive.Orm.Tests.Sql/Sqlite/MiscTests.cs b/Orm/Xtensive.Orm.Tests.Sql/Sqlite/MiscTests.cs index cbcd89b8a4..0c018f8454 100644 --- a/Orm/Xtensive.Orm.Tests.Sql/Sqlite/MiscTests.cs +++ b/Orm/Xtensive.Orm.Tests.Sql/Sqlite/MiscTests.cs @@ -5,11 +5,7 @@ // Created: 2011.05.13 using System; -using System.Data; using System.Data.Common; -using System.Diagnostics; -using System.IO; -using System.Runtime.Serialization.Formatters.Binary; using NUnit.Framework; using Xtensive.Sql; using Xtensive.Sql.Compiler; @@ -117,21 +113,13 @@ public void ImplicitConversionTest() } [Test] - public void ArrayTest() //TODO: Find reason why this pattern is structured like this.(Malisa) + public void ArrayTest() { SqlArray i = SqlDml.Array(new int[] { 1, 2 }); i.Values[0] = 10; SqlSelect select = SqlDml.Select(); select.Where = SqlDml.In(1, i); - using (var mStream = new MemoryStream()) { - var formatter = new BinaryFormatter(); - formatter.Serialize(mStream, select); - - _ = mStream.Seek(0, SeekOrigin.Begin); - select = (SqlSelect) formatter.Deserialize(mStream); - } - Console.WriteLine(sqlDriver.Compile(select).GetCommandText()); } diff --git a/Orm/Xtensive.Orm.Tests/Configuration/SessionInitializationTest.cs b/Orm/Xtensive.Orm.Tests/Configuration/SessionInitializationTest.cs index ca45984e4b..9781151d9b 100644 --- a/Orm/Xtensive.Orm.Tests/Configuration/SessionInitializationTest.cs +++ b/Orm/Xtensive.Orm.Tests/Configuration/SessionInitializationTest.cs @@ -36,13 +36,12 @@ public void TestSessionCache() public void TestCacheType(DomainConfiguration config, Type expectedType) { - var d = Domain.Build(config); + using (var d = Domain.Build(config)) using (var s = d.OpenSession()) { var cacheType = s.EntityStateCache.GetType(); TestLog.Debug($"Session CacheType: {cacheType.Name}"); Assert.That(cacheType.IsOfGenericType(expectedType), Is.True); } - d.DisposeSafely(); } [Test] diff --git a/Orm/Xtensive.Orm.Tests/Configuration/TypeRegistryTest.cs b/Orm/Xtensive.Orm.Tests/Configuration/TypeRegistryTest.cs index 3704766438..e28dd9905b 100644 --- a/Orm/Xtensive.Orm.Tests/Configuration/TypeRegistryTest.cs +++ b/Orm/Xtensive.Orm.Tests/Configuration/TypeRegistryTest.cs @@ -10,26 +10,21 @@ using Xtensive.Collections; using Xtensive.Orm.Configuration; using Xtensive.Orm.Tests.RegistryModel1; -using Xtensive.Orm.Tests; namespace Xtensive.Orm.Tests.RegistryModel1 { - [Serializable] public class A : Entity { } - [Serializable] public class B : A { } - [Serializable] public class C { } - [Serializable] public class D : A { } @@ -37,22 +32,18 @@ public class D : A namespace Xtensive.Orm.Tests.RegistryModel2 { - [Serializable] public class A : Entity { } - [Serializable] public class B : A { } - [Serializable] public class C { } - [Serializable] public class D : A { } diff --git a/Orm/Xtensive.Orm.Tests/Interfaces/InterfaceImplementationTest.cs b/Orm/Xtensive.Orm.Tests/Interfaces/InterfaceImplementationTest.cs index eaea1a7952..074f9c3174 100644 --- a/Orm/Xtensive.Orm.Tests/Interfaces/InterfaceImplementationTest.cs +++ b/Orm/Xtensive.Orm.Tests/Interfaces/InterfaceImplementationTest.cs @@ -71,20 +71,21 @@ public void CompsiteIndexTest() { var config = DomainConfigurationFactory.Create(); config.Types.RegisterCaching(typeof(IHasName).Assembly, typeof(IHasName).Namespace); - var domain = GetClassTableDomain(config); - using (var session = domain.OpenSession()) - using (var t = session.OpenTransaction()) { - var d = new D(); - d.Title = "A"; - d.Name = "B"; - d.Tag = "C"; - t.Complete(); - } - using (var session = domain.OpenSession()) - using (var t = session.OpenTransaction()) { - var d = session.Query.All().Single(); - Assert.That(d, Is.Not.Null); - t.Complete(); + using (var domain = GetClassTableDomain(config)) { + using (var session = domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var d = new D(); + d.Title = "A"; + d.Name = "B"; + d.Tag = "C"; + t.Complete(); + } + using (var session = domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var d = session.Query.All().Single(); + Assert.That(d, Is.Not.Null); + t.Complete(); + } } } @@ -101,11 +102,12 @@ public void InternalTest(Func generator) var config = DomainConfigurationFactory.Create(); config.Types.RegisterCaching(typeof(IHasName).Assembly, typeof(IHasName).Namespace); var domain = generator(config); + using (domain) using (var session = domain.OpenSession()) using (var t = session.OpenTransaction()) { - new A() {Name = "A"}; - new B() {Name = "B"}; - new C() {Name = "C"}; + _ = new A() { Name = "A" }; + _ = new B() { Name = "B" }; + _ = new C() { Name = "C" }; var hasNames = session.Query.All().ToList(); Assert.That(hasNames.Count, Is.EqualTo(2)); t.Complete(); diff --git a/Orm/Xtensive.Orm.Tests/Interfaces/InterfaceTest.cs b/Orm/Xtensive.Orm.Tests/Interfaces/InterfaceTest.cs index 78e17d3a91..cd03cdcd31 100644 --- a/Orm/Xtensive.Orm.Tests/Interfaces/InterfaceTest.cs +++ b/Orm/Xtensive.Orm.Tests/Interfaces/InterfaceTest.cs @@ -6,7 +6,6 @@ using System; using System.Linq; -using System.Linq.Expressions; using NUnit.Framework; using Xtensive.Orm.Configuration; using Xtensive.Orm.Tests.Interfaces.InterfaceTest_Model; @@ -37,7 +36,6 @@ public interface IAnimal : IEntity IPerson Owner { get; set; } } - [Serializable] [HierarchyRoot] public class Person1 : Entity, IPerson { @@ -51,7 +49,6 @@ public class Person1 : Entity, IPerson public IAnimal Favorite { get; set; } } - [Serializable] [HierarchyRoot] public class Person2 : Entity, IPerson { @@ -65,7 +62,6 @@ public class Person2 : Entity, IPerson public IAnimal Favorite { get; set; } } - [Serializable] [HierarchyRoot] public class Animal1 : Entity, IAnimal { @@ -77,7 +73,6 @@ public class Animal1 : Entity, IAnimal public IPerson Owner { get; set; } } - [Serializable] [HierarchyRoot] public class Animal2 : Entity, IAnimal { @@ -89,7 +84,6 @@ public class Animal2 : Entity, IAnimal public IPerson Owner { get; set; } } - [Serializable] [HierarchyRoot] public class Animal3 : Entity, IAnimal { @@ -116,50 +110,50 @@ protected override DomainConfiguration BuildConfiguration() [Test] public void MainTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - - IPerson p = new Person1(); - p.Pets.Add(new Animal1()); - p.Pets.Add(new Animal1()); - p.Pets.Add(new Animal2()); - - p = new Person2(); - p.Pets.Add(new Animal1()); - p.Pets.Add(new Animal1()); - p.Pets.Add(new Animal2()); - - Session.Current.SaveChanges(); - - p = session.Query.All().First(); - Assert.That(p.Pets.Count, Is.EqualTo(3)); - - var first = p.Pets.First(); - first.Remove(); - Assert.That(first.PersistenceState == PersistenceState.Removed, Is.True); - Assert.That(p.Pets.Contains(first), Is.False); - Assert.That(p.Pets.Count, Is.EqualTo(2)); - - p.Remove(); - session.Remove(session.Query.All()); - - new Animal1() { PetName = "A" }; - new Animal1() { PetName = "B" }; - new Animal1() { PetName = "C" }; - new Animal2() { PetName = "D" }; - new Animal2() { PetName = "E" }; - new Animal2() { PetName = "F" }; - new Animal3() { PetName = "G" }; - new Animal3() { PetName = "H" }; - new Animal3() { PetName = "J" }; - - var animals = session.Query.All(); - Assert.That(animals.Count(), Is.EqualTo(9)); - animals.Select(a => new {a.Id, a.PetName}).Where(x => x.Id != 0).ToList(); - var list = session.Query.All().Where(a => (string)a["PetName"] == "D").ToList(); - Assert.That(list.Count, Is.EqualTo(1)); - t.Complete(); - } + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + + var iP = (IPerson) new Person1(); + _ = iP.Pets.Add(new Animal1()); + _ = iP.Pets.Add(new Animal1()); + _ = iP.Pets.Add(new Animal2()); + + iP = new Person2(); + _ = iP.Pets.Add(new Animal1()); + _ = iP.Pets.Add(new Animal1()); + _ = iP.Pets.Add(new Animal2()); + + session.SaveChanges(); + + iP = session.Query.All().First(); + Assert.That(iP.Pets.Count, Is.EqualTo(3)); + + var first = iP.Pets.First(); + first.Remove(); + Assert.That(first.PersistenceState == PersistenceState.Removed, Is.True); + Assert.That(iP.Pets.Contains(first), Is.False); + Assert.That(iP.Pets.Count, Is.EqualTo(2)); + + iP.Remove(); + session.Remove(session.Query.All()); + + _ = new Animal1() { PetName = "A" }; + _ = new Animal1() { PetName = "B" }; + _ = new Animal1() { PetName = "C" }; + _ = new Animal2() { PetName = "D" }; + _ = new Animal2() { PetName = "E" }; + _ = new Animal2() { PetName = "F" }; + _ = new Animal3() { PetName = "G" }; + _ = new Animal3() { PetName = "H" }; + _ = new Animal3() { PetName = "J" }; + + var animals = session.Query.All(); + Assert.That(animals.Count(), Is.EqualTo(9)); + + _ = animals.Select(a => new { a.Id, a.PetName }).Where(x => x.Id != 0).ToList(); + var list = session.Query.All().Where(a => (string) a["PetName"] == "D").ToList(); + Assert.That(list.Count, Is.EqualTo(1)); + t.Complete(); } } } diff --git a/Orm/Xtensive.Orm.Tests/Interfaces/KeyStructureConflictTest.cs b/Orm/Xtensive.Orm.Tests/Interfaces/KeyStructureConflictTest.cs index ba93cfe3d3..6ecf70b1c6 100644 --- a/Orm/Xtensive.Orm.Tests/Interfaces/KeyStructureConflictTest.cs +++ b/Orm/Xtensive.Orm.Tests/Interfaces/KeyStructureConflictTest.cs @@ -15,7 +15,6 @@ public interface IChild : IEntity { } - [Serializable] [HierarchyRoot] public class Root1 : Entity { @@ -23,13 +22,11 @@ public class Root1 : Entity public int Id { get; private set; } } - [Serializable] public class Child1 : Root1, IChild { } - [Serializable] [HierarchyRoot] public class Root2 : Entity { @@ -37,7 +34,6 @@ public class Root2 : Entity public Guid Id { get; private set; } } - [Serializable] public class Child2 : Root2, IChild { } @@ -48,14 +44,24 @@ namespace Xtensive.Orm.Tests.Interfaces public class KeyStructureConflictTest { [Test] - public void MainTest() + public void DomainBuildTest() + { + var configuration = BuildConfiguration(); + _ = Assert.Throws(() => Domain.Build(configuration).Dispose()); + } + + [Test] + public void DomainBuildAsyncTest() + { + var configuration = BuildConfiguration(); + _ = Assert.ThrowsAsync(async () => (await Domain.BuildAsync(configuration)).Dispose()); + } + + private static DomainConfiguration BuildConfiguration() { var config = DomainConfigurationFactory.Create(); - config.Types.RegisterCaching(typeof (Root1).Assembly, typeof (Root1).Namespace); - var ex = Assert.Throws(() => Domain.Build(config)); - var message = ex.Message; - Assert.That(message.Contains("IChild") && message.Contains("different key structure") && message.Contains("Root1 & Root2"), - Is.True); + config.Types.RegisterCaching(typeof(Root1).Assembly, typeof(Root1).Namespace); + return config; } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Interfaces/TypeIdModeConflictTest.cs b/Orm/Xtensive.Orm.Tests/Interfaces/TypeIdModeConflictTest.cs index 7f1120195a..a78d302433 100644 --- a/Orm/Xtensive.Orm.Tests/Interfaces/TypeIdModeConflictTest.cs +++ b/Orm/Xtensive.Orm.Tests/Interfaces/TypeIdModeConflictTest.cs @@ -15,7 +15,6 @@ public interface IRoot : IEntity { } - [Serializable] [HierarchyRoot] public class Root1 : Entity, IRoot { @@ -23,7 +22,6 @@ public class Root1 : Entity, IRoot public int Id { get; private set; } } - [Serializable] [HierarchyRoot(IncludeTypeId = true)] public class Root2 : Entity, IRoot { @@ -37,14 +35,24 @@ namespace Xtensive.Orm.Tests.Interfaces public class TypeIdModeConflictTest { [Test] - public void MainTest() + public void DomainBuildTest() + { + var configuration = BuildConfiguration(); + _ = Assert.Throws(() => Domain.Build(configuration).Dispose()); + } + + [Test] + public void DomainBuildAsyncTest() + { + var configuration = BuildConfiguration(); + _ = Assert.ThrowsAsync(async () => (await Domain.BuildAsync(configuration)).Dispose()); + } + + private static DomainConfiguration BuildConfiguration() { var config = DomainConfigurationFactory.Create(); config.Types.RegisterCaching(typeof (Root1).Assembly, typeof (Root1).Namespace); - var ex = Assert.Throws(() => Domain.Build(config)); - var message = ex.Message; - Assert.That(message.Contains("IRoot") && message.Contains("one of which includes TypeId, but another doesn't") && message.Contains("Root1 & Root2"), - Is.True); + return config; } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Interfaces/UnusedTypeRemovalTest.cs b/Orm/Xtensive.Orm.Tests/Interfaces/UnusedTypeRemovalTest.cs index bbb7fe910a..380e6f0720 100644 --- a/Orm/Xtensive.Orm.Tests/Interfaces/UnusedTypeRemovalTest.cs +++ b/Orm/Xtensive.Orm.Tests/Interfaces/UnusedTypeRemovalTest.cs @@ -5,11 +5,9 @@ // Created: 2009.09.14 using System; +using System.Threading.Tasks; using NUnit.Framework; -using Xtensive.Orm.Tests; -using Xtensive.Orm; using Xtensive.Orm.Configuration; -using Xtensive.Orm.Model; using Xtensive.Orm.Tests.Interfaces.UnusedTypeRemovalTestModel; namespace Xtensive.Orm.Tests.Interfaces.UnusedTypeRemovalTestModel @@ -29,7 +27,6 @@ public interface IThird : IFirst } - [Serializable] // No [HierarchyRoot] here public class Third : Entity, IThird { @@ -54,15 +51,24 @@ namespace Xtensive.Orm.Tests.Interfaces public class UnusedTypeRemovalTest { [Test] - public void MainTest() + public void DomainBuildTest() + { + var configuration = BuildConfiguration(); + _ = Assert.Throws(() => Domain.Build(configuration).Dispose()); + } + + [Test] + public void DomainBuildAsyncTest() + { + var configuration = BuildConfiguration(); + _ = Assert.ThrowsAsync(async () => (await Domain.BuildAsync(configuration)).Dispose()); + } + + private static DomainConfiguration BuildConfiguration() { var config = DomainConfigurationFactory.Create(); config.Types.RegisterCaching(typeof(IFirst).Assembly, typeof(IFirst).Namespace); - - var ex = Assert.Throws(() => Domain.Build(config)); - var message = ex.Message; - Assert.That(message.Contains("ISecond") && message.Contains("don't belong") && message.Contains("hierarchy"), - Is.True); + return config; } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Issues/CustomCompilerException.cs b/Orm/Xtensive.Orm.Tests/Issues/CustomCompilerException.cs index fe17308ca6..c3559e1856 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/CustomCompilerException.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/CustomCompilerException.cs @@ -6,6 +6,7 @@ using System; using System.Diagnostics; +using System.Linq.Expressions; using NUnit.Framework; using Xtensive.Core; using Xtensive.Linq; @@ -15,125 +16,116 @@ namespace Xtensive.Orm.Tests.Issues { - using System.Linq.Expressions; - namespace ProjectCustomCompilerException.Model + namespace ProjectCustomCompilerException.Model + { + [HierarchyRoot] + public abstract class FundBase : Entity { - [Serializable] - [HierarchyRoot] - public abstract class FundBase : Entity + [Field, Key] + public int Id { get; private set; } + + private static readonly Expression> VirtualJuridicalPersonExpression = + obj => + (obj is MutualFund) + ? (obj as MutualFund).ManagementCompany + : (obj is MilitaryMortgage) + ? (obj as MilitaryMortgage).JuridicalPerson + : (obj is SelfRegulatoryOrganization) + ? (obj as SelfRegulatoryOrganization).Organization + : (obj is PrivatePensionFund) + ? (obj as PrivatePensionFund).JuridicalPerson + : (obj is ShareholderInvestmentFund) + ? (obj as ShareholderInvestmentFund).JuridicalPerson + : null; + + private static readonly Func VirtualJuridicalPersonCompiled = + VirtualJuridicalPersonExpression.Compile(); + + public JuridicalPerson VirtualJuridicalPerson + { + get { return VirtualJuridicalPersonCompiled(this); } + } + + [CompilerContainer(typeof(Expression))] + public static class CustomLinqCompilerContainer + { + /// Required to use a virtual field + /// The assignment expression. + /// Expression with bound parameters + [Compiler(typeof(FundBase), "VirtualJuridicalPerson", TargetKind.PropertyGet)] + public static Expression Depositary(Expression assignmentExpression) { - [Field, Key] - public int Id { get; private set; } - - private static readonly Expression> VirtualJuridicalPersonExpression = - obj => - (obj is MutualFund) - ? (obj as MutualFund).ManagementCompany - : (obj is MilitaryMortgage) - ? (obj as MilitaryMortgage).JuridicalPerson - : (obj is SelfRegulatoryOrganization) - ? (obj as SelfRegulatoryOrganization).Organization - : (obj is PrivatePensionFund) - ? (obj as PrivatePensionFund).JuridicalPerson - : (obj is ShareholderInvestmentFund) - ? (obj as ShareholderInvestmentFund).JuridicalPerson - : null; - - private static readonly Func VirtualJuridicalPersonCompiled = - VirtualJuridicalPersonExpression.Compile(); - - public JuridicalPerson VirtualJuridicalPerson - { - get { return VirtualJuridicalPersonCompiled(this); } - } - - [CompilerContainer(typeof(Expression))] - public static class CustomLinqCompilerContainer - { - /// Required to use a virtual field - /// The assignment expression. - /// Expression with bound parameters - [Compiler(typeof(FundBase), "VirtualJuridicalPerson", TargetKind.PropertyGet)] - public static Expression Depositary(Expression assignmentExpression) - { - return VirtualJuridicalPersonExpression.BindParameters(assignmentExpression); - } - } + return VirtualJuridicalPersonExpression.BindParameters(assignmentExpression); } + } + } - [Serializable] - public class MutualFund : FundBase - { - /// - /// Fund's management company - /// - [Field(Nullable = false)] - public JuridicalPerson ManagementCompany { get; set; } - } + public class MutualFund : FundBase + { + /// + /// Fund's management company + /// + [Field(Nullable = false)] + public JuridicalPerson ManagementCompany { get; set; } + } - [Serializable] - public class MilitaryMortgage : FundBase - { - [Field(Nullable = false)] - public JuridicalPerson JuridicalPerson { get; set; } - } + public class MilitaryMortgage : FundBase + { + [Field(Nullable = false)] + public JuridicalPerson JuridicalPerson { get; set; } + } - [Serializable] - public class SelfRegulatoryOrganization : FundBase - { - [Field(Nullable = false)] - public JuridicalPerson Organization { get; set; } - } - [Serializable] - public class PrivatePensionFund : FundBase - { - [Field(Nullable = false)] - public JuridicalPerson JuridicalPerson { get; set; } - } + public class SelfRegulatoryOrganization : FundBase + { + [Field(Nullable = false)] + public JuridicalPerson Organization { get; set; } + } - [Serializable] - public class ShareholderInvestmentFund : FundBase - { - [Field(Nullable = false)] - public JuridicalPerson JuridicalPerson { get; set; } - } + public class PrivatePensionFund : FundBase + { + [Field(Nullable = false)] + public JuridicalPerson JuridicalPerson { get; set; } + } - [Serializable] - [HierarchyRoot] - public partial class JuridicalPerson : Entity - { - [Field, Key] - public int Id { get; private set; } + public class ShareholderInvestmentFund : FundBase + { + [Field(Nullable = false)] + public JuridicalPerson JuridicalPerson { get; set; } + } - [Field(Nullable = false, Length = 400)] - public string FullName { get; set; } - } + [HierarchyRoot] + public partial class JuridicalPerson : Entity + { + [Field, Key] + public int Id { get; private set; } + + [Field(Nullable = false, Length = 400)] + public string FullName { get; set; } } + } - public class CustomCompilerException : AutoBuildTest + public class CustomCompilerException : AutoBuildTest + { + protected override DomainConfiguration BuildConfiguration() { - protected override DomainConfiguration BuildConfiguration() - { - var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof (FundBase).Assembly, typeof (FundBase).Namespace); - return config; - } + var config = base.BuildConfiguration(); + config.Types.RegisterCaching(typeof(FundBase).Assembly, typeof(FundBase).Namespace); + return config; + } - [Test] - public void MainTest() - { - Require.ProviderIsNot(StorageProvider.Sqlite, "parser stack overflow"); - - using (var session = Domain.OpenSession()) - { - using (var transactionScope = session.OpenTransaction()) - { - var result = session.Query.All() - .Where(q => q.VirtualJuridicalPerson != null && q.VirtualJuridicalPerson.FullName != null && q.VirtualJuridicalPerson.FullName.StartsWith("qweqwe")) - .ToArray(); - } - } + [Test] + public void MainTest() + { + Require.ProviderIsNot(StorageProvider.Sqlite, "parser stack overflow"); + + using (var session = Domain.OpenSession()) { + using (var transactionScope = session.OpenTransaction()) { + var result = session.Query.All() + .Where(q => q.VirtualJuridicalPerson != null && q.VirtualJuridicalPerson.FullName != null && q.VirtualJuridicalPerson.FullName.StartsWith("qweqwe")) + .ToArray(); } + } } + } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Issues/CustomCompilerFeatureTest.cs b/Orm/Xtensive.Orm.Tests/Issues/CustomCompilerFeatureTest.cs index cc334f624f..e0b4fdf673 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/CustomCompilerFeatureTest.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/CustomCompilerFeatureTest.cs @@ -33,7 +33,6 @@ public static Expression ITestRegionName(Expression _this) } } - [Serializable] [HierarchyRoot] public class Person : Entity, IHasVirtualFields { @@ -79,7 +78,6 @@ public Person(Session session) } } - [Serializable] [HierarchyRoot] public class Company : Entity, IHasVirtualFields { @@ -117,7 +115,6 @@ public string RegionName #endregion } - [Serializable] [HierarchyRoot] public class Address : Structure { @@ -125,7 +122,6 @@ public class Address : Structure public Region Region { get; set; } } - [Serializable] [HierarchyRoot] public class Region : Entity { @@ -239,7 +235,6 @@ public Enterprise(Session session) } } - [Serializable] [HierarchyRoot] public class BusinessAddress : Structure { @@ -247,7 +242,6 @@ public class BusinessAddress : Structure public Area Area { get; set; } } - [Serializable] [HierarchyRoot] public class Area : Entity { @@ -264,7 +258,6 @@ public Area(Session session) } } - [Serializable] public class CustomCompilerFeatureTest : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0001_MultipleHierarchyRootAttributes.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0001_MultipleHierarchyRootAttributes.cs index 67ddd474d5..e76ef5e3ef 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0001_MultipleHierarchyRootAttributes.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0001_MultipleHierarchyRootAttributes.cs @@ -5,15 +5,12 @@ // Created: 2008.10.16 using System; -using System.Reflection; using NUnit.Framework; -using Xtensive.Orm.Tests; using Xtensive.Orm.Configuration; using Xtensive.Orm.Tests.Issues.Issue0001_Model; namespace Xtensive.Orm.Tests.Issues.Issue0001_Model { - [Serializable] [HierarchyRoot] public class X : Entity { @@ -21,7 +18,6 @@ public class X : Entity public int ID { get; private set; } } - [Serializable] [HierarchyRoot] public class Y : X { @@ -31,20 +27,28 @@ public class Y : X namespace Xtensive.Orm.Tests.Issues { [TestFixture] - public class Issue0001_MultipleHierarchyRootAttributes : AutoBuildTest + public class Issue0001_MultipleHierarchyRootAttributes { - protected override DomainConfiguration BuildConfiguration() + [Test] + public void DomainBuildTest() { - var config = base.BuildConfiguration(); - config.Types.RegisterCaching(Assembly.GetExecutingAssembly(), typeof (X).Namespace); - return config; + var configuration = BuildConfiguration(); + _ = Assert.Throws(() => Domain.Build(configuration).Dispose()); } - protected override Domain BuildDomain(DomainConfiguration configuration) + [Test] + public void DomainBuildAsyncTest() { - Domain result = null; - AssertEx.Throws(() => result = base.BuildDomain(configuration)); - return result; + var configuration = BuildConfiguration(); + _ = Assert.ThrowsAsync(async () => (await Domain.BuildAsync(configuration)).Dispose()); + } + + private static DomainConfiguration BuildConfiguration() + { + var config = DomainConfigurationFactory.Create(); + config.Types.Register(typeof (X)); + config.Types.Register(typeof (Y)); + return config; } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0002_PrimaryKeyWithLazyLoad.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0002_PrimaryKeyWithLazyLoad.cs index d96bb5543b..679dd4455e 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0002_PrimaryKeyWithLazyLoad.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0002_PrimaryKeyWithLazyLoad.cs @@ -5,15 +5,12 @@ // Created: 2008.10.16 using System; -using System.Reflection; using NUnit.Framework; -using Xtensive.Orm.Tests; using Xtensive.Orm.Configuration; using Xtensive.Orm.Tests.Issues.Issue0002_Model; namespace Xtensive.Orm.Tests.Issues.Issue0002_Model { - [Serializable] [HierarchyRoot] public class X : Entity { @@ -25,20 +22,27 @@ public class X : Entity namespace Xtensive.Orm.Tests.Issues { [TestFixture] - public class Issue0002_PrimaryKeyWithLazyLoad : AutoBuildTest + public class Issue0002_PrimaryKeyWithLazyLoad { - protected override DomainConfiguration BuildConfiguration() + [Test] + public void DomainBuildTest() { - var config = base.BuildConfiguration(); - config.Types.RegisterCaching(Assembly.GetExecutingAssembly(), typeof(X).Namespace); - return config; + var configuration = BuildConfiguration(); + _ = Assert.Throws(() => Domain.Build(configuration).Dispose()); } - protected override Domain BuildDomain(DomainConfiguration configuration) + [Test] + public void DomainBuildAsyncTest() { - Domain result = null; - AssertEx.Throws(() => result = base.BuildDomain(configuration)); - return result; + var configuration = BuildConfiguration(); + _ = Assert.ThrowsAsync(async () => (await Domain.BuildAsync(configuration)).Dispose()); + } + + private static DomainConfiguration BuildConfiguration() + { + var config = DomainConfigurationFactory.Create(); + config.Types.Register(typeof(X)); + return config; } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0003_NullablePrimaryKey.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0003_NullablePrimaryKey.cs index deb71246ad..f473469db4 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0003_NullablePrimaryKey.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0003_NullablePrimaryKey.cs @@ -5,16 +5,12 @@ // Created: 2008.10.16 using System; -using System.Reflection; using NUnit.Framework; -using Xtensive.Core; -using Xtensive.Orm.Tests; using Xtensive.Orm.Configuration; using Xtensive.Orm.Tests.Issues.Issue0003_Model; namespace Xtensive.Orm.Tests.Issues.Issue0003_Model { - [Serializable] [HierarchyRoot] public class X : Entity { @@ -26,20 +22,27 @@ public class X : Entity namespace Xtensive.Orm.Tests.Issues { [TestFixture] - public class Issue0003_NullablePrimaryKey : AutoBuildTest + public class Issue0003_NullablePrimaryKey { - protected override DomainConfiguration BuildConfiguration() + [Test] + public void DomainBuildTest() { - var config = base.BuildConfiguration(); - config.Types.RegisterCaching(Assembly.GetExecutingAssembly(), typeof(X).Namespace); - return config; + var configuration = BuildConfiguration(); + _ = Assert.Throws(() => Domain.Build(configuration).Dispose()); } - protected override Domain BuildDomain(DomainConfiguration configuration) + [Test] + public void DomainBuildAsyncTest() { - Domain domain = null; - AssertEx.Throws(() => domain = base.BuildDomain(configuration)); - return domain; + var configuration = BuildConfiguration(); + _ = Assert.ThrowsAsync(async () => (await Domain.BuildAsync(configuration)).Dispose()); + } + + private static DomainConfiguration BuildConfiguration() + { + var config = DomainConfigurationFactory.Create(); + config.Types.Register(typeof(X)); + return config; } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0004_PairAttributeMisusageIsNotHandled.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0004_PairAttributeMisusageIsNotHandled.cs index 487cb9500c..e305976be8 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0004_PairAttributeMisusageIsNotHandled.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0004_PairAttributeMisusageIsNotHandled.cs @@ -5,16 +5,12 @@ // Created: 2008.11.26 using System; -using System.Reflection; using NUnit.Framework; -using Xtensive.Core; -using Xtensive.Orm.Tests; using Xtensive.Orm.Configuration; using Xtensive.Orm.Tests.Issue0004_Model; namespace Xtensive.Orm.Tests.Issue0004_Model { - [Serializable] [HierarchyRoot] public class User : Entity { @@ -28,7 +24,6 @@ public class User : Entity public EntitySet Notifications { get; set; } } - [Serializable] [HierarchyRoot] public class Notification : Entity { @@ -45,22 +40,30 @@ public class Notification : Entity namespace Xtensive.Orm.Tests.Issues { - [Ignore("No more actual")] - public class Issue0004_PairAttributeMisusageIsNotHandled : AutoBuildTest + public class Issue0004_PairAttributeMisusageIsNotHandled { - protected override DomainConfiguration BuildConfiguration() + [Test] + public void DomainBuildTest() { - var config = base.BuildConfiguration(); - config.Types.RegisterCaching(Assembly.GetExecutingAssembly(), typeof(User).Namespace); - return config; + var configuration = BuildConfiguration(); + Assert.DoesNotThrow(() => Domain.Build(configuration).Dispose()); + } + + [Test] + public void DomainBuildAsyncTest() + { + var configuration = BuildConfiguration(); + Assert.DoesNotThrowAsync(async () => (await Domain.BuildAsync(configuration)).Dispose()); } - protected override Domain BuildDomain(DomainConfiguration configuration) + private static DomainConfiguration BuildConfiguration() { - Domain result = null; - AssertEx.Throws(() => result = base.BuildDomain(configuration)); - return result; + var config = DomainConfigurationFactory.Create(); + config.Types.Register(typeof(User)); + config.Types.Register(typeof(Notification)); + return config; } + } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0007_InvalidNotNullConstraint.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0007_InvalidNotNullConstraint.cs index 4a67db0c8e..76c5a78e72 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0007_InvalidNotNullConstraint.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0007_InvalidNotNullConstraint.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0007_Model { - [Serializable] [HierarchyRoot] public class Person : Entity { @@ -26,7 +25,6 @@ public class Person : Entity public City City { get; set; } } - [Serializable] public class Address : Structure { [Field] @@ -36,7 +34,6 @@ public class Address : Structure public int House { get; set; } } - [Serializable] [HierarchyRoot] public class City : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0009_2SymmetricTablesForMNRelationship.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0009_2SymmetricTablesForMNRelationship.cs index acebf089a0..4748bfed98 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0009_2SymmetricTablesForMNRelationship.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0009_2SymmetricTablesForMNRelationship.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0009_Model { - [Serializable] [HierarchyRoot] public class Book : Entity { @@ -23,7 +22,6 @@ public class Book : Entity public EntitySet Authors { get; private set; } } - [Serializable] [HierarchyRoot] public class Author : Entity { @@ -43,7 +41,8 @@ public class Issue0009_2SymmetricTablesForMNRelationship : AutoBuildTest protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); - config.Types.RegisterCaching(Assembly.GetExecutingAssembly(), typeof(Book).Namespace); + config.Types.Register(typeof(Book)); + config.Types.Register(typeof(Author)); return config; } @@ -54,7 +53,7 @@ public void MainTest() using (var t = session.OpenTransaction()) { var book = new Book(); var author = new Author(); - book.Authors.Add(author); + _ = book.Authors.Add(author); Assert.That(book.Authors.Count, Is.EqualTo(1)); Assert.That(author.Books.Count, Is.EqualTo(1)); diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0012_TakeSkipSequence.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0012_TakeSkipSequence.cs index 08b4137a36..cffc0e0c90 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0012_TakeSkipSequence.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0012_TakeSkipSequence.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0012_Model { - [Serializable] [HierarchyRoot] public class MyEntity : Entity { @@ -46,7 +45,7 @@ protected override void CheckRequirements() protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof (MyEntity).Assembly, typeof (MyEntity).Namespace); + config.Types.Register(typeof(MyEntity)); return config; } @@ -63,12 +62,12 @@ public void MainTest() .Indexes.PrimaryIndex.GetQuery() .Filter(t => t.GetValue(0) == e1.Id || t.GetValue(0) == e2.Id); - Assert.That(rsMyEntities.Count(Session.Current), Is.EqualTo(2)); + Assert.That(rsMyEntities.Count(session), Is.EqualTo(2)); - Assert.That(rsMyEntities.Take(1).Skip(1).Count(Session.Current), Is.EqualTo(0)); - Assert.That(rsMyEntities.Skip(1).Take(1).Count(Session.Current), Is.EqualTo(1)); - Assert.That(rsMyEntities.Take(1).Take(2).Count(Session.Current), Is.EqualTo(1)); - Assert.That(rsMyEntities.Skip(1).Skip(1).Count(Session.Current), Is.EqualTo(0)); + Assert.That(rsMyEntities.Take(1).Skip(1).Count(session), Is.EqualTo(0)); + Assert.That(rsMyEntities.Skip(1).Take(1).Count(session), Is.EqualTo(1)); + Assert.That(rsMyEntities.Take(1).Take(2).Count(session), Is.EqualTo(1)); + Assert.That(rsMyEntities.Skip(1).Skip(1).Count(session), Is.EqualTo(0)); trs.Complete(); } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0013_SqlBuilderRequestTaskBug.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0013_SqlBuilderRequestTaskBug.cs index 1edd2cc84f..79d94d367d 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0013_SqlBuilderRequestTaskBug.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0013_SqlBuilderRequestTaskBug.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0013_Model { - [Serializable] [HierarchyRoot] public class SqlTaskEntity : Entity { @@ -42,7 +41,7 @@ public class Issue0013_SqlBuilderRequestTaskBug : AutoBuildTest protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof (SqlTaskEntity).Assembly, typeof (SqlTaskEntity).Namespace); + config.Types.Register(typeof(SqlTaskEntity)); return config; } @@ -51,21 +50,21 @@ public void MainTest() { using (var session = Domain.OpenSession()) { SqlTaskEntity e1; - using (TransactionScope trs = session.OpenTransaction()) { + using (var trs = session.OpenTransaction()) { e1 = new SqlTaskEntity(); //insert - Session.Current.SaveChanges(); + session.SaveChanges(); e1.Field5 = 5; //update trs.Complete(); } - using (TransactionScope trs = session.OpenTransaction()) { + using (var trs = session.OpenTransaction()) { e1.Field1 = 1; e1.Field3 = 3; //update trs.Complete(); } - using (TransactionScope trs = session.OpenTransaction()) { + using (var trs = session.OpenTransaction()) { Assert.That(e1.Field1, Is.EqualTo(1)); Assert.That(e1.Field3, Is.EqualTo(3)); } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0014_SymmetricRelationshipIsUnsupported.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0014_SymmetricRelationshipIsUnsupported.cs index 99807483c0..5cec69e3a9 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0014_SymmetricRelationshipIsUnsupported.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0014_SymmetricRelationshipIsUnsupported.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0014_Model { - [Serializable] [HierarchyRoot] public class Person : Entity { @@ -39,7 +38,7 @@ public class Issue0014_SymmetricRelationshipIsUnsupported : AutoBuildTest protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); - config.Types.RegisterCaching(Assembly.GetExecutingAssembly(), typeof(Person).Namespace); + config.Types.Register(typeof(Person)); return config; } @@ -52,69 +51,66 @@ protected override void CheckRequirements() [Test] public void ManyToManyTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - Person first = new Person {Name = "First"}; - Person second = new Person {Name = "Second"}; - Person third = new Person {Name = "Third"}; - - first.Friends.Add(second); - first.Friends.Add(third); - Assert.That(first.Friends.Count, Is.EqualTo(2)); - Assert.That(second.Friends.Count, Is.EqualTo(1)); - Assert.That(third.Friends.Count, Is.EqualTo(1)); - Assert.That(first.Friends.First().Friends.First(), Is.SameAs(first)); - Assert.That(first.Friends.Skip(1).First().Friends.First(), Is.SameAs(first)); - - first.Friends.Add(first); - Assert.That(first.Friends.Count, Is.EqualTo(3)); - - first.Friends.Remove(first); - Assert.That(first.Friends.Count, Is.EqualTo(2)); - - first.Friends.Clear(); - second.Friends.Clear(); - third.Friends.Clear(); - Session.Current.SaveChanges(); - - first.Friends.Add(first); - - t.Complete(); - } + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var first = new Person { Name = "First" }; + var second = new Person { Name = "Second" }; + var third = new Person { Name = "Third" }; + + _ = first.Friends.Add(second); + _ = first.Friends.Add(third); + Assert.That(first.Friends.Count, Is.EqualTo(2)); + Assert.That(second.Friends.Count, Is.EqualTo(1)); + Assert.That(third.Friends.Count, Is.EqualTo(1)); + Assert.That(first.Friends.First().Friends.First(), Is.SameAs(first)); + Assert.That(first.Friends.Skip(1).First().Friends.First(), Is.SameAs(first)); + + _ = first.Friends.Add(first); + Assert.That(first.Friends.Count, Is.EqualTo(3)); + + _ = first.Friends.Remove(first); + Assert.That(first.Friends.Count, Is.EqualTo(2)); + + first.Friends.Clear(); + second.Friends.Clear(); + third.Friends.Clear(); + session.SaveChanges(); + + _ = first.Friends.Add(first); + + t.Complete(); } } - [Test] public void OneToOneTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - Person first = new Person {Name = "First"}; - Person second = new Person {Name = "Second"}; - Person third = new Person {Name = "Third"}; + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var first = new Person { Name = "First" }; + var second = new Person { Name = "Second" }; + var third = new Person { Name = "Third" }; - first.BestFriend = second; - Assert.That(second, Is.SameAs(first.BestFriend)); - Assert.That(second.BestFriend, Is.SameAs(first)); + first.BestFriend = second; + Assert.That(second, Is.SameAs(first.BestFriend)); + Assert.That(second.BestFriend, Is.SameAs(first)); - first.BestFriend = third; - Assert.That(third, Is.SameAs(first.BestFriend)); - Assert.That(third.BestFriend, Is.SameAs(first)); - Assert.That(second.BestFriend, Is.SameAs(null)); + first.BestFriend = third; + Assert.That(third, Is.SameAs(first.BestFriend)); + Assert.That(third.BestFriend, Is.SameAs(first)); + Assert.That(second.BestFriend, Is.SameAs(null)); - first.BestFriend = null; - Assert.That(first.BestFriend, Is.SameAs(null)); - Assert.That(third.BestFriend, Is.SameAs(null)); + first.BestFriend = null; + Assert.That(first.BestFriend, Is.SameAs(null)); + Assert.That(third.BestFriend, Is.SameAs(null)); - first.BestFriend = first; - Assert.That(first, Is.SameAs(first.BestFriend)); + first.BestFriend = first; + Assert.That(first, Is.SameAs(first.BestFriend)); - first.BestFriend = null; - Assert.That(first.BestFriend, Is.SameAs(null)); + first.BestFriend = null; + Assert.That(first.BestFriend, Is.SameAs(null)); - t.Complete(); - } + t.Complete(); } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0016_FieldOfInterfaceType.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0016_FieldOfInterfaceType.cs index 47a0adf380..5934530000 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0016_FieldOfInterfaceType.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0016_FieldOfInterfaceType.cs @@ -17,7 +17,6 @@ public interface IMaster : IEntity Slave Slave { get; set; } } - [Serializable] [HierarchyRoot] public class Master : Entity, IMaster { @@ -27,7 +26,6 @@ public class Master : Entity, IMaster public Slave Slave { get; set; } } - [Serializable] [HierarchyRoot] public class Slave : Entity { @@ -46,31 +44,31 @@ public class Issue0016_FieldOfInterfaceType : AutoBuildTest protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof (Slave).Assembly, typeof (Slave).Namespace); + config.Types.Register(typeof(Master)); + config.Types.Register(typeof(Slave)); return config; } [Test] public void MainTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { - Master m = new Master(); - Slave s = new Slave(); - m.Slave = s; - Assert.That(m.Slave, Is.Not.Null); - Assert.That(m.Slave, Is.SameAs(s)); + var m = new Master(); + var s = new Slave(); + m.Slave = s; + Assert.That(m.Slave, Is.Not.Null); + Assert.That(m.Slave, Is.SameAs(s)); - m.Slave = null; - Assert.That(m.Slave, Is.Null); + m.Slave = null; + Assert.That(m.Slave, Is.Null); - s.Master = m; - Assert.That(s.Master, Is.Not.Null); - Assert.That(s.Master, Is.SameAs(m)); + s.Master = m; + Assert.That(s.Master, Is.Not.Null); + Assert.That(s.Master, Is.SameAs(m)); - t.Complete(); - } + t.Complete(); } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0017_ReferentialActionCascade.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0017_ReferentialActionCascade.cs index 7c85d9fe63..b7a07edf50 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0017_ReferentialActionCascade.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0017_ReferentialActionCascade.cs @@ -11,9 +11,8 @@ namespace Xtensive.Orm.Tests.Issues.Issue0017_Model { - [Serializable] [HierarchyRoot] - public class Master:Entity + public class Master : Entity { [Field, Key] public long ID { get; private set; } @@ -25,9 +24,8 @@ public class Master:Entity public EntitySet Slaves { get; private set; } } - [Serializable] [HierarchyRoot] - public class Slave:Entity + public class Slave : Entity { [Field, Key] public long ID { get; private set; } @@ -54,18 +52,17 @@ protected override DomainConfiguration BuildConfiguration() [Test] public void MainTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - var m1 = new Master(); - var s1 = new Slave(); - m1.Slave = s1; - Assert.That(s1.Master1, Is.EqualTo(m1)); - m1.Remove(); - Assert.That(m1.PersistenceState, Is.EqualTo(PersistenceState.Removed)); - Assert.That(s1.PersistenceState, Is.EqualTo(PersistenceState.Removed)); - Session.Current.SaveChanges(); - // Rollback - } + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var m1 = new Master(); + var s1 = new Slave(); + m1.Slave = s1; + Assert.That(s1.Master1, Is.EqualTo(m1)); + m1.Remove(); + Assert.That(m1.PersistenceState, Is.EqualTo(PersistenceState.Removed)); + Assert.That(s1.PersistenceState, Is.EqualTo(PersistenceState.Removed)); + session.SaveChanges(); + // Rollback } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0021_InvalidSqlQuery.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0021_InvalidSqlQuery.cs index 9f6afa0f48..b1b3364f6c 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0021_InvalidSqlQuery.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0021_InvalidSqlQuery.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0021_Model { - [Serializable] [HierarchyRoot(InheritanceSchema.ClassTable)] public class Root : Entity { @@ -23,7 +22,6 @@ public class Root : Entity public string StringField { get; set; } } - [Serializable] public class Child1 : Root { [Field] @@ -31,7 +29,6 @@ public class Child1 : Root } - [Serializable] public class Child2 : Child1 { [Field] @@ -53,34 +50,25 @@ protected override DomainConfiguration BuildConfiguration() return config; } - /*protected override Domain BuildDomain(DomainConfiguration configuration) - { - if (configuration.ConnectionInfo.Url.StartsWith("memory") && configuration.Builders.Contains(typeof(IncludeTypeIdModifier))) { - throw new IgnoreException("This configuration hangs the test"); - } - return base.BuildDomain(configuration); - }*/ - [Test] public void MainTest() { using (var session = Domain.OpenSession()) { using (var t = session.OpenTransaction()) { - new Child2 - { - StringField = "1", - BoolField = true, - DateTimeField = new DateTime(1967, 10, 23) - }; - new Child2 - { - StringField = "2", - BoolField = false, - DateTimeField = new DateTime(1968, 11, 24) - }; + _ = new Child2 { + StringField = "1", + BoolField = true, + DateTimeField = new DateTime(1967, 10, 23) + }; + _ = new Child2 { + StringField = "2", + BoolField = false, + DateTimeField = new DateTime(1968, 11, 24) + }; t.Complete(); } + using (var t = session.OpenTransaction()) { var all = session.Query.All(); foreach (var obj in all) { diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0028_1_1SymmetricAssociationBug.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0028_1_1SymmetricAssociationBug.cs index d8865d0394..aea9798b10 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0028_1_1SymmetricAssociationBug.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0028_1_1SymmetricAssociationBug.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0028_1_1SymmetricAssociationBug_Model { - [Serializable] [HierarchyRoot] public class First : Entity { @@ -27,7 +26,6 @@ public class First : Entity public Second APair { get; set; } } - [Serializable] [HierarchyRoot] public class Second : Entity { @@ -46,53 +44,53 @@ public class Issue0028_1_1SymmetricAssociationBug : AutoBuildTest protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof (First).Assembly, typeof (First).Namespace); + config.Types.Register(typeof(First)); + config.Types.Register(typeof(Second)); return config; } [Test] public void MainTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - var e1a = new First(); - var e1b = new First(); - var e1c = new First(); - var e1d = new First(); + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var e1a = new First(); + var e1b = new First(); + var e1c = new First(); + var e1d = new First(); - e1a.SPair = e1a; - Assert.That(e1a.SPair, Is.EqualTo(e1a)); - e1b.SPair = e1a; - Assert.That(e1b.SPair, Is.EqualTo(e1a)); - Assert.That(e1a.SPair, Is.EqualTo(e1b)); - e1c.SPair = e1b; - Assert.That(e1b.SPair, Is.EqualTo(e1c)); - Assert.That(e1c.SPair, Is.EqualTo(e1b)); - Assert.That(e1a.SPair, Is.EqualTo(null)); - e1c.SPair = null; - Assert.That(e1a.SPair, Is.EqualTo(null)); - Assert.That(e1b.SPair, Is.EqualTo(null)); - Assert.That(e1c.SPair, Is.EqualTo(null)); - Assert.That(e1d.SPair, Is.EqualTo(null)); + e1a.SPair = e1a; + Assert.That(e1a.SPair, Is.EqualTo(e1a)); + e1b.SPair = e1a; + Assert.That(e1b.SPair, Is.EqualTo(e1a)); + Assert.That(e1a.SPair, Is.EqualTo(e1b)); + e1c.SPair = e1b; + Assert.That(e1b.SPair, Is.EqualTo(e1c)); + Assert.That(e1c.SPair, Is.EqualTo(e1b)); + Assert.That(e1a.SPair, Is.EqualTo(null)); + e1c.SPair = null; + Assert.That(e1a.SPair, Is.EqualTo(null)); + Assert.That(e1b.SPair, Is.EqualTo(null)); + Assert.That(e1c.SPair, Is.EqualTo(null)); + Assert.That(e1d.SPair, Is.EqualTo(null)); - e1a.SPair = e1b; - Assert.That(e1b.SPair, Is.EqualTo(e1a)); - Assert.That(e1a.SPair, Is.EqualTo(e1b)); - e1c.SPair = e1d; - Assert.That(e1d.SPair, Is.EqualTo(e1c)); - Assert.That(e1c.SPair, Is.EqualTo(e1d)); - e1b.SPair = e1d; - Assert.That(e1a.SPair, Is.EqualTo(null)); - Assert.That(e1b.SPair, Is.EqualTo(e1d)); - Assert.That(e1c.SPair, Is.EqualTo(null)); - Assert.That(e1d.SPair, Is.EqualTo(e1b)); - e1d.SPair = null; - Assert.That(e1a.SPair, Is.EqualTo(null)); - Assert.That(e1b.SPair, Is.EqualTo(null)); - Assert.That(e1c.SPair, Is.EqualTo(null)); - Assert.That(e1d.SPair, Is.EqualTo(null)); - // Rollback - } + e1a.SPair = e1b; + Assert.That(e1b.SPair, Is.EqualTo(e1a)); + Assert.That(e1a.SPair, Is.EqualTo(e1b)); + e1c.SPair = e1d; + Assert.That(e1d.SPair, Is.EqualTo(e1c)); + Assert.That(e1c.SPair, Is.EqualTo(e1d)); + e1b.SPair = e1d; + Assert.That(e1a.SPair, Is.EqualTo(null)); + Assert.That(e1b.SPair, Is.EqualTo(e1d)); + Assert.That(e1c.SPair, Is.EqualTo(null)); + Assert.That(e1d.SPair, Is.EqualTo(e1b)); + e1d.SPair = null; + Assert.That(e1a.SPair, Is.EqualTo(null)); + Assert.That(e1b.SPair, Is.EqualTo(null)); + Assert.That(e1c.SPair, Is.EqualTo(null)); + Assert.That(e1d.SPair, Is.EqualTo(null)); + // Rollback } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0036_AutomaticGenericTypesRegistration.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0036_AutomaticGenericTypesRegistration.cs index 689c238b2a..8ae1614fce 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0036_AutomaticGenericTypesRegistration.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0036_AutomaticGenericTypesRegistration.cs @@ -15,7 +15,6 @@ public interface ISecurable : IEntity { } - [Serializable] [HierarchyRoot] public class Person : Entity { @@ -23,7 +22,6 @@ public class Person : Entity public int Id { get; private set; } } - [Serializable] [HierarchyRoot] public class User : Entity, ISecurable { @@ -31,7 +29,6 @@ public class User : Entity, ISecurable public int Id { get; private set; } } - [Serializable] [KeyGenerator(KeyGeneratorKind.None)] [HierarchyRoot] public class SyncInfo : Entity @@ -46,7 +43,6 @@ public SyncInfo (TEntity target) } } - [Serializable] [KeyGenerator(KeyGeneratorKind.None)] [HierarchyRoot] public class SecurityInfo : Entity @@ -76,18 +72,15 @@ protected override DomainConfiguration BuildConfiguration() [Test] public void MainTest() { -// Domain.Model.Dump(); + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var person = new Person(); + var personSyncInfo = new SyncInfo(person); + var user = new User(); + var userSyncInfo = new SyncInfo(user); + var userSecurityInfo = new SecurityInfo(user); - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - var person = new Person(); - var personSyncInfo = new SyncInfo(person); - var user = new User(); - var userSyncInfo = new SyncInfo(user); - var userSecurityInfo = new SecurityInfo(user); - - t.Complete(); - } + t.Complete(); } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0082_ReferentialManagerProblem.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0082_ReferentialManagerProblem.cs index 0aa9aaa7d3..e8c83daadf 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0082_ReferentialManagerProblem.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0082_ReferentialManagerProblem.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0082_ReferentialManagerProblem_Model { - [Serializable] [HierarchyRoot] public class Ancestor : Entity { @@ -20,7 +19,6 @@ public class Ancestor : Entity public int Id { get; private set; } } - [Serializable] public class Descendant : Ancestor { [Field] @@ -36,7 +34,7 @@ public class Descendant : Ancestor public EntitySet Set3 { get; private set; } [Field] - public String StringField { get; set; } + public string StringField { get; set; } [Field] public Descendant Ref2 { get; set; } @@ -59,8 +57,8 @@ public void MainTest() { using (var session = Domain.OpenSession()) { using (var t = session.OpenTransaction()) { - new Descendant {StringField = "1",}; - new Descendant {StringField = "2",}; + _ = new Descendant { StringField = "1" }; + _ = new Descendant { StringField = "2" }; t.Complete(); } using (var t = session.OpenTransaction()) { diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0096_NumerousSchemaExtraction.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0096_NumerousSchemaExtraction.cs index 3518569556..f9d73c6169 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0096_NumerousSchemaExtraction.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0096_NumerousSchemaExtraction.cs @@ -13,58 +13,59 @@ namespace Xtensive.Orm.Tests.Issues.Issue0096_NumerousSchemaExtraction_Model { - [Serializable] [HierarchyRoot(InheritanceSchema = InheritanceSchema.SingleTable)] public class Ancestor : Entity { [Field, Key] public int Id { get; private set; } } -} -namespace Xtensive.Orm.Tests.Issues -{ - [TestFixture] - [Explicit("Manual usage only.")] - public class Issue0096_NumerousSchemaExtraction + public class ModelChanger : IModule { - public class ModelChanger : IModule - { - public static bool IsActive { get; set; } + public static bool IsActive { get; set; } - public void OnBuilt(Domain domain) - { - } + public void OnBuilt(Domain domain) + { + } - public void OnDefinitionsBuilt(BuildingContext context, DomainModelDef model) - { - if (!IsActive) - return; + public void OnDefinitionsBuilt(BuildingContext context, DomainModelDef model) + { + if (!IsActive) + return; - if (!model.Types.Contains("Ancestor")) - return; + if (!model.Types.Contains("Ancestor")) + return; - var type = model.Types["Ancestor"]; - var newField = new FieldDef(typeof (int), context.Validator); - newField.Name = "NewField"; - type.Fields.Add(newField); - } + var type = model.Types["Ancestor"]; + var newField = new FieldDef(typeof(int), context.Validator); + newField.Name = "NewField"; + type.Fields.Add(newField); } + } +} +namespace Xtensive.Orm.Tests.Issues +{ + [TestFixture] + public class Issue0096_NumerousSchemaExtraction + { private void BuildDomain(DomainUpgradeMode mode) { var config = DomainConfigurationFactory.Create(); config.UpgradeMode = mode; - config.Types.RegisterCaching(typeof (Ancestor).Assembly, typeof (Ancestor).Namespace); + config.Types.Register(typeof(Ancestor)); + config.Types.Register(typeof(ModelChanger)); var domain = Domain.Build(config); - using (var session = domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - new Ancestor(); - t.Complete(); + using (var session = domain.OpenSession()) + using (var t = session.OpenTransaction()) { + if (mode != DomainUpgradeMode.Recreate) { + Assert.That(session.Query.All().Count(), Is.GreaterThan(0)); } - } + _ = new Ancestor(); + t.Complete(); + } } [Test] diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0167_SingleTableProblem.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0167_SingleTableProblem.cs index 1120053f3f..8f2511b8b7 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0167_SingleTableProblem.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0167_SingleTableProblem.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0167_SingleTableProblem_Model { - [Serializable] [HierarchyRoot(InheritanceSchema = InheritanceSchema.SingleTable)] public class Ancestor : Entity { @@ -20,7 +19,6 @@ public class Ancestor : Entity public int Id { get; private set; } } - [Serializable] public class Descendant : Ancestor { [Field] @@ -36,18 +34,18 @@ public class Issue0167_SingleTableProblem : AutoBuildTest protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof (Ancestor).Assembly, typeof (Ancestor).Namespace); + config.Types.Register(typeof(Ancestor)); + config.Types.Register(typeof(Descendant)); return config; } [Test] public void MainTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - new Ancestor(); - t.Complete(); - } + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + _ = new Ancestor(); + t.Complete(); } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0188_ModelBuilderError.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0188_ModelBuilderError.cs index 1ca72c6901..a1c861bb64 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0188_ModelBuilderError.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0188_ModelBuilderError.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0188_ModelBuilderError_Model { - [Serializable] [HierarchyRoot] public class A : Entity { @@ -22,7 +21,6 @@ public class A : Entity public B B { get; set; } } - [Serializable] public class B : A { } @@ -30,27 +28,28 @@ public class B : A namespace Xtensive.Orm.Tests.Issues { - public class Issue0188_ModelBuilderError : AutoBuildTest + public class Issue0188_ModelBuilderError { - protected override DomainConfiguration BuildConfiguration() + [Test] + public void DomainBuildTest() { - var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof (A).Assembly, typeof (A).Namespace); - return config; + var configuration = BuildConfiguration(); + Assert.DoesNotThrow(() => Domain.Build(configuration).Dispose()); } [Test] - public void MainTest() + public void DomainBuildAsyncTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - - - + var configuration = BuildConfiguration(); + Assert.DoesNotThrowAsync(async () => (await Domain.BuildAsync(configuration)).Dispose()); + } - // Rollback - } - } + private static DomainConfiguration BuildConfiguration() + { + var config = DomainConfigurationFactory.Create(); + config.Types.Register(typeof (A)); + config.Types.Register(typeof (B)); + return config; } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0245_StructureWhere.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0245_StructureWhere.cs index f83ee9b4e8..f3462ea57a 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0245_StructureWhere.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0245_StructureWhere.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0245_Model { - [Serializable] public class Point : Structure { [Field] @@ -32,7 +31,6 @@ public Point(int x, int y) } } - [Serializable] [HierarchyRoot] public class Range : Entity { @@ -50,7 +48,6 @@ public class Range : Entity namespace Xtensive.Orm.Tests.Issues { [TestFixture] - [Serializable] public class Issue0245_StructureWhere : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0262_StructureAssignment.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0262_StructureAssignment.cs index 72cc4f3201..752f418dbc 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0262_StructureAssignment.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0262_StructureAssignment.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0262_Model { - [Serializable] [HierarchyRoot] public class Container : Entity { @@ -22,7 +21,6 @@ public class Container : Entity public Pair Value { get; set; } } - [Serializable] public class Pair : Structure { [Field] @@ -42,7 +40,6 @@ public Pair() } } - [Serializable] public class Triple : Pair { [Field] diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0271_EntityNotInserted.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0271_EntityNotInserted.cs index bd002c89fc..e4b690bdf0 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0271_EntityNotInserted.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0271_EntityNotInserted.cs @@ -13,49 +13,46 @@ namespace Xtensive.Orm.Tests.Issues.Issue0271_Model { - [Serializable] - [HierarchyRoot] - public class Address : Entity - { - [Field, Key] - public long Id { get; private set; } - } + [HierarchyRoot] + public class Address : Entity + { + [Field, Key] + public long Id { get; private set; } + } - [Serializable] - [HierarchyRoot] - public class User : Entity - { - [Field, Key] - public long Id { get; private set; } + [HierarchyRoot] + public class User : Entity + { + [Field, Key] + public long Id { get; private set; } - [Field] - public Address Address { get; set; } + [Field] + public Address Address { get; set; } - [Field, Association("User", OnOwnerRemove = OnRemoveAction.Cascade, OnTargetRemove = OnRemoveAction.Deny)] - public Account Account { get; set; } - } + [Field, Association("User", OnOwnerRemove = OnRemoveAction.Cascade, OnTargetRemove = OnRemoveAction.Deny)] + public Account Account { get; set; } + } - [Serializable] - [HierarchyRoot] - public class Account : Entity - { - [Field, Key] - public long Id { get; private set; } + [HierarchyRoot] + public class Account : Entity + { + [Field, Key] + public long Id { get; private set; } - [Field] - public User User { get; set; } - } + [Field] + public User User { get; set; } + } } + namespace Xtensive.Orm.Tests.Issues { [TestFixture] public class Issue0271_EntityNotInserted : AutoBuildTest { - protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); - config.Types.RegisterCaching(Assembly.GetExecutingAssembly(), typeof (Issue0271_Model.Address).Namespace); + config.Types.RegisterCaching(Assembly.GetExecutingAssembly(), typeof (Address).Namespace); return config; } @@ -63,14 +60,14 @@ protected override DomainConfiguration BuildConfiguration() public void EntityNotInsertedTest() { using (var session = Domain.OpenSession()) - using (TransactionScope t = session.OpenTransaction()) { + using (var tx = session.OpenTransaction()) { var a = new Address(); var u = new User(); var ac = new Account(); u.Address = a; u.Account = ac; - t.Complete(); + tx.Complete(); } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0276_DuplicateIndex.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0276_DuplicateIndex.cs index 35683decec..e78a6e35f7 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0276_DuplicateIndex.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0276_DuplicateIndex.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0276_DuplicateIndex_Model { - [Serializable] [HierarchyRoot] [Index("Id", Unique = true, Name = "IX_Id")] [Index("Left", Unique = true, Name = "IX_L")] @@ -29,7 +28,6 @@ public class MyEntity : Entity public Key Right { get; set; } } - [Serializable] [KeyGenerator(null)] [HierarchyRoot] [Index("Target", Unique = true)] diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0282_EntitySetContains.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0282_EntitySetContains.cs index 11007793b4..aa630b4ce5 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0282_EntitySetContains.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0282_EntitySetContains.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0282_EntitySetContains_Model { - [Serializable] [HierarchyRoot] public abstract class Parent : Entity { @@ -22,12 +21,10 @@ public abstract class Parent : Entity public EntitySet Items { get; private set; } } - [Serializable] public class Child : Parent { } - [Serializable] [HierarchyRoot] public class Item : Entity { @@ -55,8 +52,10 @@ public void MainTest() var child = new Child(); var item = new Item(); - child.Items.Contains(item); + Assert.That(child.Items.Contains(item), Is.False); + _ = child.Items.Add(item); + Assert.That(child.Items.Contains(item), Is.True); // Rollback } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0296_DeferredConstraints.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0296_DeferredConstraints.cs index a5b0cba956..3347fe3f71 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0296_DeferredConstraints.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0296_DeferredConstraints.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0296_Model { - [Serializable] [HierarchyRoot] public class Node : Entity { @@ -35,34 +34,32 @@ public class Node : Entity namespace Xtensive.Orm.Tests.Issues { - [Ignore("Requires manual profiling")] public class Issue0296_DeferredConstraints : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof (Node).Assembly, typeof (Node).Namespace); + config.Types.Register(typeof(Node)); return config; } [Test] public void MainTest() { - const int count = 50; - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { + const int count = 25; + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { - var root = new Node(); - for (int i = 0; i < count-1; i++) { - var next = new Node(); - root.Right = next; - root.Left = new Node(); - root = next; - } - Assert.That(session.EntityChangeRegistry.GetItems(PersistenceState.New).Count(), Is.LessThan(count)); - - t.Complete(); + var root = new Node(); + for (int i = 0; i < count - 1; i++) { + var next = new Node(); + root.Right = next; + root.Left = new Node(); + root = next; } + Assert.That(session.EntityChangeRegistry.GetItems(PersistenceState.New).Count(), Is.LessThan(count * 2)); + + t.Complete(); } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0298_InheritedAssociationIsIgnored.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0298_InheritedAssociationIsIgnored.cs index b464f1238f..6d26b13f23 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0298_InheritedAssociationIsIgnored.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0298_InheritedAssociationIsIgnored.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0298_Model { - [Serializable] [HierarchyRoot] public class Master : Entity { @@ -26,12 +25,10 @@ public class Master : Entity public EntitySet Tracks { get; private set; } } - [Serializable] public class AudioMaster : Master { } - [Serializable] [HierarchyRoot] public class MasterTrack : Entity { @@ -57,24 +54,23 @@ protected override DomainConfiguration BuildConfiguration() [Test] public void MainTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { - var am = new AudioMaster(); - _ = am.Tracks.Add(new MasterTrack()); - _ = am.Tracks.Add(new MasterTrack()); + var am = new AudioMaster(); + _ = am.Tracks.Add(new MasterTrack()); + _ = am.Tracks.Add(new MasterTrack()); - Assert.That(session.Query.All().Count(), Is.EqualTo(1)); - Assert.That(session.Query.All().Count(), Is.EqualTo(2)); + Assert.That(session.Query.All().Count(), Is.EqualTo(1)); + Assert.That(session.Query.All().Count(), Is.EqualTo(2)); - AssertEx.Throws(() => am.Tracks.First().Remove()); + _ = Assert.Throws(() => am.Tracks.First().Remove()); - am.Remove(); + am.Remove(); - Assert.That(session.Query.All().Count(), Is.EqualTo(0)); - Assert.That(session.Query.All().Count(), Is.EqualTo(0)); - // Rollback - } + Assert.That(session.Query.All().Count(), Is.EqualTo(0)); + Assert.That(session.Query.All().Count(), Is.EqualTo(0)); + // Rollback } } @@ -88,7 +84,7 @@ public void ClientPrifileTest() _ = am.Tracks.Add(new MasterTrack()); _ = am.Tracks.Add(new MasterTrack()); - AssertEx.Throws(() => ((IEnumerable) am.Tracks).First().Remove()); + _ = Assert.Throws(() => ((IEnumerable) am.Tracks).First().Remove()); am.Remove(); // Rollback diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0307_EntitySetOfType.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0307_EntitySetOfType.cs index 481271c9f1..2a3c7e273f 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0307_EntitySetOfType.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0307_EntitySetOfType.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Issues { namespace Issue0307_EntitySetOfType_Model { - [Serializable] [HierarchyRoot] public class Company : Entity { @@ -25,7 +24,6 @@ public class Company : Entity public EntitySet Employees { get; private set; } } - [Serializable] public class Consultant : Employee { public Consultant(Company company, string firstName, string lastName, Skill mainSkill) @@ -42,7 +40,6 @@ public Consultant(Company company, string firstName, string lastName, Skill main public EntitySet Skills { get; private set; } } - [Serializable] [HierarchyRoot] public class Employee : Entity { @@ -74,7 +71,6 @@ public override string ToString() } } - [Serializable] [HierarchyRoot] public class Skill : Entity { @@ -92,7 +88,6 @@ public Skill(string name) } - [Serializable] public class Issue0307_EntitySetOfType : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0331_ForgetHierarchyRoot.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0331_ForgetHierarchyRoot.cs index 267918732b..395fddeb3d 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0331_ForgetHierarchyRoot.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0331_ForgetHierarchyRoot.cs @@ -5,56 +5,62 @@ // Created: 2009.08.03 using System; -using Xtensive.Orm.Tests; +using NUnit.Framework; using Xtensive.Orm.Configuration; using Xtensive.Orm.Tests.Issues.Issue0331_ForgetHierarchyRoot_Model; namespace Xtensive.Orm.Tests.Issues.Issue0331_ForgetHierarchyRoot_Model { - [Serializable] - [HierarchyRoot] - public class Cell : Entity - { - [Key, Field] - public int Id { get; private set; } + [HierarchyRoot] + public class Cell : Entity + { + [Key, Field] + public int Id { get; private set; } - [Field] - public int X { get; set; } + [Field] + public int X { get; set; } - [Field] - public int Y { get; set; } + [Field] + public int Y { get; set; } - [Field, Association(PairTo = "Cell", OnTargetRemove = OnRemoveAction.Clear)] - public Creature Creature { get; set; } - } + [Field, Association(PairTo = "Cell", OnTargetRemove = OnRemoveAction.Clear)] + public Creature Creature { get; set; } + } - [Serializable] - public class Creature : Entity - { - [Key, Field] - public int ID { get; private set; } + public class Creature : Entity + { + [Key, Field] + public int ID { get; private set; } - [Field] - public Cell Cell { get; set; } - } + [Field] + public Cell Cell { get; set; } + } } namespace Xtensive.Orm.Tests.Issues { - public class Issue0331_ForgetHierarchyRoot : AutoBuildTest + public class Issue0331_ForgetHierarchyRoot { - protected override DomainConfiguration BuildConfiguration() + [Test] + public void DomainBuildTest() { - var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof (Cell).Assembly, typeof (Cell).Namespace); - return config; + var configuration = BuildConfiguration(); + _ = Assert.Throws(() => Domain.Build(configuration).Dispose()); + } + + [Test] + public void DomainBuildAsyncTest() + { + var configuration = BuildConfiguration(); + _ = Assert.ThrowsAsync(async () => (await Domain.BuildAsync(configuration)).Dispose()); } - protected override Domain BuildDomain(DomainConfiguration configuration) + private static DomainConfiguration BuildConfiguration() { - Domain domain = null; - AssertEx.Throws(() => domain = base.BuildDomain(configuration)); - return domain; + var config = DomainConfigurationFactory.Create(); + config.Types.Register(typeof (Cell)); + config.Types.Register(typeof (Creature)); + return config; } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0351_NameBuilderProblem.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0351_NameBuilderProblem.cs index 650bff3bae..0a059604d6 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0351_NameBuilderProblem.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0351_NameBuilderProblem.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0351_NameBuilderProblem_Model { - [Serializable] [HierarchyRoot] public class Master : Entity { @@ -22,7 +21,6 @@ public class Master : Entity public EntitySet Slaves { get; private set; } } - [Serializable] [HierarchyRoot] public class Slave : Entity { @@ -33,26 +31,29 @@ public class Slave : Entity namespace Xtensive.Orm.Tests.Issues { - public class Issue0351_NameBuilderProblem : AutoBuildTest + public class Issue0351_NameBuilderProblem { - protected override DomainConfiguration BuildConfiguration() + [Test] + public void DomainBuildTest() { - var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof (Master).Assembly, typeof (Master).Namespace); - config.NamingConvention.NamespacePolicy = NamespacePolicy.AsIs; - return config; + var configuration = BuildConfiguration(); + Assert.DoesNotThrow(() => Domain.Build(configuration).Dispose()); } [Test] - public void MainTest() + public void DomainBuildAsyncTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - + var configuration = BuildConfiguration(); + Assert.DoesNotThrowAsync(async () => (await Domain.BuildAsync(configuration)).Dispose()); + } - // Rollback - } - } + private static DomainConfiguration BuildConfiguration() + { + var config = DomainConfigurationFactory.Create(); + config.Types.Register(typeof(Master)); + config.Types.Register(typeof(Slave)); + config.NamingConvention.NamespacePolicy = NamespacePolicy.AsIs; + return config; } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0359_UpgradeUsingAutoshortenTransaction.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0359_UpgradeUsingAutoshortenTransaction.cs index 4d03895951..6ad6248a5f 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0359_UpgradeUsingAutoshortenTransaction.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0359_UpgradeUsingAutoshortenTransaction.cs @@ -6,12 +6,12 @@ using System; using System.Transactions; +using NUnit.Framework; using Xtensive.Orm.Configuration; using Xtensive.Orm.Tests.Issues.Issue0359_CustomSessionConfigurationProblem_Model; namespace Xtensive.Orm.Tests.Issues.Issue0359_CustomSessionConfigurationProblem_Model { - [Serializable] [HierarchyRoot] public class Class1 : Entity { @@ -22,14 +22,23 @@ public class Class1 : Entity namespace Xtensive.Orm.Tests.Issues { - public class Issue0359_UpgradeUsingAutoshortenTransaction : AutoBuildTest + public class Issue0359_UpgradeUsingAutoshortenTransaction { - protected override void CheckRequirements() + [Test] + public void DomainBuildTest() { - Require.ProviderIs(StorageProvider.SqlServer); + var configuration = BuildConfiguration(); + Assert.DoesNotThrow(() => Domain.Build(configuration).Dispose()); } - protected override DomainConfiguration BuildConfiguration() + [Test] + public void DomainBuildAsyncTest() + { + var configuration = BuildConfiguration(); + Assert.DoesNotThrowAsync(async () => (await Domain.BuildAsync(configuration)).Dispose()); + } + + private static DomainConfiguration BuildConfiguration() { var config = DomainConfigurationFactory.Create(); config.ForeignKeyMode = ForeignKeyMode.All; @@ -37,7 +46,7 @@ protected override DomainConfiguration BuildConfiguration() config.UpgradeMode = DomainUpgradeMode.Recreate; - config.Types.RegisterCaching(typeof (Class1).Assembly, typeof (Class1).Namespace); + config.Types.Register(typeof(Class1)); config.Sessions.Default.DefaultIsolationLevel = IsolationLevel.Serializable; return config; diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0370_EntitiSetIsNotHandledProperly.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0370_EntitiSetIsNotHandledProperly.cs index 5359885359..30638350a9 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0370_EntitiSetIsNotHandledProperly.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0370_EntitiSetIsNotHandledProperly.cs @@ -5,7 +5,6 @@ // Created: 2009.09.03 using System; -using System.Runtime.Serialization; using NUnit.Framework; using Xtensive.Orm.Configuration; using Xtensive.Orm.Model; @@ -13,7 +12,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0370_EntitiSetIsNotHandledProperly_Model { - [Serializable] [HierarchyRoot] public class Container : Entity { @@ -24,7 +22,6 @@ public class Container : Entity public ContainerItemSet Items { get; private set; } } - [Serializable] [HierarchyRoot] public class ContainerItem : Entity { @@ -37,10 +34,6 @@ public class ContainerItemSet : EntitySet protected ContainerItemSet(Entity owner, FieldInfo field) : base(owner, field) {} - - protected ContainerItemSet(SerializationInfo info, StreamingContext context) - : base(info, context) - {} } } @@ -58,14 +51,13 @@ protected override DomainConfiguration BuildConfiguration() [Test] public void MainTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - - var c = new Container(); - c.Items.Add(new ContainerItem()); + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + + var c = new Container(); + _ = c.Items.Add(new ContainerItem()); - // Rollback - } + // Rollback } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0371_ObjectEquals.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0371_ObjectEquals.cs index 85bdf9b65f..9d3c65bc73 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0371_ObjectEquals.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0371_ObjectEquals.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0371_ObjectEquals_Model { - [Serializable] [HierarchyRoot] public class Item : Entity { @@ -60,70 +59,66 @@ protected override DomainConfiguration BuildConfiguration() [Test] public void ObjectEqualsTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - var item1 = new Item(); - var item2 = new Item(); - var result = session.Query.All().Where(item => Equals(item, item1)); - QueryDumper.Dump(result); - // Rollback - } + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var item1 = new Item(); + var item2 = new Item(); + var result = session.Query.All().Where(item => Equals(item, item1)); + QueryDumper.Dump(result); + // Rollback } } [Test] public void ItemEquals1Test() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - var item1 = new Item(); - var item2 = new Item(); - var result = session.Query.All().Where(item => Item.Equals((object)item, (object)item1)); - Assert.Throws(() => QueryDumper.Dump(result)); - // Rollback - } + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var item1 = new Item(); + var item2 = new Item(); + var result = session.Query.All().Where(item => Item.Equals((object) item, (object) item1)); + _ = Assert.Throws(() => QueryDumper.Dump(result)); + // Rollback } } [Test] public void ItemEquals2Test() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - var item1 = new Item(); - var item2 = new Item(); - var result = session.Query.All().Where(item => Item.Equals(item, item1)); - QueryDumper.Dump(result); - // Rollback - } + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var item1 = new Item(); + var item2 = new Item(); + var result = session.Query.All().Where(item => Item.Equals(item, item1)); + QueryDumper.Dump(result); + // Rollback } + } [Test] public void ClassEqualsTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - var item1 = new Item(); - var item2 = new Item(); - var result = session.Query.All().Where(item => String.Equals(item.Name, item1.Name)); - QueryDumper.Dump(result); - // Rollback - } + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var item1 = new Item(); + var item2 = new Item(); + var result = session.Query.All().Where(item => String.Equals(item.Name, item1.Name)); + QueryDumper.Dump(result); + // Rollback } } [Test] public void StringEqualsTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - var item1 = new Item(); - var item2 = new Item(); - var result = session.Query.All().Where(item => item.Equals(item1)); - QueryDumper.Dump(result); - // Rollback - } + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var item1 = new Item(); + var item2 = new Item(); + var result = session.Query.All().Where(item => item.Equals(item1)); + QueryDumper.Dump(result); + // Rollback } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0372_SelfReferenceWithInheritance.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0372_SelfReferenceWithInheritance.cs index 32484ce2fc..167604567f 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0372_SelfReferenceWithInheritance.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0372_SelfReferenceWithInheritance.cs @@ -26,7 +26,6 @@ public MyEntity() } } - [Serializable] [HierarchyRoot] public class Item : Entity @@ -41,7 +40,6 @@ public class Item public WebSite WebSite2 { get; set; } } - [Serializable] public class WebSite : Item { @@ -64,39 +62,36 @@ protected override DomainConfiguration BuildConfiguration() [Test] public void MainTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - var webSite = new WebSite(); - webSite.WebSite = webSite; // self-refernece - Session.Current.SaveChanges(); - // Rollback - } + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var webSite = new WebSite(); + webSite.WebSite = webSite; // self-refernece + session.SaveChanges(); + // Rollback } } [Test] public void DualSelfreferenceTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - var webSite = new WebSite(); - webSite.WebSite = webSite; // self-refernece 1 - webSite.WebSite2 = webSite; // self-refernece 2 - Session.Current.SaveChanges(); - // Rollback - } + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var webSite = new WebSite(); + webSite.WebSite = webSite; // self-refernece 1 + webSite.WebSite2 = webSite; // self-refernece 2 + Session.Current.SaveChanges(); + // Rollback } } [Test] public void SelfreferenceTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - var myEntity = new MyEntity(); - Session.Current.SaveChanges(); - // Rollback - } + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var myEntity = new MyEntity(); + session.SaveChanges(); + // Rollback } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0376_RemoveFieldHint.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0376_RemoveFieldHint.cs index fd172156da..fbb2ab2bdd 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0376_RemoveFieldHint.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0376_RemoveFieldHint.cs @@ -13,12 +13,14 @@ using Xtensive.Orm.Upgrade; using System.Reflection; using System.Linq; +using M1 = Xtensive.Orm.Tests.Issues.Issue0376.Model1; +using M2 = Xtensive.Orm.Tests.Issues.Issue0376.Model2; +using M3 = Xtensive.Orm.Tests.Issues.Issue0376.Model3; #region Models namespace Xtensive.Orm.Tests.Issues.Issue0376.Model1 { - [Serializable] [HierarchyRoot] public class Father : Entity { @@ -29,7 +31,6 @@ public class Father : Entity public string LastName { get; set; } } - [Serializable] public class Son : Father { [Field] @@ -42,7 +43,6 @@ public class Son : Father namespace Xtensive.Orm.Tests.Issues.Issue0376.Model2 { - [Serializable] [HierarchyRoot] public class Father : Entity { @@ -56,7 +56,6 @@ public class Father : Entity public string FirstName { get; set; } } - [Serializable] public class Son : Father { [Field] @@ -78,18 +77,14 @@ public static IDisposable Enable() }); } - public override bool IsEnabled { - get { - return isEnabled; - } - } + public override bool IsEnabled => isEnabled; protected override void AddUpgradeHints(ISet hints) { var oldNamespace = "Xtensive.Orm.Tests.Issues.Issue0376.Model1"; - hints.Add(new RenameTypeHint(oldNamespace + ".Father", typeof (Father))); - hints.Add(new RenameTypeHint(oldNamespace + ".Son", typeof (Son))); - hints.Add(new MoveFieldHint(oldNamespace + ".Son", "FirstName", typeof (Father))); + _ = hints.Add(new RenameTypeHint(oldNamespace + ".Father", typeof (Father))); + _ = hints.Add(new RenameTypeHint(oldNamespace + ".Son", typeof (Son))); + _ = hints.Add(new MoveFieldHint(oldNamespace + ".Son", "FirstName", typeof (Father))); // hintSet.Add(new CopyFieldHint(oldNamescpace + ".Son", "FirstName", typeof (Father))); // hintSet.Add(new RemoveFieldHint(oldNamescpace + ".Son", "FirstName")); } @@ -98,7 +93,6 @@ protected override void AddUpgradeHints(ISet hints) namespace Xtensive.Orm.Tests.Issues.Issue0376.Model3 { - [Serializable] [HierarchyRoot] public class Father : Entity { @@ -136,8 +130,8 @@ public override bool IsEnabled { protected override void AddUpgradeHints(ISet hints) { var oldNamespace = "Xtensive.Orm.Tests.Issues.Issue0376.Model2"; - hints.Add(new RenameTypeHint(oldNamespace + ".Father", typeof (Father))); - hints.Add(new RemoveTypeHint(oldNamespace + ".Son")); + _ = hints.Add(new RenameTypeHint(oldNamespace + ".Father", typeof (Father))); + _ = hints.Add(new RemoveTypeHint(oldNamespace + ".Son")); } } } @@ -147,67 +141,56 @@ protected override void AddUpgradeHints(ISet hints) namespace Xtensive.Orm.Tests.Issues { - using M1 = Issue0376.Model1; - using M2 = Issue0376.Model2; - using M3 = Issue0376.Model3; - [TestFixture] - public class Issue0376_RemoveFieldHint : AutoBuildTest + public class Issue0376_RemoveFieldHint { - protected override DomainConfiguration BuildConfiguration() + [Test] + public void MainTest() { - var config = base.BuildConfiguration(); - config.Types.RegisterCaching(Assembly.GetExecutingAssembly(), "Xtensive.Orm.Tests.Issues.Issue0376.Model1"); + Require.AllFeaturesSupported(ProviderFeatures.UpdateFrom); + + var config = DomainConfigurationFactory.Create(); + config.Types.RegisterCaching(Assembly.GetExecutingAssembly(), typeof(M1.Son).Namespace); config.UpgradeMode = DomainUpgradeMode.Recreate; - return config; - } - protected override Domain BuildDomain(DomainConfiguration configuration) - { - var domain = base.BuildDomain(configuration); - using (var session = domain.OpenSession()) { - using (var transactionScope = session.OpenTransaction()) { - var son = new M1.Son {FirstName = "FirstName", LastName = "LastName", NickName = "NickName"}; - transactionScope.Complete(); - } + Domain domain; + using (domain = Domain.Build(config)) + using (var session = domain.OpenSession()) + using (var transactionScope = session.OpenTransaction()) { + var son = new M1.Son { FirstName = "FirstName", LastName = "LastName", NickName = "NickName" }; + transactionScope.Complete(); } - return domain; - } - [Test] - public void BaseTest() - { - Require.AllFeaturesSupported(ProviderFeatures.UpdateFrom); // Test MoveFieldHint (RemoveFieldHint) - var config = base.BuildConfiguration(); - config.Types.RegisterCaching(Assembly.GetExecutingAssembly(), "Xtensive.Orm.Tests.Issues.Issue0376.Model2"); + config = DomainConfigurationFactory.Create(); + config.Types.RegisterCaching(Assembly.GetExecutingAssembly(), typeof(M2.Son).Namespace); config.UpgradeMode = DomainUpgradeMode.PerformSafely; - Domain domain; + using (M2.Upgrader.Enable()) { domain = Domain.Build(config); } - using (var session = domain.OpenSession()) { - using (var transactionScope = session.OpenTransaction()) { - var son = session.Query.All().Single(); - Assert.That(son.FirstName, Is.EqualTo("FirstName")); - Assert.That(son.LastName, Is.EqualTo("LastName")); - Assert.That(son.NickName, Is.EqualTo("NickName")); - transactionScope.Complete(); - } + using (domain) + using (var session = domain.OpenSession()) + using (var transactionScope = session.OpenTransaction()) { + var son = session.Query.All().Single(); + Assert.That(son.FirstName, Is.EqualTo("FirstName")); + Assert.That(son.LastName, Is.EqualTo("LastName")); + Assert.That(son.NickName, Is.EqualTo("NickName")); + transactionScope.Complete(); } // Test RemoveTypeHint - config = base.BuildConfiguration(); - config.Types.RegisterCaching(Assembly.GetExecutingAssembly(), "Xtensive.Orm.Tests.Issues.Issue0376.Model3"); + config = DomainConfigurationFactory.Create(); + config.Types.RegisterCaching(Assembly.GetExecutingAssembly(), typeof(M3.Father).Namespace); config.UpgradeMode = DomainUpgradeMode.PerformSafely; using (M3.Upgrader.Enable()) { domain = Domain.Build(config); } - using (var session = domain.OpenSession()) { - using (var transactionScope = session.OpenTransaction()) { - Assert.That(session.Query.All().Count()==0, Is.True); - transactionScope.Complete(); - } + using (domain) + using (var session = domain.OpenSession()) + using (var transactionScope = session.OpenTransaction()) { + Assert.That(session.Query.All().Count() == 0, Is.True); + transactionScope.Complete(); } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0391_OnRemoveActionNone.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0391_OnRemoveActionNone.cs index 70f14c09c2..a5b9e5c23d 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0391_OnRemoveActionNone.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0391_OnRemoveActionNone.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0391_OnRemoveActionNone_Model { - [Serializable] [HierarchyRoot] public class Customer : Entity { @@ -19,7 +18,6 @@ public class Customer : Entity public int Id { get; private set; } } - [Serializable] [HierarchyRoot] public class Order : Entity { @@ -32,7 +30,7 @@ public class Order : Entity public bool HasCustomerKey() { - var field = GetTypeInfo().Fields["Customer"]; + var field = TypeInfo.Fields["Customer"]; return GetReferenceKey(field)!=null; } } @@ -45,24 +43,24 @@ public class Issue0391_OnRemoveActionNone : AutoBuildTest protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof (Customer).Assembly, typeof (Customer).Namespace); + config.Types.Register(typeof(Customer)); + config.Types.Register(typeof(Order)); return config; } [Test] public void MainTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { - var c = new Customer(); - var o = new Order(); - o.Customer = c; - c.Remove(); - Assert.That(o.HasCustomerKey(), Is.True); - - t.Complete(); - } + var c = new Customer(); + var o = new Order(); + o.Customer = c; + c.Remove(); + Assert.That(o.HasCustomerKey(), Is.True); + + t.Complete(); } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0402_WrongEntitySetQuery.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0402_WrongEntitySetQuery.cs index 9b9a4b7b89..9ffbc2d9b1 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0402_WrongEntitySetQuery.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0402_WrongEntitySetQuery.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0402_WrongEntitySetQuery_Model { - [Serializable] [HierarchyRoot] public class Node : Entity { @@ -43,7 +42,7 @@ public class Issue0402_WrongEntitySetQuery : AutoBuildTest protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof (Node).Assembly, typeof (Node).Namespace); + config.Types.Register(typeof (Node)); return config; } @@ -51,64 +50,63 @@ protected override DomainConfiguration BuildConfiguration() public void MainTest() { Key key; - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { - var root1 = new Node("1"); - key = root1.Key; - var child11 = new Node("11"); - var child12 = new Node("12"); - root1.Children.Add(child11); - root1.Children.Add(child12); - child11.Children.Add(new Node("111")); - child11.Children.Add(new Node("112")); - child12.Children.Add(new Node("121")); - child12.Children.Add(new Node("122")); + var root1 = new Node("1"); + key = root1.Key; + var child11 = new Node("11"); + var child12 = new Node("12"); + _ = root1.Children.Add(child11); + _ = root1.Children.Add(child12); + _ = child11.Children.Add(new Node("111")); + _ = child11.Children.Add(new Node("112")); + _ = child12.Children.Add(new Node("121")); + _ = child12.Children.Add(new Node("122")); - var root2 = new Node("2"); - var child21 = new Node("21"); - var child22 = new Node("22"); - root2.Children.Add(child21); - root2.Children.Add(child22); - child21.Children.Add(new Node("211")); - child21.Children.Add(new Node("212")); - child22.Children.Add(new Node("221")); - child22.Children.Add(new Node("222")); + var root2 = new Node("2"); + var child21 = new Node("21"); + var child22 = new Node("22"); + _ = root2.Children.Add(child21); + _ = root2.Children.Add(child22); + _ = child21.Children.Add(new Node("211")); + _ = child21.Children.Add(new Node("212")); + _ = child22.Children.Add(new Node("221")); + _ = child22.Children.Add(new Node("222")); - t.Complete(); - } + t.Complete(); } - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - var root1 = session.Query.Single(key); - Console.WriteLine("Direct query"); - var directQuery = session.Query - .All() - .Where(node => root1.Children.Contains(node.Parent)); - var enumerable = session.Query - .All() - .AsEnumerable(); - var directQueryExpected = enumerable - .Where(node => root1.Children.AsEnumerable().Contains(node.Parent)); - foreach (var node in directQuery) - Console.WriteLine(node.Name); - Assert.That(directQueryExpected.Except(directQuery).Count(), Is.EqualTo(0)); + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var root1 = session.Query.Single(key); + Console.WriteLine("Direct query"); + var directQuery = session.Query + .All() + .Where(node => root1.Children.Contains(node.Parent)); + var enumerable = session.Query + .All() + .AsEnumerable(); + var directQueryExpected = enumerable + .Where(node => root1.Children.AsEnumerable().Contains(node.Parent)); + foreach (var node in directQuery) + Console.WriteLine(node.Name); + Assert.That(directQueryExpected.Except(directQuery).Count(), Is.EqualTo(0)); - Console.WriteLine("Query through EntitySet"); - var entitySet = root1.Children; - var entitySetQuery = session.Query - .All() - .Where(node => entitySet.Contains(node.Parent)); - var entitySetQueryExpected = session.Query - .All() - .AsEnumerable() - .Where(node => entitySet.AsEnumerable().Contains(node.Parent)); - foreach (var node in entitySetQuery) - Console.WriteLine(node.Name); - Assert.That(entitySetQueryExpected.Except(entitySetQuery).Count(), Is.EqualTo(0)); - } + + Console.WriteLine("Query through EntitySet"); + var entitySet = root1.Children; + var entitySetQuery = session.Query + .All() + .Where(node => entitySet.Contains(node.Parent)); + var entitySetQueryExpected = session.Query + .All() + .AsEnumerable() + .Where(node => entitySet.AsEnumerable().Contains(node.Parent)); + foreach (var node in entitySetQuery) + Console.WriteLine(node.Name); + Assert.That(entitySetQueryExpected.Except(entitySetQuery).Count(), Is.EqualTo(0)); } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference.cs index 13995f7a01..4e18ba5ea6 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference.cs @@ -41,13 +41,13 @@ public void Main() TestLog.Error("Domain build failed: " + e.ToString()); throw; } + using (domain) { + string key = CreateObjects.CreateTestEchoQueueProcessor(domain); - string key = CreateObjects.CreateTestEchoQueueProcessor(domain); - - IList workList = QueueProcessor.GetWork(key, domain); - foreach (object workUnit in workList) - { - QueueProcessor.Execute(key, workUnit, domain); + IList workList = QueueProcessor.GetWork(key, domain); + foreach (object workUnit in workList) { + QueueProcessor.Execute(key, workUnit, domain); + } } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/Container.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/Container.cs index 86b54c0a8a..071bbc8bea 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/Container.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/Container.cs @@ -2,8 +2,7 @@ namespace Xtensive.Orm.Tests.Issues.Issue0408_EntitySetNullReference_Model { - [Serializable] - [HierarchyRoot] + [HierarchyRoot] public class Container : Entity { [Field, Key] @@ -18,7 +17,7 @@ public class Container : Entity public virtual T CreateDocument(string name) where T : Document, new() { T doc = new T() { Name = name }; - Documents.Add(doc); + _ = Documents.Add(doc); return doc; } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/DocumentLink.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/DocumentLink.cs index b1f933890d..5e06af01e7 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/DocumentLink.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/DocumentLink.cs @@ -1,8 +1,7 @@ -using System; +using System; namespace Xtensive.Orm.Tests.Issues.Issue0408_EntitySetNullReference_Model { - [Serializable] [HierarchyRoot] public class DocumentLink : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/EchoProcessor.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/EchoProcessor.cs index d2d441a9b3..4d1e49ed81 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/EchoProcessor.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/EchoProcessor.cs @@ -1,18 +1,17 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Xtensive.Orm.Tests.Issues.Issue0408_EntitySetNullReference_Model { - [Serializable] public class EchoProcessor : QueueProcessor { public override void ProcessDocument(Document inputDocument) { TestLog.Info("Entered EchoProcessor.Process() "); - Document outputDocument = OutputContainer.CreateDocument("output test document"); + var outputDocument = OutputContainer.CreateDocument("output test document"); MoveDocumentsToOutputAndDoneContainers(outputDocument, inputDocument); } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/ErrorDocument.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/ErrorDocument.cs index d2ec738c17..2917794391 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/ErrorDocument.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/ErrorDocument.cs @@ -1,8 +1,7 @@ -using System; +using System; namespace Xtensive.Orm.Tests.Issues.Issue0408_EntitySetNullReference_Model { - [Serializable] public class ErrorDocument : Document { [Field] diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/HistoryEntry.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/HistoryEntry.cs index c96b7bee5c..7c3a56b01a 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/HistoryEntry.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/HistoryEntry.cs @@ -1,17 +1,16 @@ -using System; +using System; namespace Xtensive.Orm.Tests.Issues.Issue0408_EntitySetNullReference_Model { - [Serializable] [HierarchyRoot] public class HistoryEntry : Entity { + public const HistoryEntryVisibility VisibilityForAll = HistoryEntryVisibility.EndUser | HistoryEntryVisibility.AdministratorUser | HistoryEntryVisibility.Debugger; + [Field, Key] public long Id { get; private set; } - public const HistoryEntryVisibility VisibilityForAll = HistoryEntryVisibility.EndUser | HistoryEntryVisibility.AdministratorUser | HistoryEntryVisibility.Debugger; - - [Field(Length = Int32.MaxValue)] + [Field(Length = int.MaxValue)] public string What { get; set; } [Field] diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/HistoryEntryVisibility.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/HistoryEntryVisibility.cs index cfa3c5950f..abdc30e1bc 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/HistoryEntryVisibility.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/HistoryEntryVisibility.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -10,7 +10,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0408_EntitySetNullReference_Model /// Consider also HistoryEntry.VisibilityForAll . /// [Flags] - [Serializable] public enum HistoryEntryVisibility : int { None = 0, diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/Processor.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/Processor.cs index e9d8ce7840..5b7fbbdc14 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/Processor.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/Processor.cs @@ -3,7 +3,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0408_EntitySetNullReference_Model { - [Serializable] [HierarchyRoot] public abstract class Processor : Entity { @@ -48,7 +47,7 @@ protected void PropagateAllGroups(Document sourceDocument, Document destinationD // qr = q.Execute(); //} - var qr = from link in Session.Demand().Query.All() + var qr = from link in Session.Query.All() where link.LinkSemantic == LinkSemantic.GroupHeadToDocumentInGroup where link.LinkDestination == sourceDocument select link; diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/QueueProcessor.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/QueueProcessor.cs index f08cbd31c7..10953e5ee6 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/QueueProcessor.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0408_EntitySetNullReference_Model/QueueProcessor.cs @@ -7,7 +7,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0408_EntitySetNullReference_Model { - [Serializable] public abstract class QueueProcessor : Processor { [Field] @@ -19,51 +18,37 @@ public abstract class QueueProcessor : Processor [Field] public Container ProcessedContainer { get; set; } - public static IList GetWork(string key, Domain domain) + public string SchedulerKey { - using (var session = domain.OpenSession()) - { - QueueProcessor queueProcessor = null; - IList result; - using (TransactionScope transactionScope = session.OpenTransaction()) - { - queueProcessor = GetQueueProcessorByKey(key); - transactionScope.Complete(); - result = queueProcessor.GetWork(); - } - return result; + get { + return this.GetType().FullName + "~" + this.Id; } } - public static void Execute(string key, object workUnit, Domain domain) + public static IList GetWork(string key, Domain domain) { using (var session = domain.OpenSession()) - { - QueueProcessor queueProcessor = null; - using (TransactionScope transactionScope = session.OpenTransaction()) - { - queueProcessor = GetQueueProcessorByKey(key); - queueProcessor.Execute(workUnit); - transactionScope.Complete(); - } + using (var transactionScope = session.OpenTransaction()) { + var queueProcessor = GetQueueProcessorByKey(session, key); + transactionScope.Complete(); + return queueProcessor.GetWork(); } } - private static QueueProcessor GetQueueProcessorByKey(string key) + public static void Execute(string key, object workUnit, Domain domain) { - string[] parts = key.Split('~'); - long id = Convert.ToInt64(parts[1]); - return (from p in Session.Demand().Query.All() - where p.Id == id - select p).FirstOrDefault(); + using (var session = domain.OpenSession()) + using (var transactionScope = session.OpenTransaction()) { + var queueProcessor = GetQueueProcessorByKey(session, key); + queueProcessor.Execute(workUnit); + transactionScope.Complete(); + } } - public string SchedulerKey + private static QueueProcessor GetQueueProcessorByKey(Session session, string key) { - get - { - return this.GetType().FullName + "~" + this.Id; - } + var id = Convert.ToInt64(key.Split('~')[1]); + return session.Query.All().FirstOrDefault(p => p.Id == id); } /// @@ -84,20 +69,20 @@ public virtual IList GetWork() var work = from d in InputContainer.Documents select (object)d.Id; - return (IList)work.ToList(); + return work.ToList(); } //-> pour commiter chaque document traité //on laisse remonter les exceptions dataobjects public virtual void Execute(object workUnit) { - long id = (long)workUnit; - Document inputDocument = InputContainer.Documents.Where(d => d.Id == id).FirstOrDefault(); + var id = (long)workUnit; + var inputDocument = InputContainer.Documents.FirstOrDefault(d => d.Id == id); System.Diagnostics.Debug.Assert(inputDocument != null, "QueueProcessor.Execute() called with nothing to do. There must be a document in the InputContainer"); try { - Document documentToProcess = GetDocumentToProcessFromInputDocument(inputDocument); + var documentToProcess = GetDocumentToProcessFromInputDocument(inputDocument); if (documentToProcess == null) { string message = $"No document with DocumentTypeToProcess={DocumentTypeToProcess} found in the group of the inputDocument."; @@ -109,7 +94,7 @@ public virtual void Execute(object workUnit) } catch (Exception ex) // yes, general exception type { - using (TransactionScope transactionScope = Session.OpenTransaction()) + using (var transactionScope = Session.OpenTransaction()) { string message = $"Exception caught in {this.Name}.Execute() : '"; TestLog.Error(message, ex); @@ -137,7 +122,7 @@ private void ProcessAndMove(Document inputDocument, Document documentToProcess) documentToProcess.AddHistoryEntry("Document processed by " + this.Name, HistoryEntryVisibility.AdministratorUser); - Container processedContainer = GetProcessedContainerForDocument(inputDocument); + var processedContainer = GetProcessedContainerForDocument(inputDocument); if (processedContainer != null) { MoveDocumentToContainer(inputDocument, processedContainer); @@ -167,7 +152,7 @@ protected Document GetDocumentToProcessFromInputDocument(Document inputDocument) } string documentTypeToProcess = DocumentTypeToProcess; - if (String.IsNullOrEmpty(documentTypeToProcess)) + if (string.IsNullOrEmpty(documentTypeToProcess)) { return inputDocument; } @@ -176,7 +161,7 @@ protected Document GetDocumentToProcessFromInputDocument(Document inputDocument) return inputDocument; } - List documentsMatchingDocType = inputDocument.FindDocumentsInMyGroupsByType(documentTypeToProcess, 0); + var documentsMatchingDocType = inputDocument.FindDocumentsInMyGroupsByType(documentTypeToProcess, 0); // return the document in the innermost group : if (documentsMatchingDocType.Count > 0) diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0409_ConstructorTransactional.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0409_ConstructorTransactional.cs index 4e471a554c..92ab4f70bf 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0409_ConstructorTransactional.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0409_ConstructorTransactional.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0409_ConstructorTransactional_Model { - [Serializable] [HierarchyRoot] public class Document : Entity { @@ -29,7 +28,7 @@ public class Issue0409_ConstructorTransactional : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() { - DomainConfiguration config = base.BuildConfiguration(); + var config = base.BuildConfiguration(); config.Types.RegisterCaching(typeof (Document).Assembly, typeof (Document).Namespace); return config; } @@ -45,16 +44,9 @@ public void DocumentCreatedInSeparateTransactionTest() t.Complete(); } } - using (var s = Domain.OpenSession()) { - Assert.Throws(() => { var document = s.Query.Single(key); }); - } - } - - [Test] - public void DocumentCreatedInAutoTransactionTest() - { - using (var s = Domain.OpenSession()) { - Assert.Throws(() => { var document = new Document(); }); + using (var s = Domain.OpenSession()) + using (var tx = s.OpenTransaction()) { + Assert.DoesNotThrow(() => { var document = s.Query.Single(key); }); } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0422_GetStructureFieldsForComplexStructures.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0422_GetStructureFieldsForComplexStructures.cs index 458ddafb57..5323efe255 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0422_GetStructureFieldsForComplexStructures.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0422_GetStructureFieldsForComplexStructures.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0422_GetStructureFieldsForComplexStructures_Model { - [Serializable] public class EntityStructure : Structure { [Field] @@ -28,7 +27,6 @@ public class EntityStructure : Structure public DateTime StructureAge { get; set; } } - [Serializable] public class ComplexStructure : Structure { [Field] @@ -42,7 +40,6 @@ public class ComplexStructure : Structure public EntityStructure EntityStructure { get; set; } } - [Serializable] [HierarchyRoot] public class EntityB : Entity { @@ -83,39 +80,38 @@ protected override void CheckRequirements() [Test] public void MainTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - // Fill - IEnumerable entitiesB = Enumerable - .Range(0, 100) - .Select(i => new EntityB { - Name = "NameB_" + i, - ComplexStructure = new ComplexStructure { + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + // Fill + IEnumerable entitiesB = Enumerable + .Range(0, 100) + .Select(i => new EntityB { + Name = "NameB_" + i, + ComplexStructure = new ComplexStructure { + EntityB = new EntityB { + Name = "NameB_1_" + i + }, + ComplexStructureName = "StructureName_1_" + i, + EntityStructure = new EntityStructure { EntityB = new EntityB { - Name = "NameB_1_" + i + Name = "NameB_2_" + i }, - ComplexStructureName = "StructureName_1_" + i, - EntityStructure = new EntityStructure { - EntityB = new EntityB { - Name = "NameB_2_" + i - }, - StructureAge = new DateTime(2000 + i, 10, 10), - StructureName = "StructureName_2_" + i, - } + StructureAge = new DateTime(2000 + i, 10, 10), + StructureName = "StructureName_2_" + i, } - }) - .ToList(); - - // Query - session.SaveChanges(); - var structures = session.Query.All().Select(b => b.ComplexStructure).Skip(83).Take(1); - var str = structures.Single(); - var testEntities = session.Query.All().Where(b => b.ComplexStructure==str).ToArray(); - var actualEntities = session.Query.All().AsEnumerable().Where(b => b.ComplexStructure==str).ToArray(); - Assert.That(actualEntities.Except(testEntities).Count(), Is.EqualTo(0)); - - // Rollback - } + } + }) + .ToList(); + + // Query + session.SaveChanges(); + var structures = session.Query.All().Select(b => b.ComplexStructure).Skip(83).Take(1); + var str = structures.Single(); + var testEntities = session.Query.All().Where(b => b.ComplexStructure == str).ToArray(); + var actualEntities = session.Query.All().AsEnumerable().Where(b => b.ComplexStructure == str).ToArray(); + Assert.That(actualEntities.Except(testEntities).Count(), Is.EqualTo(0)); + + // Rollback } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0424_SqlCommandIsNull.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0424_SqlCommandIsNull.cs index 80e971e360..5d713e624a 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0424_SqlCommandIsNull.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0424_SqlCommandIsNull.cs @@ -12,20 +12,18 @@ namespace Xtensive.Orm.Tests.Issues.Issue0296_Model { - [Serializable] [HierarchyRoot] - public class TheParent : Entity + public class Parent : Entity { [Key, Field] public int Id { get; private set;} [Field] - public TheChild Child { get; set; } + public Child Child { get; set; } } - [Serializable] [HierarchyRoot] - public class TheChild : Entity + public class Child : Entity { [Key, Field] public int Id { get; private set; } @@ -37,22 +35,21 @@ public class TheChild : Entity namespace Xtensive.Orm.Tests.Issues { - [Serializable] public class Issue0424_SqlCommandIsNull : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); - configuration.Types.RegisterCaching(typeof (TheParent).Assembly, typeof (TheParent).Namespace); + configuration.Types.Register(typeof (Parent)); + configuration.Types.Register(typeof (Child)); return configuration; } - public override void TestFixtureSetUp() + protected override void PopulateData() { - base.TestFixtureSetUp(); using (var session = Domain.OpenSession()) using (var t = session.OpenTransaction()) { - new TheParent {Child = new TheChild()}; + _ = new Parent {Child = new Child()}; t.Complete(); } } @@ -62,8 +59,8 @@ public void MainTest() { using (var session = Domain.OpenSession()) using (var t = session.OpenTransaction()) { - var parent = session.Query.All().Single(); - var result = session.Query.All().Single(child => child.Value==parent.Child.Value); + var parent = session.Query.All().Single(); + var result = session.Query.All().Single(child => child.Value==parent.Child.Value); t.Complete(); } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0435_BatchingFail.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0435_BatchingFail.cs index d1de9b6c39..d94c8bd6d5 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0435_BatchingFail.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0435_BatchingFail.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0435_Model { - [Serializable] [HierarchyRoot] public class MyEntity : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0452_OrderByIncorrectColumn.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0452_OrderByIncorrectColumn.cs index 68fc9af57a..2c900d8e87 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0452_OrderByIncorrectColumn.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0452_OrderByIncorrectColumn.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0452_OrderByIncorrectColumn_Model { - [Serializable] [HierarchyRoot] public class Image : Entity { @@ -21,7 +20,6 @@ public class Image : Entity public Guid Id { get; private set; } } - [Serializable] [HierarchyRoot] public class SitePage : Entity { @@ -31,7 +29,6 @@ public class SitePage : Entity public string Url { get; set; } } - [Serializable] [HierarchyRoot] public class Person : Entity { @@ -39,7 +36,6 @@ public class Person : Entity public Guid Id { get; private set; } } - [Serializable] [HierarchyRoot] public class Category : Entity { @@ -50,7 +46,6 @@ public class Category : Entity public string Name { get; set; } } - [Serializable] [HierarchyRoot] public abstract class AbstractObject : Entity { @@ -64,7 +59,6 @@ public abstract class AbstractObject : Entity public Person CreatedBy{ get; set;} } - [Serializable] public abstract class BlogPost : AbstractObject { [Field] @@ -83,12 +77,10 @@ public abstract class BlogPost : AbstractObject public SitePage SitePage { get; set; } } - [Serializable] public sealed class Article : BlogPost { } - [Serializable] public sealed class Article2 : BlogPost { @@ -114,82 +106,77 @@ protected override void CheckRequirements() Require.AnyFeatureSupported(ProviderFeatures.RowNumber | ProviderFeatures.NativePaging); } - public override void TestFixtureSetUp() + protected override void PopulateData() { - base.TestFixtureSetUp(); - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - Fill(); - t.Complete(); - } + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + Fill(session); + t.Complete(); } } [Test] public void TakeTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - var result = session.Query.All
().OrderByDescending(a => a.PublishedOn).Take(Count - 1).ToList(); - var expected = session.Query.All
().AsEnumerable().OrderByDescending(a => a.PublishedOn).Take(Count - 1).ToList(); - Assert.That(expected.Count>0, Is.True); - Assert.That(result.Count, Is.EqualTo(expected.Count)); - for (int i = 0; i < expected.Count; i++) { - var areMatch = Equals(expected[i], result[i]); - Assert.That(areMatch, Is.True); - } - Assert.That(expected.SequenceEqual(result), Is.True); + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var result = session.Query.All
().OrderByDescending(a => a.PublishedOn).Take(Count - 1).ToList(); + var expected = session.Query.All
().AsEnumerable().OrderByDescending(a => a.PublishedOn).Take(Count - 1).ToList(); + Assert.That(expected.Count > 0, Is.True); + Assert.That(result.Count, Is.EqualTo(expected.Count)); + for (int i = 0; i < expected.Count; i++) { + var areMatch = Equals(expected[i], result[i]); + Assert.That(areMatch, Is.True); } + Assert.That(expected.SequenceEqual(result), Is.True); } } [Test] public void SkipTakeTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - var result = session.Query.All
().OrderByDescending(a => a.PublishedOn).Skip(5).Take(Count - 10).ToList(); - var expected = session.Query.All
().AsEnumerable().OrderByDescending(a => a.PublishedOn).Skip(5).Take(Count - 10).ToList(); - Assert.That(expected.Count>0, Is.True); - Assert.That(result.Count, Is.EqualTo(expected.Count)); - for (int i = 0; i < expected.Count; i++) { - bool areMatch = Equals(expected[i], result[i]); - Assert.That(areMatch, Is.True); - } - Assert.That(expected.SequenceEqual(result), Is.True); + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var result = session.Query.All
().OrderByDescending(a => a.PublishedOn).Skip(5).Take(Count - 10).ToList(); + var expected = session.Query.All
().AsEnumerable().OrderByDescending(a => a.PublishedOn).Skip(5).Take(Count - 10).ToList(); + Assert.That(expected.Count > 0, Is.True); + Assert.That(result.Count, Is.EqualTo(expected.Count)); + for (int i = 0; i < expected.Count; i++) { + bool areMatch = Equals(expected[i], result[i]); + Assert.That(areMatch, Is.True); } + Assert.That(expected.SequenceEqual(result), Is.True); } } [Test] public void SkipTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - var result = session.Query.All
().OrderByDescending(a => a.PublishedOn).Skip(5).ToList(); - var expected = session.Query.All
().AsEnumerable().OrderByDescending(a => a.PublishedOn).Skip(5).ToList(); - Assert.That(result.Count, Is.EqualTo(expected.Count)); - Assert.That(expected.Count>0, Is.True); - for (int i = 0; i < expected.Count; i++) { - bool areMatch = Equals(expected[i], result[i]); - Assert.That(areMatch, Is.True); - } - Assert.That(expected.SequenceEqual(result), Is.True); + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var result = session.Query.All
().OrderByDescending(a => a.PublishedOn).Skip(5).ToList(); + var expected = session.Query.All
().AsEnumerable().OrderByDescending(a => a.PublishedOn).Skip(5).ToList(); + Assert.That(result.Count, Is.EqualTo(expected.Count)); + Assert.That(expected.Count > 0, Is.True); + for (int i = 0; i < expected.Count; i++) { + bool areMatch = Equals(expected[i], result[i]); + Assert.That(areMatch, Is.True); } + Assert.That(expected.SequenceEqual(result), Is.True); } } [Test] public void SelectCategoryTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - var result = session.Query.All
().Select(p => p.Category); - foreach (var category in result) { - Assert.That(category, Is.Not.Null); - } + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var result = session.Query.All
().Select(p => p.Category); + foreach (var category in result) { + Assert.That(category, Is.Not.Null); } } + } [Test] @@ -216,7 +203,7 @@ public void QuerySingleOrDefaultTest() } } - private void Fill() + private void Fill(Session session) { for (int i = 0; i < Count; i++) { var person = new Person(); @@ -235,7 +222,7 @@ private void Fill() TeaserImage = image }; } - Session.Current.SaveChanges(); + session.SaveChanges(); } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0457_EntityStateToString.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0457_EntityStateToString.cs index a4f47554a6..835eba430b 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0457_EntityStateToString.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0457_EntityStateToString.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0457_EntityStateToStringModel { - [Serializable] [HierarchyRoot] public class BuggyEntity : Entity { @@ -28,22 +27,21 @@ public class Issue0457_EntityStateToString : AutoBuildTest protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof (BuggyEntity).Assembly, typeof (BuggyEntity).Namespace); + config.Types.Register(typeof (BuggyEntity)); return config; } [Test] public void MainTest() { - using (var session = Domain.OpenSession()) { - using (var transactionScope = session.OpenTransaction()) { + using (var session = Domain.OpenSession()) + using (var transactionScope = session.OpenTransaction()) { - session.Query.SingleOrDefault(1001); - var entityState = session.EntityStateCache.FirstOrDefault(); + _ = session.Query.SingleOrDefault(1001); // fetch inexistent state to cache + var entityState = session.EntityStateCache.FirstOrDefault(); - if (entityState!=null) - Console.WriteLine(entityState.ToString()); // NullReferenceException is thrown here - } + if (entityState != null) + Console.WriteLine(entityState.ToString()); // NullReferenceException is thrown here } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0485_EntitySetDescendant.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0485_EntitySetDescendant.cs index 522413dd8d..30515fdac1 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0485_EntitySetDescendant.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0485_EntitySetDescendant.cs @@ -5,7 +5,6 @@ // Created: 2009.11.26 using System; -using System.Runtime.Serialization; using NUnit.Framework; using Xtensive.Orm.Configuration; using Xtensive.Orm.Model; @@ -15,7 +14,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0485_EntitySetDescendant_Model { - [Serializable] [HierarchyRoot] public class Company : Entity { @@ -29,7 +27,6 @@ public class Company : Entity public EntitySetDescendant Employees{ get; private set;} } - [Serializable] [HierarchyRoot] public class Employee : Entity { @@ -48,11 +45,6 @@ protected EntitySetDescendant(Entity owner, FieldInfo field) : base(owner, field) { } - - protected EntitySetDescendant(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } @@ -76,18 +68,17 @@ protected override void CheckRequirements() [Test] public void MainTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - var company = new Company(); - var employee1 = new Employee(); - var employee2 = new Employee(); - var employee3 = new Employee(); - company.Employees.Add(employee1); - company.Employees.Add(employee2); - company.Employees.Add(employee3); - Assert.That(company.Employees.ElementAt(0), Is.Not.Null); - // Rollback - } + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var company = new Company(); + var employee1 = new Employee(); + var employee2 = new Employee(); + var employee3 = new Employee(); + _ = company.Employees.Add(employee1); + _ = company.Employees.Add(employee2); + _ = company.Employees.Add(employee3); + Assert.That(company.Employees.ElementAt(0), Is.Not.Null); + // Rollback } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0493_BadImageFormatTest.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0493_BadImageFormatTest.cs index ad0aabbff4..478369ab76 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0493_BadImageFormatTest.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0493_BadImageFormatTest.cs @@ -6,7 +6,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0493_BadImageFormatTest_Model { - [Serializable] public abstract class Info : Entity where T:Entity { [Field, Key] @@ -17,7 +16,6 @@ public Info(T target) {} } - [Serializable] [HierarchyRoot] public class Person : Entity { @@ -25,7 +23,6 @@ public class Person : Entity public int Id { get; private set; } } - [Serializable] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] public class PersonInfo : Info diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0559_EntitySetQueryError.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0559_EntitySetQueryError.cs index 3dd9c03b4c..760411d032 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0559_EntitySetQueryError.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0559_EntitySetQueryError.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Issues { namespace Issue0559_EntitySetQueryError_Model { - [Serializable] [HierarchyRoot] [Index("Name")] public class Topic : Entity @@ -29,7 +28,6 @@ public class Topic : Entity public EntitySet Subscriptions { get; private set; } } - [Serializable] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] [Index("ApplicationName")] @@ -60,7 +58,8 @@ public class Issue0559_EntitySetQueryError : AutoBuildTest protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof(Subscription).Assembly, typeof(Subscription).Namespace); + config.Types.Register(typeof(Subscription)); + config.Types.Register(typeof(Topic)); return config; } @@ -75,10 +74,8 @@ public void MainTest() var subscription = new Subscription(1, 1) {ApplicationName = ApplicationName}; _ = defaultTopic.Subscriptions.Add(subscription); - var subTopic = (from topic in session.Query.All() where topic.Name == topicName select topic).SingleOrDefault(); - var subscriptions = subTopic.Subscriptions; - var result = from sub in subscriptions where sub.ApplicationName == ApplicationName select sub; - var list = result.ToList(); + var subTopic = session.Query.All().SingleOrDefault(t => t.Name == topicName); + var subscriptions = subTopic.Subscriptions.Where(sub => sub.ApplicationName == ApplicationName).ToList(); t.Complete(); } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0585_TakeSkipJoinMappingError.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0585_TakeSkipJoinMappingError.cs index 7bc2174fec..6ee8790ac7 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0585_TakeSkipJoinMappingError.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0585_TakeSkipJoinMappingError.cs @@ -116,44 +116,35 @@ public class Role : Entity } } - [Serializable] public class Issue0585_TakeSkipJoinMappingError : AutoBuildTest { - public override void TestFixtureSetUp() + protected override void PopulateData() { - base.TestFixtureSetUp(); - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - Fill(); - t.Complete(); - } - } - } - - private void Fill() - { - for (int i = 0; i < 10; i++) { - var user = new User { - Name = $"name_{i}", - Password = $"password_{i}", - PasswordQuestion = $"passwordQuestion_{i}", - Email = $"email{i}" - }; - for (int j = 0; j < 10; j++) { - var activity = new UserActivity { - Comment = $"comment_{i}_{j}", - IsApproved = true, - IsLockedOut = false, - CreationDate = DateTime.Now, - LastLoginDate = DateTime.Now, - LastActivityDate = DateTime.Now, - LastPasswordChangeDate = DateTime.Now, - LastLockoutDate = DateTime.Now, - User = user + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + for (int i = 0; i < 10; i++) { + var user = new User { + Name = $"name_{i}", + Password = $"password_{i}", + PasswordQuestion = $"passwordQuestion_{i}", + Email = $"email{i}" }; + for (int j = 0; j < 10; j++) { + var activity = new UserActivity { + Comment = $"comment_{i}_{j}", + IsApproved = true, + IsLockedOut = false, + CreationDate = DateTime.Now, + LastLoginDate = DateTime.Now, + LastActivityDate = DateTime.Now, + LastPasswordChangeDate = DateTime.Now, + LastLockoutDate = DateTime.Now, + User = user + }; + } } + t.Complete(); } - Session.Current.SaveChanges(); } protected override DomainConfiguration BuildConfiguration() @@ -172,31 +163,30 @@ protected override void CheckRequirements() [Test] public void MainTest() { - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - int pageIndex = 1; - int pageSize = 1; - IQueryable usersQuery = session.Query.All().Skip(pageIndex * pageSize).Take(pageSize); - var query = - from user in usersQuery - from activity in session.Query.All().Where(a => a.User==user).DefaultIfEmpty() - select new { - user.Name, - user.UniqueIndentifier, - user.Email, - user.PasswordQuestion, - activity.Comment, - activity.IsApproved, - activity.IsLockedOut, - activity.CreationDate, - activity.LastLoginDate, - activity.LastActivityDate, - activity.LastPasswordChangeDate, - activity.LastLockoutDate - }; - var result = query.ToList(); - Assert.That(result.Count, Is.GreaterThan(0)); - } + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + int pageIndex = 1; + int pageSize = 1; + var usersQuery = session.Query.All().Skip(pageIndex * pageSize).Take(pageSize); + var query = + from user in usersQuery + from activity in session.Query.All().Where(a => a.User == user).DefaultIfEmpty() + select new { + user.Name, + user.UniqueIndentifier, + user.Email, + user.PasswordQuestion, + activity.Comment, + activity.IsApproved, + activity.IsLockedOut, + activity.CreationDate, + activity.LastLoginDate, + activity.LastActivityDate, + activity.LastPasswordChangeDate, + activity.LastLockoutDate + }; + var result = query.ToList(); + Assert.That(result.Count, Is.GreaterThan(0)); } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0587_ByteArrayEquals.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0587_ByteArrayEquals.cs index bf60573e6e..74c6bde3c6 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0587_ByteArrayEquals.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0587_ByteArrayEquals.cs @@ -29,13 +29,12 @@ public class User : Entity } } - [Serializable] public class Issue0587_ByteArrayEquals : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof (User).Assembly, typeof (User).Namespace); + config.Types.Register(typeof(User)); return config; } @@ -63,7 +62,7 @@ public void MainTest() var usersQuery = session.Query.All().Skip(pageIndex * pageSize).Take(pageSize); var key = new byte[] { 1, 1, 1 }; var result = session.Query.All().Where(user => user.Photo == key).ToList(); - Assert.That(result.Count, Is.GreaterThan(0)); + Assert.That(result.Count, Is.EqualTo(1)); } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0597_OpenGenericsInDomainModel.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0597_OpenGenericsInDomainModel.cs index 48b5c84217..82f3ff323a 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0597_OpenGenericsInDomainModel.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0597_OpenGenericsInDomainModel.cs @@ -54,7 +54,7 @@ public MediaBase() public Guid ID { get; private set; } [Field] - public abstract Int64 Duration { get; } + public abstract long Duration { get; } } [HierarchyRoot] @@ -87,13 +87,13 @@ public abstract class OutputTrack : Entity { protected OutputTrack() { } - protected OutputTrack(Int32 trackDefinition) + protected OutputTrack(int trackDefinition) { TrackDefinition = trackDefinition; } [Field] - public Int32 TrackDefinition { get; private set; } + public int TrackDefinition { get; private set; } } [HierarchyRoot] @@ -101,7 +101,7 @@ public class SimpleOutputTrack : OutputTrack { public SimpleOutputTrack() { } - public SimpleOutputTrack(Int32 trackDefinition) + public SimpleOutputTrack(int trackDefinition) : base(trackDefinition) { } [Field, Key] @@ -111,17 +111,17 @@ public SimpleOutputTrack(Int32 trackDefinition) public abstract class SimpleMedia : MediaItem where MT : MediaType { - private Int64 _duration = 0; + private long _duration = 0; public SimpleMedia() { } - public SimpleMedia(Int64 duration, IList outputTracks) + public SimpleMedia(long duration, IList outputTracks) : base(outputTracks) { _duration = duration; } - public override Int64 Duration { get { return _duration; } } + public override long Duration { get { return _duration; } } } [HierarchyRoot] @@ -129,12 +129,11 @@ public class SimpleVirtualMedia : SimpleMedia { public SimpleVirtualMedia() { } - public SimpleVirtualMedia(Int64 duration, IList outputTracks) + public SimpleVirtualMedia(long duration, IList outputTracks) : base(duration, outputTracks) { } } } - [Serializable] public class Issue0597_OpenGenericsInDomainModel : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() @@ -148,9 +147,6 @@ protected override DomainConfiguration BuildConfiguration() public void MainTest() { Assert.That(Domain.Model.Types.Contains(typeof(WrongMediaItemBase)), Is.False); - using (var session = Domain.OpenSession()) - using (var t = session.OpenTransaction()) { - } } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0624_EntitySetSubqueryError.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0624_EntitySetSubqueryError.cs index 1054ad1da4..86281355b3 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0624_EntitySetSubqueryError.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0624_EntitySetSubqueryError.cs @@ -64,7 +64,6 @@ protected TablePartBase(Guid id) } } - [Serializable] public class Issue0624_EntitySetSubqueryError : AutoBuildTest { protected override void CheckRequirements() diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0626_SequenceContainsNoElements.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0626_SequenceContainsNoElements.cs index 6d68a89e80..6001840217 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0626_SequenceContainsNoElements.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0626_SequenceContainsNoElements.cs @@ -56,7 +56,6 @@ public Position(Guid id) } } - [Serializable] public class Issue0626_SequenceContainsNoElements : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0628_ExecuteFutureScalarError.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0628_ExecuteFutureScalarError.cs index e6258cd12f..b3e5eb53ed 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0628_ExecuteFutureScalarError.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0628_ExecuteFutureScalarError.cs @@ -30,13 +30,12 @@ class Item : Entity } } - [Serializable] public class Issue0628_ExecuteFutureScalarError : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof(Item).Assembly, typeof(Item).Namespace); + config.Types.Register(typeof(Item)); return config; } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0630_NullReferenceOnSelect.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0630_NullReferenceOnSelect.cs index f20a1e4f63..a1b7a38420 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0630_NullReferenceOnSelect.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0630_NullReferenceOnSelect.cs @@ -16,7 +16,6 @@ namespace Xtensive.Orm.Tests.Issues { namespace Issue0630_NullReferenceOnSelect_Model { - [Serializable] [HierarchyRoot] public class MyEntity : Entity { @@ -27,7 +26,6 @@ public class MyEntity : Entity public string Text { get; set; } } - [Serializable] [HierarchyRoot] public class MyEntity2 : Entity { @@ -45,12 +43,11 @@ public class ValObj } } - [Serializable] public class Issue0630_NullReferenceOnSelect : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() { - DomainConfiguration config = base.BuildConfiguration(); + var config = base.BuildConfiguration(); config.Types.RegisterCaching(typeof(MyEntity).Assembly, typeof(MyEntity).Namespace); return config; } @@ -62,11 +59,10 @@ public void MainTest() using (var transactionScope = session.OpenTransaction()) { // Creating new persistent object // Creating new persistent object - var helloWorld = new MyEntity - { + var helloWorld = new MyEntity { Text = "Hello World!" - }; var helloWorld2 = new MyEntity2 - { + }; + var helloWorld2 = new MyEntity2 { Text = "Hello World!" }; @@ -76,13 +72,13 @@ public void MainTest() using (var transactionScope = session.OpenTransaction()) { var c = session.Query.All() - .Select(a => new ValObj {Id = a.Id, Text = a.Text}) + .Select(a => new ValObj { Id = a.Id, Text = a.Text }) .ToList(); var d = session.Query.All() .Select(a => new ValObj { Id = a.Id, Text = a.Text }) .ToList(); - var a11 = new ArrayList() {session.Query.All().Select("new(Id,Text)")}; - var b12 = new ArrayList() {session.Query.All().Select("new(Id,Text)")}; + var a11 = new ArrayList() { session.Query.All().Select("new(Id,Text)") }; + var b12 = new ArrayList() { session.Query.All().Select("new(Id,Text)") }; } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0634_PairToMisuse.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0634_PairToMisuse.cs index 101402e3d6..0f1dbd4829 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0634_PairToMisuse.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0634_PairToMisuse.cs @@ -163,7 +163,7 @@ private static void Check(params Type[] types) foreach (var type in types) configuration.Types.Register(type); configuration.Types.Register(typeof (Helper)); - AssertEx.Throws(() => Domain.Build(configuration)); + AssertEx.Throws(() => Domain.Build(configuration).Dispose()); } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0641_GroupBySumError.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0641_GroupBySumError.cs index d53b6d540e..36f62718d8 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0641_GroupBySumError.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0641_GroupBySumError.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Issues { namespace Issue0641_GroupBySumError_Model { - [Serializable] [HierarchyRoot] public class MyEntity : Entity { @@ -42,13 +41,13 @@ public class Line : Entity } } - [Serializable] public class Issue0641_GroupBySumError : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() { - DomainConfiguration config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof (Line).Assembly, typeof (Line).Namespace); + var config = base.BuildConfiguration(); + config.Types.Register(typeof(MyEntity)); + config.Types.Register(typeof(Line)); return config; } @@ -56,44 +55,37 @@ protected override DomainConfiguration BuildConfiguration() public void MainTest() { using (var session = Domain.OpenSession()) - { - using (TransactionScope transactionScope = session.OpenTransaction()) - { - // Creating new persistent object - var helloWorld = new MyEntity - { - Text = "Hello World!", - Lines = - { - new Line {Rate = 5.5M, Amount = 2M}, - new Line {Rate = 5.5M, Amount = 2M}, - new Line {Rate = 5.5M, Amount = 2M}, - new Line {Rate = 5.5M, Amount = 2M}, - new Line {Rate = 5.5M, Amount = 2M}, - new Line {Rate = 5.5M, Amount = 2M} - } - }; - // Committing transaction - transactionScope.Complete(); - } + using (var transactionScope = session.OpenTransaction()) { + // Creating new persistent object + var helloWorld = new MyEntity { + Text = "Hello World!", + Lines = { + new Line {Rate = 5.5M, Amount = 2M}, + new Line {Rate = 5.5M, Amount = 2M}, + new Line {Rate = 5.5M, Amount = 2M}, + new Line {Rate = 5.5M, Amount = 2M}, + new Line {Rate = 5.5M, Amount = 2M}, + new Line {Rate = 5.5M, Amount = 2M} + } + }; + // Committing transaction + transactionScope.Complete(); } // Reading all persisted objects from another Session using (var session = Domain.OpenSession()) - { - using (var transactionScope = session.OpenTransaction()) { - var query = from l in session.Query.All().First().Lines - group l by l.Rate.GetValueOrDefault() into g - select new {Rate = g.Key, BaseAmount = g.Sum(l => l.Amount.GetValueOrDefault())}; - var actual = query.ToList().Single(); - var expected = (from l in session.Query.All().First().Lines.ToList() - group l by l.Rate.GetValueOrDefault() - into g - select new {Rate = g.Key, BaseAmount = g.Sum(l => l.Amount.GetValueOrDefault())}) - .Single(); - Assert.That(actual.Rate, Is.EqualTo(expected.Rate)); - Assert.That(actual.BaseAmount, Is.EqualTo(expected.BaseAmount)); - } + using (var transactionScope = session.OpenTransaction()) { + var query = from l in session.Query.All().First().Lines + group l by l.Rate.GetValueOrDefault() into g + select new { Rate = g.Key, BaseAmount = g.Sum(l => l.Amount.GetValueOrDefault()) }; + var actual = query.ToList().Single(); + var expected = (from l in session.Query.All().First().Lines.ToList() + group l by l.Rate.GetValueOrDefault() + into g + select new { Rate = g.Key, BaseAmount = g.Sum(l => l.Amount.GetValueOrDefault()) }) + .Single(); + Assert.That(actual.Rate, Is.EqualTo(expected.Rate)); + Assert.That(actual.BaseAmount, Is.EqualTo(expected.BaseAmount)); } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0643_EntitySetAddInCtor.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0643_EntitySetAddInCtor.cs index 475aea3a4e..e395adb0f7 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0643_EntitySetAddInCtor.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0643_EntitySetAddInCtor.cs @@ -32,8 +32,7 @@ public class Module : ModuleBase { public Module() { - new ModuleItem(); -// Items.Add(new ModuleItem()); + _ = Items.Add(new ModuleItem()); } } @@ -51,12 +50,11 @@ public class ModuleItem : Entity } } - [Serializable] public class Issue0643_EntitySetAddInCtor : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() { - DomainConfiguration config = base.BuildConfiguration(); + var config = base.BuildConfiguration(); config.Types.RegisterCaching(typeof (Module).Assembly, typeof (Module).Namespace); return config; } @@ -64,14 +62,21 @@ protected override DomainConfiguration BuildConfiguration() [Test] public void MainTest() { - using (var session = Domain.OpenSession()) { - using (var transactionScope = session.OpenTransaction()) { - // Creating new persistent object - var modules = new Module(); + using (var session = Domain.OpenSession()) + using (var transactionScope = session.OpenTransaction()) { + // Creating new persistent object + var modules = new Module(); - // Committing transaction - transactionScope.Complete(); - } + // Committing transaction + transactionScope.Complete(); + } + + using (var session = Domain.OpenSession()) + using (var transactionScope = session.OpenTransaction()) { + + var allItems = session.Query.All().ToList(); + Assert.That(allItems.Count, Is.EqualTo(1)); + Assert.That(allItems[0].Module, Is.Not.Null); } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0647_WrongLinqQuery.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0647_WrongLinqQuery.cs index afdfa280c4..4d995fa3c0 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0647_WrongLinqQuery.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0647_WrongLinqQuery.cs @@ -16,7 +16,6 @@ namespace Xtensive.Orm.Tests.Issues { namespace Issue0647_WrongLinqQuery_Model { - [Serializable] public abstract class EntityBase : Entity { protected EntityBase(Guid id) @@ -113,7 +112,6 @@ public MlRowlevelPermissionDocEntityField(Guid id) } } - [Serializable] public abstract class Multilink : EntityBase where TOwner : EntityBase where TLinked : EntityBase @@ -203,13 +201,12 @@ where perm.Role.Name.In(roles) && perm.Entity.SysName == effectiveEntity } - [Serializable] public class Issue0647_WrongLinqQuery : AutoBuildTest { - private Guid globalId1 = new Guid("A3A01D2F-41A9-416E-8513-6C2F55224B56"); - private Guid globalId2 = new Guid("FDBDBCF1-0117-4508-89A3-F47A9A098478"); - private Guid globalId3 = new Guid("EC2F180E-48BB-445C-BE95-C384B069D60B"); - private Guid globalId4 = new Guid("07F0DF2A-B55F-44BE-BB9B-034A875BF0DE"); + private readonly Guid globalId1 = new Guid("A3A01D2F-41A9-416E-8513-6C2F55224B56"); + private readonly Guid globalId2 = new Guid("FDBDBCF1-0117-4508-89A3-F47A9A098478"); + private readonly Guid globalId3 = new Guid("EC2F180E-48BB-445C-BE95-C384B069D60B"); + private readonly Guid globalId4 = new Guid("07F0DF2A-B55F-44BE-BB9B-034A875BF0DE"); protected override void CheckRequirements() { @@ -219,7 +216,7 @@ protected override void CheckRequirements() protected override DomainConfiguration BuildConfiguration() { - DomainConfiguration config = base.BuildConfiguration(); + var config = base.BuildConfiguration(); config.Types.RegisterCaching(typeof(Role).Assembly, typeof(Role).Namespace); return config; } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0648_MultiThreadNullReference.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0648_MultiThreadNullReference.cs index 7d1feb7866..50a5137cb5 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0648_MultiThreadNullReference.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0648_MultiThreadNullReference.cs @@ -23,7 +23,6 @@ public class Simple : Entity } } - [Serializable] public class Issue0648_MultiThreadNullReference : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() @@ -42,20 +41,20 @@ public void MainTest() using (var session = Domain.OpenSession()) { using (var transactionScope = session.OpenTransaction()) { - new Simple(); - new Simple(); - new Simple(); - new Simple(); - new Simple(); + _ = new Simple(); + _ = new Simple(); + _ = new Simple(); + _ = new Simple(); + _ = new Simple(); for (int i = 0; i < threadCount; i++) { var completionEvent = completionEvents[i] = new ManualResetEvent(false); - ThreadPool.QueueUserWorkItem(state => { + _ = ThreadPool.QueueUserWorkItem(state => { using (var session2 = Domain.OpenSession()) using (var t = session2.OpenTransaction()) { var count = session2.Query.All().Count(); } - completionEvent.Set(); + _ = completionEvent.Set(); }); } @@ -64,7 +63,7 @@ public void MainTest() } } - WaitHandle.WaitAll(completionEvents); + _ = WaitHandle.WaitAll(completionEvents); foreach (var item in completionEvents) item.Close(); diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0676_NonNullableReferenceBug.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0676_NonNullableReferenceBug.cs index b7cf3b396b..d969b50a32 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0676_NonNullableReferenceBug.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0676_NonNullableReferenceBug.cs @@ -16,7 +16,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0676.Model { - [Serializable] [HierarchyRoot] public class Animal : Entity { @@ -48,7 +47,6 @@ public Animal(string name) } } - [Serializable] [HierarchyRoot] public class Person : Entity, IHasNullEntity diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0696_EntitySetItemAddBug.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0696_EntitySetItemAddBug.cs index b7799d94d4..eb98cbbda7 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0696_EntitySetItemAddBug.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0696_EntitySetItemAddBug.cs @@ -17,7 +17,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0696.Model { - [Serializable] [HierarchyRoot] public class Master : Entity { @@ -37,7 +36,6 @@ public override string ToString() } } - [Serializable] [HierarchyRoot] public class Detail : Entity { @@ -161,14 +159,14 @@ public void EventSequenceTest() d1.Master = m1; d2.Master = m1; d1.Master = m2; - m1.Details.Add(d2); + _ = m1.Details.Add(d2); EventHandler h1 = (s, e) => { isNewChain = true; - m2.Details.Add(d3); + _ = m2.Details.Add(d3); }; session.Events.EntitySetItemRemove += h1; - m2.Details.Add(d2); + _ = m2.Details.Add(d2); } } @@ -227,7 +225,7 @@ private void CheckDirection(AssociationInfo association, Entity owner, Entity it } int depth; if (entry.CheckDirection(direction, out depth)) - stack.Pop(); + _ = stack.Pop(); TestLog.Info($"{message.Indent(depth * 2)}"); } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0715_NestedTypeBug.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0715_NestedTypeBug.cs index 601dacec27..5a0d406100 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0715_NestedTypeBug.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0715_NestedTypeBug.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0715.Model { public static class Forest { - [Serializable] [HierarchyRoot] public class Animal : Entity { @@ -32,7 +31,6 @@ public override string ToString() } } - [Serializable] [HierarchyRoot] public class Animal : Entity { @@ -68,8 +66,8 @@ public void StandardTest() { using (var session = Domain.OpenSession()) using (var tx = session.OpenTransaction()) { - new Forest.Animal {Name = "Forest Animal"}; - new Animal {Name = "Animal"}; + _ = new Forest.Animal {Name = "Forest Animal"}; + _ = new Animal {Name = "Animal"}; } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0717_VersionCheckBug.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0717_VersionCheckBug.cs index 932941790d..ef6966d2da 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0717_VersionCheckBug.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0717_VersionCheckBug.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0717.Model { - [Serializable] [HierarchyRoot] public class Person : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0733_UseINNER_JOIN.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0733_UseINNER_JOIN.cs index de09470e99..a8e6bc7622 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0733_UseINNER_JOIN.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0733_UseINNER_JOIN.cs @@ -5,62 +5,46 @@ // Created: 2010.07.12 using System; -using System.Diagnostics; +using System.Linq; using NUnit.Framework; using Xtensive.Orm.Configuration; -using Xtensive.Orm.Tests.Issues.Issue0737_PersistentFieldState_Model; -using System.Linq; +using Xtensive.Orm.Tests.Issues.Issue0733_UseINNER_JOIN_Model; namespace Xtensive.Orm.Tests.Issues { - namespace Issue0737_PersistentFieldState_Model + namespace Issue0733_UseINNER_JOIN_Model { [HierarchyRoot] - public class Derived : Entity + public class Person : Entity { - [Key,Field] + [Key, Field] public int Id { get; private set; } [Field] - public new string State { get; set; } - } - - [HierarchyRoot, Serializable] - [TableMapping("States")] - [KeyGenerator(KeyGeneratorKind.None)] - public class State : Entity - { - [Key] - [Field(Length = 100)] - public string ID { get; private set; } + public string Name { get; set; } - [Field] - [Association(PairTo = "State")] - public EntitySet AbiturAds { get; set; } + [Field(Nullable = false)] + public City City { get; set; } } - [HierarchyRoot, Serializable] - [TableMapping("AbiturAds")] - public class AbiturAd : Entity + [HierarchyRoot] + public class City : Entity { - [Key] - [Field] - public int ID { get; private set; } + [Key, Field] + public int Id { get; private set; } [Field] - [FieldMapping("StateID")] - public new State State { get; set; } + public string Name { get; set; } } } - [Serializable] - public class Issue0737_PersistentFieldState : AutoBuildTest + public class Issue0733_UseINNER_JOIN : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() { - DomainConfiguration config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof(Derived).Assembly, typeof(Derived).Namespace); + var config = base.BuildConfiguration(); + config.Types.RegisterCaching(typeof(Person).Assembly, typeof(Person).Namespace); return config; } @@ -69,10 +53,16 @@ public void MainTest() { using (var session = Domain.OpenSession()) using (var t = session.OpenTransaction()) { - var derived = new Derived() {State = "new"}; + var msk = new City() { Name = "Moscow" }; + var ekb = new City() { Name = "Yekaterinburg" }; + for (int i = 0; i < 100; i++) { + _ = new Person() { Name = "Alex " + i, City = msk }; + _ = new Person() { Name = "Ivan " + i, City = ekb }; + } - var list = session.Query.All() - .Where(d => d.State == "new") + var list = session.Query.All() + .OrderBy(p => p.City.Name) + .Take(10) .ToList(); } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0737_PersistentFieldState.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0737_PersistentFieldState.cs index 4b3ad9badd..c7f34d3e2a 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0737_PersistentFieldState.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0737_PersistentFieldState.cs @@ -5,48 +5,60 @@ // Created: 2010.07.12 using System; -using System.Diagnostics; +using System.Linq; using NUnit.Framework; using Xtensive.Orm.Configuration; -using Xtensive.Orm.Tests.Issues.Issue0733_UseINNER_JOIN_Model; -using System.Linq; +using Xtensive.Orm.Tests.Issues.Issue0737_PersistentFieldState_Model; namespace Xtensive.Orm.Tests.Issues { - namespace Issue0733_UseINNER_JOIN_Model + namespace Issue0737_PersistentFieldState_Model { [HierarchyRoot] - public class Person : Entity + public class Derived : Entity { - [Key,Field] + [Key, Field] public int Id { get; private set; } [Field] - public string Name { get; set; } + public new string State { get; set; } + } - [Field(Nullable = false)] - public City City { get; set; } + [HierarchyRoot] + [TableMapping("States")] + [KeyGenerator(KeyGeneratorKind.None)] + public class State : Entity + { + [Key] + [Field(Length = 100)] + public string ID { get; private set; } + + [Field] + [Association(PairTo = "State")] + public EntitySet AbiturAds { get; set; } } [HierarchyRoot] - public class City : Entity + [TableMapping("AbiturAds")] + public class AbiturAd : Entity { - [Key,Field] - public int Id { get; private set; } + [Key] + [Field] + public int ID { get; private set; } [Field] - public string Name { get; set; } + [FieldMapping("StateID")] + public new State State { get; set; } } } - [Serializable] - public class Issue0733_UseINNER_JOIN : AutoBuildTest + public class Issue0737_PersistentFieldState : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() { - DomainConfiguration config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof(Person).Assembly, typeof(Person).Namespace); + var config = base.BuildConfiguration(); + config.Types.RegisterCaching(typeof(Derived).Assembly, typeof(Derived).Namespace); return config; } @@ -55,18 +67,12 @@ public void MainTest() { using (var session = Domain.OpenSession()) using (var t = session.OpenTransaction()) { - var msk = new City() {Name = "Moscow"}; - var ekb = new City() {Name = "Yekaterinburg"}; - for (int i = 0; i < 100; i++) { - new Person() {Name = "Alex " + i, City = msk}; - new Person() {Name = "Ivan " + i, City = ekb}; - } + var derived = new Derived() { State = "new" }; - var list = session.Query.All() - .OrderBy(p => p.City.Name) - .Take(10) + var list = session.Query.All() + .Where(d => d.State == "new") .ToList(); } } } -} \ No newline at end of file +} diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0764_LinqTranslationError.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0764_LinqTranslationError.cs index 4d7391d240..5c4e3a455f 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0764_LinqTranslationError.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0764_LinqTranslationError.cs @@ -5,17 +5,16 @@ // Created: 2010.07.12 using System; -using System.Diagnostics; +using System.Linq; using NUnit.Framework; using Xtensive.Orm.Configuration; using Xtensive.Orm.Tests.Issues.Issue0764_LinqTranslationError_Model; -using System.Linq; + namespace Xtensive.Orm.Tests.Issues { namespace Issue0764_LinqTranslationError_Model { - [Serializable] [HierarchyRoot] public class MyEntity : Entity { @@ -46,13 +45,12 @@ public class Link : Entity } } - [Serializable] public class Issue0764_LinqTranslationError : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() { - DomainConfiguration config = base.BuildConfiguration(); + var config = base.BuildConfiguration(); config.Types.RegisterCaching(typeof(MyEntity).Assembly, typeof(MyEntity).Namespace); return config; } @@ -71,7 +69,7 @@ from l in session.Query.All() where l.LinkSource == source && l.LinkDestination.Text == "Destination" select l.LinkDestination; - query.ToList(); + _ = query.ToList(); } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0765_LinqTranslationError.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0765_LinqTranslationError.cs index f136b78424..831484fc38 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0765_LinqTranslationError.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0765_LinqTranslationError.cs @@ -51,7 +51,6 @@ public class InvoiceExtract : Entity } } - [Serializable] public class Issue0765_LinqTranslationError : AutoBuildTest { diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0766_LinqTranslationError.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0766_LinqTranslationError.cs index 712b9fcbca..f2f46992dd 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0766_LinqTranslationError.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0766_LinqTranslationError.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Issues { - [Serializable] public class Issue0766_LinqTranslationError : ChinookDOModelTest { protected override void CheckRequirements() diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0767_QueryByInterfaceException.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0767_QueryByInterfaceException.cs index 933d9f7586..39d439618d 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0767_QueryByInterfaceException.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0767_QueryByInterfaceException.cs @@ -64,13 +64,12 @@ public class Bar : BusinessEntity, IHasName } - [Serializable] public class Issue0767_QueryByInterfaceException : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() { - DomainConfiguration config = base.BuildConfiguration(); + var config = base.BuildConfiguration(); config.Types.RegisterCaching(typeof(BusinessEntity).Assembly, typeof(BusinessEntity).Namespace); return config; } @@ -79,10 +78,9 @@ protected override DomainConfiguration BuildConfiguration() public void MainTest() { using (var session = Domain.OpenSession()) - using (var t = session.OpenTransaction()) - { - new Foo() {Name = "foo", Some = 10, Tag = "foo tag"}; - new Bar() {Name = "bar", Some = Guid.NewGuid(), Tag = "bar tag"}; + using (var t = session.OpenTransaction()) { + _ = new Foo() {Name = "foo", Some = 10, Tag = "foo tag"}; + _ = new Bar() { Name = "bar", Some = Guid.NewGuid(), Tag = "bar tag" }; var all = session.Query.All().ToList(); Assert.That(all.Count, Is.EqualTo(2)); diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0768_WrongJoinBehavior.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0768_WrongJoinBehavior.cs index ffc54d0f89..f4de0536f2 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0768_WrongJoinBehavior.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0768_WrongJoinBehavior.cs @@ -18,7 +18,6 @@ namespace Xtensive.Orm.Tests.Issues { namespace Issue0768_WrongJoinBehavior_Model { - [Serializable] [HierarchyRoot] public class Node : Entity { @@ -46,7 +45,6 @@ public Node(Guid id) public Node Parent { get; set; } } - [Serializable] [HierarchyRoot] public class Reference : Entity { @@ -67,17 +65,16 @@ public Reference(Guid id) [Field] public string Name { get; set; } } - } - [Serializable] public class Issue0768_WrongJoinBehavior : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() { - DomainConfiguration config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof(Issue0768_WrongJoinBehavior_Model.Node).Assembly, typeof(Issue0768_WrongJoinBehavior_Model.Node).Namespace); + var config = base.BuildConfiguration(); + config.Types.Register(typeof(Reference)); + config.Types.Register(typeof(Node)); return config; } @@ -87,19 +84,19 @@ public void MainTest() using (var session = Domain.OpenSession()) using (var t = session.OpenTransaction()) { var ref1 = new Reference(Guid.NewGuid()) { Name = "q", Version = DateTime.Now }; - var node1 = new Issue0768_WrongJoinBehavior_Model.Node(Guid.NewGuid()) { Name = "w", Ref = ref1, Version = DateTime.Now }; + var node1 = new Node(Guid.NewGuid()) { Name = "w", Ref = ref1, Version = DateTime.Now }; var ref2 = new Reference(Guid.NewGuid()) { Name = "p5", Version = DateTime.Now }; - var node2 = new Issue0768_WrongJoinBehavior_Model.Node(Guid.NewGuid()) { Name = "pp", Ref = ref1, Version = DateTime.Now }; + var node2 = new Node(Guid.NewGuid()) { Name = "pp", Ref = ref1, Version = DateTime.Now }; var ref3 = new Reference(Guid.NewGuid()) { Name = "q2", Version = DateTime.Now }; - var node3 = new Issue0768_WrongJoinBehavior_Model.Node(Guid.NewGuid()) { Name = "w2", Ref = ref1, Version = DateTime.Now, Parent = node2 }; + var node3 = new Node(Guid.NewGuid()) { Name = "w2", Ref = ref1, Version = DateTime.Now, Parent = node2 }; t.Complete(); } using (var session = Domain.OpenSession()) using (var t = session.OpenTransaction()) { - var list = session.Query.All().Select(node => new { Parent = node.Parent.Ref.Name, node.Name }).ToList(); + var list = session.Query.All().Select(node => new { Parent = node.Parent.Ref.Name, node.Name }).ToList(); Assert.That(list.Count(), Is.EqualTo(3)); // Current wrong way diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0771_AbstractTypeRegistration.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0771_AbstractTypeRegistration.cs index 5daddc630a..666dc361a7 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0771_AbstractTypeRegistration.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0771_AbstractTypeRegistration.cs @@ -1,16 +1,12 @@ -// Copyright (C) 2010 Xtensive LLC. +// Copyright (C) 2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Alexis Kochetov // Created: 2010.07.26 using System; -using System.Diagnostics; -using System.Linq.Expressions; -using NUnit.Framework; using System.Linq; -using Xtensive.Orm.Configuration; -using Xtensive.Orm.Model; +using NUnit.Framework; using Xtensive.Orm.Tests.Issues.Issue0771_AbstractTypeRegistration_Model; namespace Xtensive.Orm.Tests.Issues @@ -37,17 +33,16 @@ public class E : C {} } - [Serializable] public class Issue0771_AbstractTypeRegistration { [Test] -// [ExpectedException(typeof(DomainBuilderException))] public void AbstractClassPerHierarchyTest() { var config = DomainConfigurationFactory.Create(); config.Types.Register(typeof (A)); - var domain = Domain.Build(config); + + using (var domain = Domain.Build(config)) using (var session = domain.OpenSession()) using (var t = session.OpenTransaction()) { var list = session.Query.All().ToList(); @@ -55,13 +50,13 @@ public void AbstractClassPerHierarchyTest() } [Test] -// [ExpectedException(typeof(DomainBuilderException))] public void AbstractHierarchyTest() { var config = DomainConfigurationFactory.Create(); config.Types.Register(typeof(A)); config.Types.Register(typeof(B)); - var domain = Domain.Build(config); + + using (var domain = Domain.Build(config)) using (var session = domain.OpenSession()) using (var t = session.OpenTransaction()) { var listA = session.Query.All().ToList(); @@ -78,7 +73,8 @@ public void NonAbstractLeafTest() config.Types.Register(typeof(C)); config.Types.Register(typeof(D)); config.Types.Register(typeof(E)); - var domain = Domain.Build(config); + + using (var domain = Domain.Build(config)) using (var session = domain.OpenSession()) using (var t = session.OpenTransaction()) { var listA = session.Query.All().ToList(); diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0773_UnableTranslateUnionQuery.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0773_UnableTranslateUnionQuery.cs index 61b7800f9e..a44338b89c 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0773_UnableTranslateUnionQuery.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0773_UnableTranslateUnionQuery.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Issues { - [Serializable] public class Issue0773_UnableTranslateUnionQuery : ChinookDOModelTest { private class DTO diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0775_WrongLinqQueryOverComputedFields.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0775_WrongLinqQueryOverComputedFields.cs index 971b472bf7..ea5de0cf63 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0775_WrongLinqQueryOverComputedFields.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0775_WrongLinqQueryOverComputedFields.cs @@ -99,7 +99,6 @@ public Fund(Guid id) } } - [Serializable] public class Issue0775_WrongLinqQueryOverComputedFields : AutoBuildTest { protected override void CheckRequirements() diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0776_OrderingCorrectorOfAggregateProvider.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0776_OrderingCorrectorOfAggregateProvider.cs index 9c398225fa..6f0c243813 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0776_OrderingCorrectorOfAggregateProvider.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0776_OrderingCorrectorOfAggregateProvider.cs @@ -17,7 +17,6 @@ namespace Xtensive.Orm.Tests.Issues { namespace Issue0776_OrderingCorrectorOfAggregateProvider_Model { - [Serializable] [HierarchyRoot] public class MyEntity : Entity { @@ -66,7 +65,6 @@ public static Expression MyEntText(Expression assignmentExpression) } } - [Serializable] public class Issue0776_OrderingCorrectorOfAggregateProvider : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0777_WrongLinqQueryConditional.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0777_WrongLinqQueryConditional.cs index e79d28c3bf..f6f6eb9847 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0777_WrongLinqQueryConditional.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0777_WrongLinqQueryConditional.cs @@ -29,11 +29,10 @@ public class BooleanHell : Entity } } - [Serializable] public class Issue0777_WrongLinqQueryConditional : AutoBuildTest { - DateTime? apocalypseNow = DateTime.Now; - DateTime? apocalypseNever = null; + private readonly DateTime? apocalypseNow = DateTime.Now; + private readonly DateTime? apocalypseNever = null; protected override DomainConfiguration BuildConfiguration() { @@ -47,7 +46,7 @@ public void MainTest() { using (var session = Domain.OpenSession()) using (var t = session.OpenTransaction()) { - new BooleanHell { ApocalypseDate = new DateTime(2012, 12, 12), DefaultApocalypseDate = new DateTime(2012, 12, 12)}; + _ = new BooleanHell { ApocalypseDate = new DateTime(2012, 12, 12), DefaultApocalypseDate = new DateTime(2012, 12, 12)}; session.SaveChanges(); var firstHell = session.Query.All() diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0785_GenericStructureBugs.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0785_GenericStructureBugs.cs index 1f25cbabd3..43461584b1 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0785_GenericStructureBugs.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0785_GenericStructureBugs.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0785.Model { - [Serializable] [HierarchyRoot] public class Book : Entity { @@ -47,7 +46,6 @@ public class BookInfo : ItemInfo } - [Serializable] public class RefHolder : Structure { [Field] diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0808_StructSerialization.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0808_StructSerialization.cs deleted file mode 100644 index 3135b9554b..0000000000 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0808_StructSerialization.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.Serialization; -using NUnit.Framework; -using Xtensive.Core; -using Xtensive.Linq.SerializableExpressions; - -namespace Xtensive.Orm.Tests.Issues -{ - public struct UnifiedCustomerID - { - public int Id; - } - - [TestFixture] - public class Issue0808_StructSerialization - { - public IEnumerable SerializableExpressionTypes - { - get - { - yield return typeof (SerializableBinaryExpression); - yield return typeof (SerializableConditionalExpression); - yield return typeof (SerializableConstantExpression); - yield return typeof (SerializableElementInit); - yield return typeof (SerializableExpression); - yield return typeof (SerializableInvocationExpression); - yield return typeof (SerializableLambdaExpression); - yield return typeof (SerializableListInitExpression); - yield return typeof (SerializableMemberAssignment); - yield return typeof (SerializableMemberBinding); - yield return typeof (SerializableMemberExpression); - yield return typeof (SerializableMemberInitExpression); - yield return typeof (SerializableMemberListBinding); - yield return typeof (SerializableMemberMemberBinding); - yield return typeof (SerializableMethodCallExpression); - yield return typeof (SerializableNewArrayExpression); - yield return typeof (SerializableNewExpression); - yield return typeof (SerializableParameterExpression); - yield return typeof (SerializableTypeBinaryExpression); - yield return typeof (SerializableUnaryExpression); - } - } - - [Test] - public void MainTest() - { - var t = typeof(UnifiedCustomerID); - Expression> ex = a => new UnifiedCustomerID { Id = 2 }; - var serializableExpression = ex.ToSerializableExpression(); - using (var memoryStream = new MemoryStream()) { - var serializer = new DataContractSerializer(typeof(SerializableLambdaExpression), - SerializableExpressionTypes.Except(Enumerable.Repeat(typeof(SerializableLambdaExpression), 1))); - - serializer.WriteObject(memoryStream, serializableExpression); - - memoryStream.Position = 0; - - var deserializedExpression = (SerializableLambdaExpression) serializer.ReadObject(memoryStream); - - var ex2 = deserializedExpression.ToExpression(); - } - } - } -} diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0827_LinqDtoMaterialization.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0827_LinqDtoMaterialization.cs index 786f0e83c6..b8f74e879a 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0827_LinqDtoMaterialization.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0827_LinqDtoMaterialization.cs @@ -45,13 +45,13 @@ public class DocEntity : BaseEntity namespace Xtensive.Orm.Tests.Issues { - [Serializable] public class Issue0827_LinqDtoMaterialization : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof (DocEntity).Assembly, typeof (DocEntity).Namespace); + config.Types.Register(typeof(DocEntity)); + config.Types.Register(typeof(BaseEntity)); return config; } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0828_LinqMaterializeException.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0828_LinqMaterializeException.cs index 938660e51c..a20a55d25c 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0828_LinqMaterializeException.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0828_LinqMaterializeException.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Issues_Issue0828_LinqMaterializeException { - [Serializable] [HierarchyRoot] public class MyEntity : Entity { @@ -70,25 +69,25 @@ protected override DomainConfiguration BuildConfiguration() return config; } + protected override void CheckRequirements() => Require.AllFeaturesSupported(ProviderFeatures.ScalarSubqueries); + [Test] public void MainTest() { - Require.AllFeaturesSupported(ProviderFeatures.ScalarSubqueries); - using (var session = Domain.OpenSession()) { - using (var transaction = session.OpenTransaction()) { - var myEntity = new MyEntity() { - Date = DateTime.Now, - Text = "Text" - }; - var query = session.Query.All() - .Select(e => new { - MyEntity = e, - Year = (int?) e.Date.Value.Year, - Status = e.Infos.OfType().Any() ? Status.Success : (e.Infos.OfType().Any() ? Status.Error : Status.Unknown) - }) - .Select(o => new object[] {o.MyEntity.Id, o.Year, o.Status}); - var result = query.ToList(); - } + using (var session = Domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var myEntity = new MyEntity() { + Date = DateTime.Now, + Text = "Text" + }; + var query = session.Query.All() + .Select(e => new { + MyEntity = e, + Year = (int?) e.Date.Value.Year, + Status = e.Infos.OfType().Any() ? Status.Success : (e.Infos.OfType().Any() ? Status.Error : Status.Unknown) + }) + .Select(o => new object[] { o.MyEntity.Id, o.Year, o.Status }); + var result = query.ToList(); } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue0839_MultithreadingBug.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue0839_MultithreadingBug.cs index 7b50f51476..8700de3d2b 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue0839_MultithreadingBug.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue0839_MultithreadingBug.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue0839_MultithreadingBug_Model { - [Serializable] [HierarchyRoot] [Index("NextRun")] public class BaseEntity : Entity @@ -27,7 +26,6 @@ public class BaseEntity : Entity public DateTime NextRun { get; set; } } - [Serializable] [Index("Text", Unique = true)] public class UniqueTextEntity : BaseEntity { diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueA363_WrongInnerJoin.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueA363_WrongInnerJoin.cs index e03369b35f..781d882adb 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueA363_WrongInnerJoin.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueA363_WrongInnerJoin.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Issues { namespace IssueA363_WrongInnerJoin_Model { - [Serializable] [HierarchyRoot] public abstract class MyEntity : Entity { @@ -48,7 +47,6 @@ public class MyEntityWithText : MyEntity } } - [Serializable] public class IssueA363_WrongInnerJoin : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueA399_SetPropertyForPrivatePropertiesOfInheritors.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueA399_SetPropertyForPrivatePropertiesOfInheritors.cs index ca9bcd374a..239eacb7b1 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueA399_SetPropertyForPrivatePropertiesOfInheritors.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueA399_SetPropertyForPrivatePropertiesOfInheritors.cs @@ -32,7 +32,6 @@ public class Derived : Base } } - [Serializable] public class IssueA399_SetPropertyForPrivatePropertiesOfInheritors : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueA401_AmbiguousMatchFoundException.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueA401_AmbiguousMatchFoundException.cs index a8b034e716..04dd2824c7 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueA401_AmbiguousMatchFoundException.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueA401_AmbiguousMatchFoundException.cs @@ -6,11 +6,11 @@ using System; using System.Diagnostics; +using System.Linq; using NUnit.Framework; using Xtensive.Orm.Configuration; -using Xtensive.Orm.Tests.Issues.IssueA401_AmbiguousMatchFoundException_Model; -using System.Linq; using Xtensive.Orm.Validation; +using Xtensive.Orm.Tests.Issues.IssueA401_AmbiguousMatchFoundException_Model; namespace Xtensive.Orm.Tests.Issues { @@ -43,20 +43,23 @@ public class Some : AbstractEntity } } - [Serializable] - public class IssueA401_AmbiguousMatchFoundException + public class IssueA401_AmbiguousMatchFoundException : AutoBuildTest { + protected override DomainConfiguration BuildConfiguration() + { + var config = base.BuildConfiguration(); + config.Types.RegisterCaching(typeof(ConcreteEntity).Assembly, typeof(ConcreteEntity).Namespace); + return config; + } + [Test] public void MainTest() { - var config = DomainConfigurationFactory.Create(); - config.Types.RegisterCaching(typeof(ConcreteEntity).Assembly, typeof(ConcreteEntity).Namespace); - var domain = Domain.Build(config); - using (var session = domain.OpenSession()) + using (var session = Domain.OpenSession()) using (var t = session.OpenTransaction()) { var concrete = new ConcreteEntity(new Some()); - var result = Query.All().ToList(); + var result = session.Query.All().ToList(); Assert.That(result.Count, Is.EqualTo(1)); t.Complete(); } diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueA408_TargetException.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueA408_TargetException.cs index 7b0d464569..54e55e1922 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueA408_TargetException.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueA408_TargetException.cs @@ -49,7 +49,6 @@ public class Ref : Entity } } - [Serializable] public class IssueA408_TargetException : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() @@ -63,26 +62,25 @@ protected override DomainConfiguration BuildConfiguration() public void MainTest() { using (var session = Domain.OpenSession()) - using (var t = session.OpenTransaction()) - { - var some = new Some {Tag = 100500, Reference = new Ref{Tag = 9000}, Structure = new Struct{Tag = 777}}; + using (var t = session.OpenTransaction()) { + var some = new Some { Tag = 100500, Reference = new Ref { Tag = 9000 }, Structure = new Struct { Tag = 777 } }; var tagObject = some.GetProperty("Tag"); var tagValue = some.GetProperty("Tag"); var tagIndexed = some["Tag"]; AssertEx.Throws(() => some.GetProperty("Tag")); Assert.That(tagValue, Is.EqualTo(100500)); - Assert.That((uint)tagObject, Is.EqualTo(100500)); - Assert.That((uint)tagIndexed, Is.EqualTo(100500)); + Assert.That((uint) tagObject, Is.EqualTo(100500)); + Assert.That((uint) tagIndexed, Is.EqualTo(100500)); var refObject = some.GetProperty("Reference.Tag"); var refValue = some.Reference.Tag; Assert.That(refValue, Is.EqualTo(9000)); - Assert.That((uint)refObject, Is.EqualTo(9000)); + Assert.That((uint) refObject, Is.EqualTo(9000)); var strObject = some.GetProperty("Structure.Tag"); var strValue = some.Structure.Tag; Assert.That(strValue, Is.EqualTo(777)); - Assert.That((uint)strObject, Is.EqualTo(777)); + Assert.That((uint) strObject, Is.EqualTo(777)); some.SetProperty("Tag", 111u); some.SetProperty("Reference.Tag", 111u); diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueA413_KeyNotFoundException.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueA413_KeyNotFoundException.cs index bbfae02be9..dbbce427c8 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueA413_KeyNotFoundException.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueA413_KeyNotFoundException.cs @@ -91,7 +91,6 @@ public MyEntityViewModel(MyStatus status) var x = from e in Session.Query.All() select new MyEntitiyViewModel(e.Status)*/ } - [Serializable] public class IssueA413_KeyNotFoundException : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() @@ -106,14 +105,19 @@ public void MainTest() { using (var session = Domain.OpenSession()) using (var t = session.OpenTransaction()) { - new A {Tag = "Alpha", B = new B {Item = new Item {Name = "Item name"}}}; + _ = new A { + Tag = "Alpha", + B = new B { + Item = new Item {Name = "Item name"} + } + }; t.Complete(); } using (var session = Domain.OpenSession()) using (var t = session.OpenTransaction()) { var query = - from a in Query.All() + from a in session.Query.All() where a.Tag == "Alpha" group a by a.B into g select new { g.Key.Item.Name, Count = g.Count() }; @@ -131,13 +135,13 @@ public void EnumTest() { using (var session = Domain.OpenSession()) using (var t = session.OpenTransaction()) { - new My {Status = MyStatus.Closed}; + _ = new My { Status = MyStatus.Closed }; t.Complete(); } using (var session = Domain.OpenSession()) using (var t = session.OpenTransaction()) { - var x = from e in Query.All() + var x = from e in session.Query.All() select new MyEntityViewModel(e.Status); var list = x.ToList(); Assert.That(list.Count, Is.EqualTo(1)); diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueA418_UnableToCompileModelWithPersistentInterface.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueA418_UnableToCompileModelWithPersistentInterface.cs index fe7b157125..21130f2737 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueA418_UnableToCompileModelWithPersistentInterface.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueA418_UnableToCompileModelWithPersistentInterface.cs @@ -6,10 +6,11 @@ using System; using System.Diagnostics; +using System.Linq; using NUnit.Framework; using Xtensive.Orm.Configuration; using Xtensive.Orm.Tests.Issues.IssueA418_UnableToCompileModelWithPersistentInterface_Model; -using System.Linq; + namespace Xtensive.Orm.Tests.Issues { @@ -40,21 +41,23 @@ public class Reference : Entity } } - [Serializable] - public class IssueA418_UnableToCompileModelWithPersistentInterface + public class IssueA418_UnableToCompileModelWithPersistentInterface : AutoBuildTest { + protected override DomainConfiguration BuildConfiguration() + { + var config = base.BuildConfiguration(); + config.Types.RegisterCaching(typeof(IWithReference).Assembly, typeof(IWithReference).Namespace); + return config; + } + [Test] public void MainTest() { - var config = DomainConfigurationFactory.Create(); - config.Types.RegisterCaching(typeof (IWithReference).Assembly, typeof (IWithReference).Namespace); - var domain = Domain.Build(config); - - using (var session = domain.OpenSession()) + using (var session = Domain.OpenSession()) using (var t = session.OpenTransaction()) { - new SomeWithReference {Reference = new Reference()}; + _ = new SomeWithReference { Reference = new Reference() }; - var result = Query.All() + var result = session.Query.All() .Prefetch(s => s.Reference) .ToList(); diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueA424_QueryByInterfaceException.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueA424_QueryByInterfaceException.cs index cfbb39ff0a..9cedc0f530 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueA424_QueryByInterfaceException.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueA424_QueryByInterfaceException.cs @@ -6,24 +6,27 @@ using System; using System.Diagnostics; +using System.Linq; using NUnit.Framework; using Xtensive.Orm.Configuration; using Xtensive.Orm.Model; using Xtensive.Orm.Tests.Issues.IssueA424_QueryByInterfaceException_Model; -using System.Linq; + namespace Xtensive.Orm.Tests.Issues { namespace IssueA424_QueryByInterfaceException_Model { - [Serializable] [HierarchyRoot(InheritanceSchema = InheritanceSchema.ConcreteTable)] public abstract class Animal : Entity { [Field, Key] public int Id { get; private set; } - protected Animal(Session session) : base(session) { } + protected Animal(Session session) + : base(session) + { + } } public interface IHasLegs : IEntity @@ -37,7 +40,10 @@ public abstract class Mammal : Animal, IHasLegs [Field] public string NumberOfLegs { get; set; } - protected Mammal(Session session) : base(session) { } + protected Mammal(Session session) + : base(session) + { + } } public interface ICanRun : IHasLegs @@ -55,17 +61,19 @@ protected Cat(Session session) : base(session) { } public class Lion : Cat { - public Lion(Session session) : base(session) { } + public Lion(Session session) + : base(session) + { + } } } - [Serializable] public class IssueA424_QueryByInterfaceException : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof (IHasLegs).Assembly, typeof (IHasLegs).Namespace); + config.Types.RegisterCaching(typeof(IHasLegs).Assembly, typeof(IHasLegs).Namespace); return config; } @@ -73,10 +81,8 @@ protected override DomainConfiguration BuildConfiguration() public void MainTest() { using (var session = Domain.OpenSession()) - using (var t = session.OpenTransaction()) - { - - Query.All().ToList(); + using (var t = session.OpenTransaction()) { + _ = session.Query.All().ToList(); t.Complete(); } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueGithub0224_DelayedQueryCapture.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueGithub0224_DelayedQueryCapture.cs index f31c280efc..6a93e08869 100755 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueGithub0224_DelayedQueryCapture.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueGithub0224_DelayedQueryCapture.cs @@ -29,7 +29,6 @@ public class Item : Entity } } - [Serializable] public class IssueGithub0224_DelayedQueryCapture : AutoBuildTest { diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJIRA0003_OrderByStructureFieldLost.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJIRA0003_OrderByStructureFieldLost.cs index 6667700051..8e55a575f5 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJIRA0003_OrderByStructureFieldLost.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJIRA0003_OrderByStructureFieldLost.cs @@ -38,7 +38,6 @@ public class Address : Structure } } - [Serializable] public class IssueJIRA0003_OrderByStructureFieldLost : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() @@ -53,8 +52,8 @@ public void MainTest() { using (var session = Domain.OpenSession()) using (var t = session.OpenTransaction()) { - new Person() {Name = "Vasya", Address = new Address {City = "Moscow", PostCode = "444444"}}; - new Person() {Name = "Petya", Address = new Address {City = "Kiev", PostCode = "111111"}}; + _ = new Person() {Name = "Vasya", Address = new Address {City = "Moscow", PostCode = "444444"}}; + _ = new Person() {Name = "Petya", Address = new Address {City = "Kiev", PostCode = "111111"}}; session.SaveChanges(); var query = session.Query.All() diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJIRA0020_CustomLINQCompilerContainerInterface.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJIRA0020_CustomLINQCompilerContainerInterface.cs index 1637edcfe1..8324d3a69f 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJIRA0020_CustomLINQCompilerContainerInterface.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJIRA0020_CustomLINQCompilerContainerInterface.cs @@ -17,7 +17,6 @@ namespace Xtensive.Orm.Tests.Issues { namespace IssueJIRA0020_CustomLINQCompilerContainerInterface_Model { - [Serializable] [HierarchyRoot] public class Person : Entity, ITest { @@ -60,7 +59,6 @@ public static Expression ITestRegionName(Expression assignmentExpression) } } - [Serializable] [HierarchyRoot] public class Region : Entity { @@ -77,7 +75,6 @@ public interface ITest : IEntity } } - [Serializable] public class IssueJIRA0020_CustomLINQCompilerContainerInterface : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJIRA0036_AutoTransactionsOpenModeDoesNotWork.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJIRA0036_AutoTransactionsOpenModeDoesNotWork.cs index c451371e08..cdf3c52f47 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJIRA0036_AutoTransactionsOpenModeDoesNotWork.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJIRA0036_AutoTransactionsOpenModeDoesNotWork.cs @@ -47,7 +47,6 @@ public class Contractor : Entity } - [Serializable] public class IssueJIRA0036_AutoTransactionsOpenModeDoesNotWork : AutoBuildTest { private Session session; diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJIRA0085.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJIRA0085.cs index 926a24ee2a..56bc82afab 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJIRA0085.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJIRA0085.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Issues.IssueJIRA0085_Model { - [Serializable] [HierarchyRoot] public abstract class SomeEntity : Entity { @@ -26,7 +25,6 @@ protected SomeEntity(Session session) : base(session) {} } - [Serializable] public class FirstEntity : SomeEntity { [Field] @@ -37,7 +35,6 @@ public FirstEntity(Session session) : base(session) {} } - [Serializable] public class SecondEntity : SomeEntity { [Field] @@ -48,7 +45,6 @@ public SecondEntity(Session session) : base(session) {} } - [Serializable] public class MyEntity : Entity where TEntity : Entity { [Field, Key] @@ -71,7 +67,6 @@ public MyEntity(Session session) {} } - [Serializable] [HierarchyRoot] public abstract class NextEntity : MyEntity { @@ -82,7 +77,6 @@ protected NextEntity(Session session, SomeEntity entity) : base(session, entity) {} } - [Serializable] public class FirstChild : NextEntity { public FirstChild(Session session, SomeEntity entity) : base(session, entity) @@ -92,7 +86,6 @@ public FirstChild(Session session) : base(session) {} } - [Serializable] public class SecondChild : NextEntity { public SecondChild(Session session) diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0180_ChangeNullabilityViaUpgradeHints/Upgrader.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0180_ChangeNullabilityViaUpgradeHints/Upgrader.cs index 8247a3ed75..6523145ef8 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0180_ChangeNullabilityViaUpgradeHints/Upgrader.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0180_ChangeNullabilityViaUpgradeHints/Upgrader.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Tests.Issues.IssueJira0180_ChangeNullabilityViaUpgradeHints { - [Serializable] public class Upgrader : UpgradeHandler { private static bool isEnabled = false; diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0208_IncorrectUpgradeSequence/Upgrader.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0208_IncorrectUpgradeSequence/Upgrader.cs index 3d53cff379..4d0d33ff05 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0208_IncorrectUpgradeSequence/Upgrader.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0208_IncorrectUpgradeSequence/Upgrader.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Tests.Issues.IssueJira0208_IncorrectUpgradeSequence { - [Serializable] public class Upgrader : UpgradeHandler { private static bool isEnabled = false; diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0430_PartialIndexOnBoolOrEnumFields.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0430_PartialIndexOnBoolOrEnumFields.cs index 358d2f3f11..c26fe4a584 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0430_PartialIndexOnBoolOrEnumFields.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0430_PartialIndexOnBoolOrEnumFields.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2013 Xtensive LLC. +// Copyright (C) 2013 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Denis Krjuchkov @@ -89,7 +89,7 @@ private void BuildDomain(Type type, DomainUpgradeMode upgradeMode) var configuration = DomainConfigurationFactory.Create(); configuration.Types.Register(type); configuration.UpgradeMode = upgradeMode; - Domain.Build(configuration).Dispose(); + using (Domain.Build(configuration)) { } } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0431_IGroupingKeyIsNotUsable.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0431_IGroupingKeyIsNotUsable.cs index d0e7cdbe33..844707f9f7 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0431_IGroupingKeyIsNotUsable.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0431_IGroupingKeyIsNotUsable.cs @@ -6,7 +6,6 @@ using System; using System.Linq; -using System.Runtime.Serialization; using NUnit.Framework; using Xtensive.Orm.Configuration; using Xtensive.Orm.Model; @@ -32,11 +31,6 @@ protected ItemItemVersionsEntitySet(Entity owner, FieldInfo field) : base(owner, field) { } - - protected ItemItemVersionsEntitySet(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } public abstract class ItemBase : Entity, IItemBase diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0516_PartialIndexConstruction.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0516_PartialIndexConstruction.cs index 50d9843aab..3a767893a8 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0516_PartialIndexConstruction.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0516_PartialIndexConstruction.cs @@ -1,10 +1,11 @@ -// Copyright (C) 2013 Xtensive LLC. +// Copyright (C) 2013 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Alena Mikshina // Created: 2014.02.13 using System; +using System.Linq; using System.Linq.Expressions; using NUnit.Framework; using Xtensive.Orm.Model; @@ -44,13 +45,8 @@ internal class IssueJira0516_PartialIndexConstruction [Test] public void MainTest() { - RunTest(typeof (Derived)); - } - - private void RunTest(Type type) - { - BuildDomain(type, DomainUpgradeMode.Recreate); - BuildDomain(type, DomainUpgradeMode.Validate); + BuildDomain(typeof(Derived), DomainUpgradeMode.Recreate); + BuildDomain(typeof(Derived), DomainUpgradeMode.Validate); } private void BuildDomain(Type type, DomainUpgradeMode upgradeMode) @@ -58,7 +54,7 @@ private void BuildDomain(Type type, DomainUpgradeMode upgradeMode) var configuration = DomainConfigurationFactory.Create(); configuration.Types.Register(type); configuration.UpgradeMode = upgradeMode; - Domain.Build(configuration).Dispose(); + using (Domain.Build(configuration)) { } } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0538_IncorrectSortedActionSequence.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0538_IncorrectSortedActionSequence.cs index 6a9d1f7642..dc8367048b 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0538_IncorrectSortedActionSequence.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0538_IncorrectSortedActionSequence.cs @@ -23,8 +23,7 @@ protected DataFieldBase(Guid id) { } } - - [Serializable] + public class ExternalDataField : DataFieldBase { [Field(Nullable = false)] @@ -69,7 +68,6 @@ protected TablePartBase(Guid id, TOwner owner) } [HierarchyRoot] - [Serializable] public class TpVisibleEnable : TablePartBase { public TpVisibleEnable(Guid id, FormElement owner) diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0540_IncorrectBehaviorOnDomainUpgradeWithRecycledTypeBug.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0540_IncorrectBehaviorOnDomainUpgradeWithRecycledTypeBug.cs index 1fb4287a29..fc5d08684d 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0540_IncorrectBehaviorOnDomainUpgradeWithRecycledTypeBug.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0540_IncorrectBehaviorOnDomainUpgradeWithRecycledTypeBug.cs @@ -90,7 +90,7 @@ public void OldTypeDoesNotDefinedInAttributeTest() domainConfiguration = domainConfiguration.Clone(); domainConfiguration.UpgradeMode = DomainUpgradeMode.PerformSafely; - Assert.DoesNotThrow(()=>Domain.Build(domainConfiguration)); + Assert.DoesNotThrow(() => Domain.Build(domainConfiguration).Dispose()); } [Test] @@ -104,7 +104,7 @@ public void OldTypeDefinedInAttributeTest() domainConfiguration = domainConfiguration.Clone(); domainConfiguration.UpgradeMode = DomainUpgradeMode.PerformSafely; - Assert.Throws(() => Domain.Build(domainConfiguration)); + _ = Assert.Throws(() => Domain.Build(domainConfiguration).Dispose()); } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0553_IncorrectLeftJoinOnNotNullEntityField.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0553_IncorrectLeftJoinOnNotNullEntityField.cs index bf2d9c79eb..9717a89066 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0553_IncorrectLeftJoinOnNotNullEntityField.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0553_IncorrectLeftJoinOnNotNullEntityField.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Issues.IssueJira0553_IncorrectLeftJoinOnNotNullEntityFieldModel { - [Serializable] [HierarchyRoot] public class Employee : Entity { @@ -21,14 +20,12 @@ public class Employee : Entity public Guid Id { get; private set; } } - [Serializable] public class EmployeeWithCar : Employee { [Field(Nullable = false)] public Car Car { get; set; } } - [Serializable] [HierarchyRoot] public class Car : Entity { @@ -43,7 +40,6 @@ public class BaseClass : Entity public int Id { get; set; } } - [Serializable] [HierarchyRoot] public class Job : BaseClass { @@ -51,7 +47,6 @@ public class Job : BaseClass public Location Location { get; set; } } - [Serializable] [HierarchyRoot] public class Invoice : BaseClass { @@ -62,7 +57,6 @@ public class Invoice : BaseClass public Customer Customer { get; set; } } - [Serializable] [HierarchyRoot] public class Location : BaseClass { @@ -70,7 +64,6 @@ public class Location : BaseClass public Address Address { get; set; } } - [Serializable] [HierarchyRoot] public class Address : BaseClass { diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0566_IndexOnRemovableEntityBug.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0566_IndexOnRemovableEntityBug.cs index 1f2cf910b8..54732cd4be 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0566_IndexOnRemovableEntityBug.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0566_IndexOnRemovableEntityBug.cs @@ -18,7 +18,6 @@ namespace Xtensive.Orm.Tests.Issues.IssueJira0566_BuildingUnderlyingIndexForForeignKeyBugModel1 { [Index("Entity", Clustered = true, Name = "Clustered")] - [Serializable] public abstract class BaseEntity : Entity { [Key] @@ -39,7 +38,6 @@ public class TestEntity : BaseEntity } [HierarchyRoot] - [Serializable] public class WithEntitySet : Entity { [Key] @@ -58,7 +56,6 @@ public class WithEntitySet : Entity namespace Xtensive.Orm.Tests.Issues.IssueJira0566_BuildingUnderlyingIndexForForeignKeyBugModel2 { [Index("Entity", Clustered = true, Name = "Clustered")] - [Serializable] public abstract class BaseEntity : Entity { [Key] @@ -85,7 +82,6 @@ public class TestEntityChild : TestEntity } [HierarchyRoot] - [Serializable] public class WithEntitySet : Entity { [Key] @@ -104,7 +100,6 @@ public class WithEntitySet : Entity namespace Xtensive.Orm.Tests.Issues.IssueJira0566_BuildingUnderlyingIndexForForeignKeyBugModel3 { [Index("Entity", Clustered = true, Name = "Clustered")] - [Serializable] public abstract class BaseEntity : Entity { [Key] @@ -131,7 +126,6 @@ public class TestEntityChild : TestEntity } [HierarchyRoot] - [Serializable] public class WithEntitySet : Entity { [Key] diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0612_NonPairedReferencesSearchBug.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0612_NonPairedReferencesSearchBug.cs index 2ddea05ae4..b58c8334cd 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0612_NonPairedReferencesSearchBug.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0612_NonPairedReferencesSearchBug.cs @@ -32,7 +32,6 @@ public class TestB : Entity public TestA TestA { get; set; } } - [Serializable] [HierarchyRoot] public class TestC : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0613_DataCleanUpInPerformSafely.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0613_DataCleanUpInPerformSafely.cs index e8909c84d0..1801056215 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0613_DataCleanUpInPerformSafely.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0613_DataCleanUpInPerformSafely.cs @@ -170,10 +170,10 @@ private void RunTest(Action populateAction, Action validateAction, Type upgradingConfiguration.UpgradeMode = (isSafelyMode) ? DomainUpgradeMode.PerformSafely : DomainUpgradeMode.Perform; upgradingConfiguration.Types.RegisterCaching(upgradedType.Assembly, upgradedType.Namespace); if (isSafelyMode) { - Assert.Throws(() => Domain.Build(upgradingConfiguration)); + _ = Assert.Throws(() => Domain.Build(upgradingConfiguration).Dispose()); } else - Assert.DoesNotThrow(() => Domain.Build(upgradingConfiguration)); + Assert.DoesNotThrow(() => Domain.Build(upgradingConfiguration).Dispose()); var validationConfiguration = inintialConfiguration.Clone(); validationConfiguration.UpgradeMode = DomainUpgradeMode.Validate; @@ -188,7 +188,7 @@ private void RunTest(Action populateAction, Action validateAction, Type // In this kind of tests we have only primary keys changed. // To be clear, only name is changed, // but this change is irrelevant for certain providers and comparison result is null - var exception = Assert.Throws(() => Domain.Build(validationConfiguration)); + var exception = Assert.Throws(() => Domain.Build(validationConfiguration).Dispose()); var provider = validationConfiguration.ConnectionInfo.Provider; if (provider != WellKnown.Provider.MySql && provider != WellKnown.Provider.Sqlite) { Assert.That(exception.ComparisonResult, Is.Not.Null); diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0617_IncorrectRemoveOfRedundantColumns.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0617_IncorrectRemoveOfRedundantColumns.cs index 01adbcb120..e0fb122e88 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0617_IncorrectRemoveOfRedundantColumns.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0617_IncorrectRemoveOfRedundantColumns.cs @@ -1447,7 +1447,6 @@ protected Portfolio(Guid id) } } - [Serializable] public sealed class AggregatePortfolio : Portfolio { public AggregatePortfolio(Guid id) diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0641_IndexFilterExpressionTranslationBug.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0641_IndexFilterExpressionTranslationBug.cs index b844121235..63ceec39ee 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0641_IndexFilterExpressionTranslationBug.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0641_IndexFilterExpressionTranslationBug.cs @@ -72,10 +72,7 @@ public void MainTest() configuration.Types.RegisterCaching(typeof (BandwidthCall).Assembly, typeof (BandwidthCall).Namespace); configuration.UpgradeMode = DomainUpgradeMode.Recreate; - Domain domain = null; - Assert.DoesNotThrow(() => domain = Domain.Build(configuration)); - if (domain!=null) - domain.Dispose(); + Assert.DoesNotThrow(() => Domain.Build(configuration).Dispose()); } [Test] diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0656_RemapRestoresRemovedReferences.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0656_RemapRestoresRemovedReferences.cs index e88e014b61..a1f60a90af 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0656_RemapRestoresRemovedReferences.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0656_RemapRestoresRemovedReferences.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Issues.IssueJira0656_RemapRestoresRemovedReferencesModel { - [Serializable] [HierarchyRoot] public class TestA : Entity { @@ -26,7 +25,6 @@ public class TestA : Entity public TestB TestB { get; set; } } - [Serializable] [HierarchyRoot] public class TestB : Entity { @@ -37,7 +35,6 @@ public class TestB : Entity public string Text { get; set; } } - [Serializable] [HierarchyRoot] public class TestBase : Entity { @@ -48,15 +45,12 @@ public class TestBase : Entity public string Text { get; set; } } - [Serializable] public class TestC : TestBase { [Field, Association(PairTo = "TestC", OnOwnerRemove = OnRemoveAction.Cascade, OnTargetRemove = OnRemoveAction.Clear)] public EntitySet TestDs { get; private set; } } - - [Serializable] [HierarchyRoot] public class TestD : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0674_ReferenceFinderBug.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0674_ReferenceFinderBug.cs index 295ebe167b..f85885c827 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0674_ReferenceFinderBug.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0674_ReferenceFinderBug.cs @@ -5,7 +5,6 @@ namespace Xtensive.Orm.Tests.Issues.IssueJira0674_ReferenceFinderBugModel { - [Serializable] [HierarchyRoot] public class TestA : Entity { @@ -18,7 +17,6 @@ public TestA(Session session) : base(session) { } public string Text { get; set; } } - [Serializable] [HierarchyRoot] public class TestB : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0735_WrongTypeIdsInValidateMode.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0735_WrongTypeIdsInValidateMode.cs index f8ade435c8..11fc4e2d9a 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0735_WrongTypeIdsInValidateMode.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0735_WrongTypeIdsInValidateMode.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2018 Xtensive LLC. +// Copyright (C) 2018 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Alexey Kulakov @@ -19,7 +19,7 @@ public void DefaultBehaviorTest() { using (var domain = Domain.Build(BuildInitialConfiguration())) { } - var exception = Assert.Throws(() => Domain.Build(BuildUpgradeConfiguration())); + var exception = Assert.Throws(() => Domain.Build(BuildUpgradeConfiguration()).Dispose()); Assert.That(exception.ComparisonResult, Is.Null); } diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0752_RecycledAttributeDontWorkForPersistentGenericInterface.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0752_RecycledAttributeDontWorkForPersistentGenericInterface.cs index 296d4e5688..ae9db2b411 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0752_RecycledAttributeDontWorkForPersistentGenericInterface.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0752_RecycledAttributeDontWorkForPersistentGenericInterface.cs @@ -57,7 +57,7 @@ public void ValidateTest() { var initialConfiguration = DomainConfigurationFactory.Create(); initialConfiguration.Types.RegisterCaching(typeof(RecycledEntity).Assembly, typeof(RecycledEntity).Namespace); - BuildDomain(initialConfiguration).Dispose(); + using (BuildDomain(initialConfiguration)) { } Domain domain = null; Assert.DoesNotThrow(() => domain = BuildDomain(BuildConfiguration(DomainUpgradeMode.Validate))); @@ -147,7 +147,6 @@ public ActionGatherer(ActionSequence upgrading, ActionSequence final) namespace Xtensive.Orm.Tests.Issues.IssueJira0752_RecycledAttributeDontWorkForPersistentGenericInterfaceModels { - [Serializable] [HierarchyRoot] [Recycled] public class RecycledEntity : Entity @@ -161,7 +160,6 @@ public interface ITestInterface : IEntity { } - [Serializable] [HierarchyRoot] [Recycled] public class RecycledWithInterfaceEntity : @@ -173,7 +171,6 @@ public class RecycledWithInterfaceEntity : public Guid Id { get; private set; } } - [Serializable] [HierarchyRoot] public class NonRecycledWithInterfaceEntity : Entity, diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0759_UnableToTranslateOfTypeSelectExpression.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0759_UnableToTranslateOfTypeSelectExpression.cs index aa62b08cad..8686edadd0 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0759_UnableToTranslateOfTypeSelectExpression.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0759_UnableToTranslateOfTypeSelectExpression.cs @@ -169,7 +169,6 @@ public interface IHasStatus : IEntity } [HierarchyRoot] - [Serializable] public class Status : Entity { [Key] @@ -184,7 +183,6 @@ public class Status : Entity } [HierarchyRoot] - [Serializable] public class TestEntity4 : Entity, IHasStatus { [Key] diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0767_OfTypeForNonGenericSources.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0767_OfTypeForNonGenericSources.cs index cb53d6f806..60d6635e21 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0767_OfTypeForNonGenericSources.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0767_OfTypeForNonGenericSources.cs @@ -5,7 +5,6 @@ // Created: 2019.06.21 using System.Linq; -using System.Runtime.Serialization; using NUnit.Framework; using Xtensive.Core; using Xtensive.Orm.Configuration; @@ -43,11 +42,6 @@ protected EntitySetOfTestEntity(Entity owner, FieldInfo field) : base(owner, field) { } - - protected EntitySetOfTestEntity(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } diff --git a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0804_RenameFieldHintValidationBug.cs b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0804_RenameFieldHintValidationBug.cs index 578b859428..25f45eaf5f 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/IssueJira0804_RenameFieldHintValidationBug.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/IssueJira0804_RenameFieldHintValidationBug.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Issues.IssueJira0804_RenameFieldHintValidationBugModel { - [Serializable] [HierarchyRoot] public class Person : Entity { @@ -19,7 +18,6 @@ public class Person : Entity public long Id { get; private set; } } - [Serializable] [HierarchyRoot] public class Address : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue_0694_SchemaUpgradeBug/ModelVersion1.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue_0694_SchemaUpgradeBug/ModelVersion1.cs index 1a3e2c5e9b..2aa2c409e7 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue_0694_SchemaUpgradeBug/ModelVersion1.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue_0694_SchemaUpgradeBug/ModelVersion1.cs @@ -9,7 +9,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue_0694_SchemaUpgradeBug.Model.Version1 { - [Serializable] [HierarchyRoot] public sealed class Status : Entity { @@ -29,7 +28,6 @@ public override string ToString() } } - [Serializable] [HierarchyRoot] public class Content : Entity { @@ -48,7 +46,6 @@ public override string ToString() } } - [Serializable] public class Media : Content { [Field] diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue_0694_SchemaUpgradeBug/ModelVersion2.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue_0694_SchemaUpgradeBug/ModelVersion2.cs index 0a347d0c46..b387a2ae20 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue_0694_SchemaUpgradeBug/ModelVersion2.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue_0694_SchemaUpgradeBug/ModelVersion2.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue_0694_SchemaUpgradeBug.Model.Version2 { - [Serializable] [HierarchyRoot] public sealed class Status : Entity { @@ -33,7 +32,6 @@ public override string ToString() } } - [Serializable] [HierarchyRoot] public class Content : Entity { @@ -52,7 +50,6 @@ public override string ToString() } } - [Serializable] public class NewMedia : Content { [Field] diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue_0694_SchemaUpgradeBug/ModelVersion3.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue_0694_SchemaUpgradeBug/ModelVersion3.cs index 3dcf69c8d3..a03d5bb452 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue_0694_SchemaUpgradeBug/ModelVersion3.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue_0694_SchemaUpgradeBug/ModelVersion3.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue_0694_SchemaUpgradeBug.Model.Version3 { - [Serializable] [HierarchyRoot] public sealed class Status : Entity { @@ -33,7 +32,6 @@ public override string ToString() } } - [Serializable] [HierarchyRoot] public class Content : Entity { @@ -52,7 +50,6 @@ public override string ToString() } } - [Serializable] public class NewMedia : Content { [Field] diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue_0694_SchemaUpgradeBug/Upgrader.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue_0694_SchemaUpgradeBug/Upgrader.cs index 0abc973b19..ff06570123 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue_0694_SchemaUpgradeBug/Upgrader.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue_0694_SchemaUpgradeBug/Upgrader.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue_0694_SchemaUpgradeBug { - [Serializable] public class Upgrader : UpgradeHandler { private static bool isEnabled = false; diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue_0716_UpgradeFailsInValidateMode/ModelVersion1.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue_0716_UpgradeFailsInValidateMode/ModelVersion1.cs index 6a1eb455c8..9ec9cbf697 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue_0716_UpgradeFailsInValidateMode/ModelVersion1.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue_0716_UpgradeFailsInValidateMode/ModelVersion1.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue_0716_UpgradeFailsInValidateMode.Model.Version1 { - [Serializable] [HierarchyRoot] public class Article : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue_0716_UpgradeFailsInValidateMode/ModelVersion2.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue_0716_UpgradeFailsInValidateMode/ModelVersion2.cs index 94714c87f6..3132ff327a 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue_0716_UpgradeFailsInValidateMode/ModelVersion2.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue_0716_UpgradeFailsInValidateMode/ModelVersion2.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue_0716_UpgradeFailsInValidateMode.Model.Version2 { - [Serializable] [HierarchyRoot] public class Article : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue_0716_UpgradeFailsInValidateMode/Upgrader.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue_0716_UpgradeFailsInValidateMode/Upgrader.cs index a5bf9d3453..21e2f18dcc 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue_0716_UpgradeFailsInValidateMode/Upgrader.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue_0716_UpgradeFailsInValidateMode/Upgrader.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue_0716_UpgradeFailsInValidateMode { - [Serializable] public class Upgrader : UpgradeHandler { private static bool isEnabled = false; diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue_0743_UpgradeToNonNullableTypes/ModelVersion1.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue_0743_UpgradeToNonNullableTypes/ModelVersion1.cs index 89eaee2b10..9ee40370c1 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue_0743_UpgradeToNonNullableTypes/ModelVersion1.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue_0743_UpgradeToNonNullableTypes/ModelVersion1.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue_0743_UpgradeToNonNullableTypes.Model.Version1 { - [Serializable] [HierarchyRoot] public class Person : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue_0743_UpgradeToNonNullableTypes/ModelVersion2.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue_0743_UpgradeToNonNullableTypes/ModelVersion2.cs index be285df7d3..0de217d720 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue_0743_UpgradeToNonNullableTypes/ModelVersion2.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue_0743_UpgradeToNonNullableTypes/ModelVersion2.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue_0743_UpgradeToNonNullableTypes.Model.Version2 { - [Serializable] [HierarchyRoot] public class Person : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue_0743_UpgradeToNonNullableTypes/Upgrader.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue_0743_UpgradeToNonNullableTypes/Upgrader.cs index 71f9e4b784..57d78981ef 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue_0743_UpgradeToNonNullableTypes/Upgrader.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue_0743_UpgradeToNonNullableTypes/Upgrader.cs @@ -16,7 +16,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue_0743_UpgradeToNonNullableTypes { - [Serializable] public class Upgrader : UpgradeHandler { private static bool isEnabled = false; diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue_0769_ByteArrayColumnUpgrade/ModelVersion1.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue_0769_ByteArrayColumnUpgrade/ModelVersion1.cs index d6f230fc3a..98ec46374b 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue_0769_ByteArrayColumnUpgrade/ModelVersion1.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue_0769_ByteArrayColumnUpgrade/ModelVersion1.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue_0769_ByteArrayColumnUpgrade.Model.Version1 { - [Serializable] [HierarchyRoot] public class Person : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue_0769_ByteArrayColumnUpgrade/ModelVersion2.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue_0769_ByteArrayColumnUpgrade/ModelVersion2.cs index f4f16e36dc..cefa14667e 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue_0769_ByteArrayColumnUpgrade/ModelVersion2.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue_0769_ByteArrayColumnUpgrade/ModelVersion2.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue_0769_ByteArrayColumnUpgrade.Model.Version2 { - [Serializable] [HierarchyRoot] public class Person : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue_0769_ByteArrayColumnUpgrade/Upgrader.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue_0769_ByteArrayColumnUpgrade/Upgrader.cs index fbffb7a818..79c2a92489 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue_0769_ByteArrayColumnUpgrade/Upgrader.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue_0769_ByteArrayColumnUpgrade/Upgrader.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue_0769_ByteArrayColumnUpgrade { - [Serializable] public class Upgrader : UpgradeHandler { private static bool isEnabled = false; diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue_0837_HintGeneratorBug/Upgrader.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue_0837_HintGeneratorBug/Upgrader.cs index 2624531860..2d415bd6c5 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue_0837_HintGeneratorBug/Upgrader.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue_0837_HintGeneratorBug/Upgrader.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue_0834_HintGeneratorBug { - [Serializable] public class Upgrader : UpgradeHandler { private static bool isEnabled = false; diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue_0841_HintGeneratorBug/Upgrader.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue_0841_HintGeneratorBug/Upgrader.cs index 82900cabe0..b09e48988f 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue_0841_HintGeneratorBug/Upgrader.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue_0841_HintGeneratorBug/Upgrader.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue_0841_HintGeneratorBug { - [Serializable] public class Upgrader : UpgradeHandler { private static bool isEnabled = false; diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue_0841_HintGeneratorBug2/Upgrader.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue_0841_HintGeneratorBug2/Upgrader.cs index aa1333bca9..b96dc3108e 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue_0841_HintGeneratorBug2/Upgrader.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue_0841_HintGeneratorBug2/Upgrader.cs @@ -16,7 +16,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue_0841_HintGeneratorBug2 { - [Serializable] public class Upgrader : UpgradeHandler { private static bool isEnabled = false; diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue_0841_HintGeneratorBug3/Upgrader.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue_0841_HintGeneratorBug3/Upgrader.cs index 6023fe4b83..6b68af86f6 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue_0841_HintGeneratorBug3/Upgrader.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue_0841_HintGeneratorBug3/Upgrader.cs @@ -17,7 +17,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue_0841_HintGeneratorBug3 { - [Serializable] public class Upgrader : UpgradeHandler { private static bool isEnabled = false; diff --git a/Orm/Xtensive.Orm.Tests/Issues/Issue_0841_HintGeneratorBug4/Upgrader.cs b/Orm/Xtensive.Orm.Tests/Issues/Issue_0841_HintGeneratorBug4/Upgrader.cs index a57aada164..ce54e558eb 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/Issue_0841_HintGeneratorBug4/Upgrader.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/Issue_0841_HintGeneratorBug4/Upgrader.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Tests.Issues.Issue_0841_HintGeneratorBug4 { - [Serializable] public class Upgrader : UpgradeHandler { private static bool isEnabled = false; diff --git a/Orm/Xtensive.Orm.Tests/Issues/KeyFormatBug.cs b/Orm/Xtensive.Orm.Tests/Issues/KeyFormatBug.cs index 4b52311019..86ec3a106d 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/KeyFormatBug.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/KeyFormatBug.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Issues.KeyFormatBug { - [Serializable] [HierarchyRoot] public class Base : Entity { @@ -22,14 +21,12 @@ public class Base : Entity public long Id { get; private set; } } - [Serializable] public class Child : Base { } namespace Nested { - [Serializable] [HierarchyRoot] public class Base : Entity { @@ -37,7 +34,6 @@ public class Base : Entity public long Id { get; private set; } } - [Serializable] public class Child : Base { } diff --git a/Orm/Xtensive.Orm.Tests/Issues/NotEqualsForNullableColumnTest.cs b/Orm/Xtensive.Orm.Tests/Issues/NotEqualsForNullableColumnTest.cs index 07c2b5034b..0ffe13baa2 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/NotEqualsForNullableColumnTest.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/NotEqualsForNullableColumnTest.cs @@ -39,7 +39,6 @@ public class Reference : Entity } } - [Serializable] public class NotEqualsForNullableColumnTest : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() diff --git a/Orm/Xtensive.Orm.Tests/Issues/StrangeLockingExceptionTest.cs b/Orm/Xtensive.Orm.Tests/Issues/StrangeLockingExceptionTest.cs index 2fb2b1f608..11ed7a6684 100644 --- a/Orm/Xtensive.Orm.Tests/Issues/StrangeLockingExceptionTest.cs +++ b/Orm/Xtensive.Orm.Tests/Issues/StrangeLockingExceptionTest.cs @@ -16,7 +16,6 @@ namespace Xtensive.Orm.Tests.Issues { namespace StrangeLockingExceptionModel { - [Serializable] [HierarchyRoot] public class TestA : Entity { @@ -29,7 +28,6 @@ public TestA(Session session) : base(session) { } public int Val { get; set; } } - [Serializable] [HierarchyRoot] public class TestB : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Linq/ArrayTest.cs b/Orm/Xtensive.Orm.Tests/Linq/ArrayTest.cs index 890447407e..cd634e87a3 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/ArrayTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/ArrayTest.cs @@ -18,7 +18,6 @@ namespace Xtensive.Orm.Tests.Linq { [Category("Linq")] [TestFixture] - [Serializable] public class ArrayTest : ChinookDOModelTest { [Test] diff --git a/Orm/Xtensive.Orm.Tests/Linq/ConditionalTest.cs b/Orm/Xtensive.Orm.Tests/Linq/ConditionalTest.cs index 2d66ab3f31..adcc02f3aa 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/ConditionalTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/ConditionalTest.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Linq.ConditionalTestModel { - [Serializable] [KeyGenerator(KeyGeneratorKind.Custom, Name = "DualInt")] [HierarchyRoot] public class Root1 : Entity @@ -25,21 +24,18 @@ public class Root1 : Entity public int Id2 { get; private set; } } - [Serializable] public class A : Root1 { [Field] public int FieldA { get; private set; } } - [Serializable] public class B : Root1 { [Field] public int FieldB { get; private set; } } - [Serializable] [HierarchyRoot] public class Root2 : Entity { @@ -59,6 +55,7 @@ public class Root2 : Entity namespace Xtensive.Orm.Tests.Linq { + [TestFixture, Category("Linq")] public class ConditionalTest : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() diff --git a/Orm/Xtensive.Orm.Tests/Linq/CustomExpressionCompilers.cs b/Orm/Xtensive.Orm.Tests/Linq/CustomExpressionCompilers.cs index 178b520966..aa21ecceba 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/CustomExpressionCompilers.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/CustomExpressionCompilers.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Tests.Linq.CustomExpressionCompilersModel { - [Serializable] [HierarchyRoot] public class Person : Entity { @@ -109,6 +108,7 @@ public static Expression Current(Expression assignmentExpression) namespace Xtensive.Orm.Tests.Linq { + [TestFixture, Category("Linq")] public class CustomExpressionCompilers : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() diff --git a/Orm/Xtensive.Orm.Tests/Linq/InOverSubtypeColumnTest.cs b/Orm/Xtensive.Orm.Tests/Linq/InOverSubtypeColumnTest.cs index cc1bf8700e..a36495b561 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/InOverSubtypeColumnTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/InOverSubtypeColumnTest.cs @@ -78,10 +78,10 @@ public override void TestFixtureSetUp() using (var session = Domain.OpenSession()) using (var tx = session.OpenTransaction()) { - new MainEntity {Reference = new RefBase()}; - new MainEntity {Reference = new Ref()}; - new MainEntity {Reference = new Ref {Info = "Don't know"}}; - new MainEntity {Reference = new Ref {Info = "IDDQD"}}; + _ = new MainEntity {Reference = new RefBase()}; + _ = new MainEntity {Reference = new Ref()}; + _ = new MainEntity {Reference = new Ref {Info = "Don't know"}}; + _ = new MainEntity {Reference = new Ref {Info = "IDDQD"}}; tx.Complete(); } } diff --git a/Orm/Xtensive.Orm.Tests/Linq/Interfaces/AlphabetTest.cs b/Orm/Xtensive.Orm.Tests/Linq/Interfaces/AlphabetTest.cs index 0969d7ef6d..a53c1cb029 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/Interfaces/AlphabetTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/Interfaces/AlphabetTest.cs @@ -15,7 +15,7 @@ namespace Xtensive.Orm.Tests.Linq.Interfaces { - [Serializable] + [TestFixture, Category("Linq")] public class AlphabetTest : AutoBuildTest { const int EachCount = 10; @@ -27,85 +27,83 @@ protected override DomainConfiguration BuildConfiguration() return config; } - public override void TestFixtureSetUp() + protected override void PopulateData() { - base.TestFixtureSetUp(); - using (var session = Domain.OpenSession()) { - using (var t = session.OpenTransaction()) { - // ClassTable - for (var i = 0; i < EachCount; i++) { - _ = new A() {Name = "Name: A" + i}; - } - - for (var i = 0; i < EachCount; i++) { - var named = (INamed)new B() { Name = "Name: B" + i, Tag = "Tag: B" + i}; - named.Name = "Name: B'" + i; - } - for (var i = 0; i < EachCount; i++) { - var tagged = (ITagged)new C() { Name = "Name: C" + i }; - tagged.Tag = "Tag: C'" + i; - } - for (var i = 0; i < EachCount; i++) { - var named = (INamed)new D() { Name = "Name: D" + i, Tag= "Tag: D" + i, First = "First: D" + i, Second = "Second: D" + i }; - named.Name = "Name: D'" + i; - } - for (var i = 0; i < EachCount; i++) { - var named = (INamed)new E() { Name = "Name: E" + i, Tag = "Tag: E" + i, First = "First: E" + i, Second = "Second: E" + i }; - var composite = (IComposite) named; - named.Name = "Name: E'" + i; - composite.First = "First: E'" + i; - } - - // ConcreteTable - for (var i = 0; i < EachCount; i++) { - _ = new F() {Name = "Name: F" + i}; - } - - for (var i = 0; i < EachCount; i++) { - var named = (INamed)new G() { Name = "Name: G" + i, Tag = "Tag: G" + i}; - named.Name = "Name: G'" + i; - } - for (var i = 0; i < EachCount; i++) { - var tagged = (ITagged)new H() { Name = "Name: H" + i }; - tagged.Tag = "Tag: H'" + i; - } - for (var i = 0; i < EachCount; i++) { - var named = (INamed)new I() { Name = "Name: I" + i, Tag= "Tag: I" + i, First = "First: I" + i, Second = "Second: I" + i }; - named.Name = "Name: I'" + i; - } - for (var i = 0; i < EachCount; i++) { - var named = (INamed)new J() { Name = "Name: J" + i, Tag = "Tag: J" + i, First = "First: J" + i, Second = "Second: J" + i }; - var composite = (IComposite) named; - named.Name = "Name: J'" + i; - composite.First = "First: J'" + i; - } - - // SingleTable - for (var i = 0; i < EachCount; i++) { - _ = new K() {Name = "Name: K" + i}; - } - - for (var i = 0; i < EachCount; i++) { - var named = (INamed)new L() { Name = "Name: L" + i, Tag = "Tag: L" + i}; - named.Name = "Name: L'" + i; - } - for (var i = 0; i < EachCount; i++) { - var tagged = (ITagged)new M() { Name = "Name: M" + i }; - tagged.Tag = "Tag: M'" + i; - } - for (var i = 0; i < EachCount; i++) { - var named = (INamed)new N() { Name = "Name: N" + i, Tag= "Tag: N" + i, First = "First: N" + i, Second = "Second: N" + i }; - named.Name = "Name: N'" + i; - } - for (var i = 0; i < EachCount; i++) { - var named = (INamed)new O() { Name = "Name: O" + i, Tag = "Tag: O" + i, First = "First: O" + i, Second = "Second: O" + i }; - var composite = (IComposite) named; - named.Name = "Name: O'" + i; - composite.First = "First: O'" + i; - } - - t.Complete(); + using (var session = Domain.OpenSession()) + using (var t = session.OpenTransaction()) { + // ClassTable + for (var i = 0; i < EachCount; i++) { + _ = new A() {Name = "Name: A" + i}; + } + + for (var i = 0; i < EachCount; i++) { + var named = (INamed)new B() { Name = "Name: B" + i, Tag = "Tag: B" + i}; + named.Name = "Name: B'" + i; + } + for (var i = 0; i < EachCount; i++) { + var tagged = (ITagged)new C() { Name = "Name: C" + i }; + tagged.Tag = "Tag: C'" + i; + } + for (var i = 0; i < EachCount; i++) { + var named = (INamed)new D() { Name = "Name: D" + i, Tag= "Tag: D" + i, First = "First: D" + i, Second = "Second: D" + i }; + named.Name = "Name: D'" + i; + } + for (var i = 0; i < EachCount; i++) { + var named = (INamed)new E() { Name = "Name: E" + i, Tag = "Tag: E" + i, First = "First: E" + i, Second = "Second: E" + i }; + var composite = (IComposite) named; + named.Name = "Name: E'" + i; + composite.First = "First: E'" + i; + } + + // ConcreteTable + for (var i = 0; i < EachCount; i++) { + _ = new F() {Name = "Name: F" + i}; + } + + for (var i = 0; i < EachCount; i++) { + var named = (INamed)new G() { Name = "Name: G" + i, Tag = "Tag: G" + i}; + named.Name = "Name: G'" + i; + } + for (var i = 0; i < EachCount; i++) { + var tagged = (ITagged)new H() { Name = "Name: H" + i }; + tagged.Tag = "Tag: H'" + i; } + for (var i = 0; i < EachCount; i++) { + var named = (INamed)new I() { Name = "Name: I" + i, Tag= "Tag: I" + i, First = "First: I" + i, Second = "Second: I" + i }; + named.Name = "Name: I'" + i; + } + for (var i = 0; i < EachCount; i++) { + var named = (INamed)new J() { Name = "Name: J" + i, Tag = "Tag: J" + i, First = "First: J" + i, Second = "Second: J" + i }; + var composite = (IComposite) named; + named.Name = "Name: J'" + i; + composite.First = "First: J'" + i; + } + + // SingleTable + for (var i = 0; i < EachCount; i++) { + _ = new K() {Name = "Name: K" + i}; + } + + for (var i = 0; i < EachCount; i++) { + var named = (INamed)new L() { Name = "Name: L" + i, Tag = "Tag: L" + i}; + named.Name = "Name: L'" + i; + } + for (var i = 0; i < EachCount; i++) { + var tagged = (ITagged)new M() { Name = "Name: M" + i }; + tagged.Tag = "Tag: M'" + i; + } + for (var i = 0; i < EachCount; i++) { + var named = (INamed)new N() { Name = "Name: N" + i, Tag= "Tag: N" + i, First = "First: N" + i, Second = "Second: N" + i }; + named.Name = "Name: N'" + i; + } + for (var i = 0; i < EachCount; i++) { + var named = (INamed)new O() { Name = "Name: O" + i, Tag = "Tag: O" + i, First = "First: O" + i, Second = "Second: O" + i }; + var composite = (IComposite) named; + named.Name = "Name: O'" + i; + composite.First = "First: O'" + i; + } + + t.Complete(); } } diff --git a/Orm/Xtensive.Orm.Tests/Linq/Interfaces/SlaveryTest.cs b/Orm/Xtensive.Orm.Tests/Linq/Interfaces/SlaveryTest.cs index 92c219f561..ba26db29e4 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/Interfaces/SlaveryTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/Interfaces/SlaveryTest.cs @@ -11,7 +11,7 @@ namespace Xtensive.Orm.Tests.Linq.Interfaces { - [Serializable] + [TestFixture, Category("Linq")] public class SlaveryTest : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() diff --git a/Orm/Xtensive.Orm.Tests/Linq/LocalCollectionsComplexTest.cs b/Orm/Xtensive.Orm.Tests/Linq/LocalCollectionsComplexTest.cs index cf1b7dfcb2..3e09e68833 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/LocalCollectionsComplexTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/LocalCollectionsComplexTest.cs @@ -38,7 +38,6 @@ public class Poco2 public ComplexStructure ComplexStructure { get; set; } } - [Serializable] public class EntityStructure : Structure { [Field] @@ -51,7 +50,6 @@ public class EntityStructure : Structure public DateTime StructureAge { get; set; } } - [Serializable] public class ComplexStructure : Structure { [Field] @@ -67,7 +65,6 @@ public class ComplexStructure : Structure public EntityStructure EntityStructure { get; set; } } - [Serializable] [HierarchyRoot] public class EntityA : Entity { @@ -82,7 +79,6 @@ public class EntityA : Entity public DateTime Age { get; set; } } - [Serializable] [HierarchyRoot] public class EntityB : Entity { @@ -103,49 +99,48 @@ public class EntityB : Entity namespace Xtensive.Orm.Tests.Linq { + [Category("Linq")] public class LocalCollectionsComplexTest : AutoBuildTest { private const int count = 10; protected override DomainConfiguration BuildConfiguration() { - DomainConfiguration config = base.BuildConfiguration(); + var config = base.BuildConfiguration(); config.Types.RegisterCaching(typeof (EntityA).Assembly, typeof (EntityA).Namespace); config.UpgradeMode = DomainUpgradeMode.Recreate; return config; } - public override void TestFixtureSetUp() + protected override void PopulateData() { - base.TestFixtureSetUp(); - using (Session session = Domain.OpenSession()) { - using (TransactionScope t = session.OpenTransaction()) { - var entitiesB = Enumerable - .Range(0, count) - .Select(i => new EntityB { - Age = new DateTime(2000 + i, 2, 2), - Name = "NameB_" + i, - AdditionalInfo = new ComplexStructure { + using (var session = Domain.OpenSession()) + using (var tx = session.OpenTransaction()) { + var entitiesB = Enumerable + .Range(0, count) + .Select(i => new EntityB { + Age = new DateTime(2000 + i, 2, 2), + Name = "NameB_" + i, + AdditionalInfo = new ComplexStructure { + A = new EntityA { + Age = new DateTime(2000 + i, 3, 3), + Name = "NameA_1_" + i + }, + StructureAge = new DateTime(2000 + i, 7, 7), + StructureName = "StructureName_1_" + i, + EntityStructure = new EntityStructure { A = new EntityA { - Age = new DateTime(2000 + i, 3, 3), - Name = "NameA_1_" + i + Age = new DateTime(2000 + i, 1, 1), + Name = "NameA_2_" + i }, - StructureAge = new DateTime(2000 + i, 7, 7), - StructureName = "StructureName_1_" + i, - EntityStructure = new EntityStructure { - A = new EntityA { - Age = new DateTime(2000 + i, 1, 1), - Name = "NameA_2_" + i - }, - StructureAge = new DateTime(2000 + i, 10, 10), - StructureName = "StructureName_2_" + i, - } + StructureAge = new DateTime(2000 + i, 10, 10), + StructureName = "StructureName_2_" + i, } - }) - .ToList(); - t.Complete(); + } + }) + .ToList(); + tx.Complete(); } - } } [Test] diff --git a/Orm/Xtensive.Orm.Tests/Linq/MiscTest.cs b/Orm/Xtensive.Orm.Tests/Linq/MiscTest.cs index fb828399d5..f1c98ebdb0 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/MiscTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/MiscTest.cs @@ -17,7 +17,7 @@ namespace Xtensive.Orm.Tests.Linq { [TestFixture] - [Serializable] + [Category("Linq")] public class MiscTest : ChinookDOModelTest { [Test] diff --git a/Orm/Xtensive.Orm.Tests/Linq/QueryPreprocessorSortingTest.cs b/Orm/Xtensive.Orm.Tests/Linq/QueryPreprocessorSortingTest.cs index ef69bcc654..bd763992d0 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/QueryPreprocessorSortingTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/QueryPreprocessorSortingTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2012 Xtensive LLC. +// Copyright (C) 2012 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Denis Krjuchkov @@ -134,7 +134,7 @@ public void FailureTest() configuration.Types.Register(typeof (PreprocessorB)); configuration.Types.Register(typeof (PreprocessorC)); - AssertEx.ThrowsInvalidOperationException(() => Domain.Build(configuration)); + AssertEx.ThrowsInvalidOperationException(() => Domain.Build(configuration).Dispose()); } [Test] diff --git a/Orm/Xtensive.Orm.Tests/Linq/SelectDtoTest.cs b/Orm/Xtensive.Orm.Tests/Linq/SelectDtoTest.cs index 51addc0e57..d695e9cc1a 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/SelectDtoTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/SelectDtoTest.cs @@ -83,7 +83,7 @@ public class PersonDto } } - [Serializable] + [Category("Linq")] public class SelectDtoTest : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() diff --git a/Orm/Xtensive.Orm.Tests/Linq/SetOperationsTest.cs b/Orm/Xtensive.Orm.Tests/Linq/SetOperationsTest.cs index 00d9dfce3f..11fa4eee76 100644 --- a/Orm/Xtensive.Orm.Tests/Linq/SetOperationsTest.cs +++ b/Orm/Xtensive.Orm.Tests/Linq/SetOperationsTest.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Linq { [Category("Linq")] - [Serializable] public class SetOperationsTest : ChinookDOModelTest { [Test] diff --git a/Orm/Xtensive.Orm.Tests/Model/AssociationTest.cs b/Orm/Xtensive.Orm.Tests/Model/AssociationTest.cs index 6f42bd5124..c965ef9dec 100644 --- a/Orm/Xtensive.Orm.Tests/Model/AssociationTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/AssociationTest.cs @@ -4,22 +4,19 @@ // Created by: Dmitri Maximov // Created: 2008.06.16 +using System; +using System.Collections.Generic; +using System.Linq; using System.Reflection; using NUnit.Framework; using Xtensive.Core; using Xtensive.Orm.Rse; -using Xtensive.Orm.Tests; -using Xtensive.Tuples; -using Tuple = Xtensive.Tuples.Tuple; using Xtensive.Orm.Configuration; using Xtensive.Orm.Tests.Model.Association; -using System.Linq; -using System.Collections.Generic; -using System; +using Tuple = Xtensive.Tuples.Tuple; namespace Xtensive.Orm.Tests.Model.Association { - [Serializable] [HierarchyRoot] public abstract class Root : Entity { @@ -27,7 +24,6 @@ public abstract class Root : Entity public int Id { get; private set; } } - [Serializable] [HierarchyRoot] public abstract class Root2 : Entity { @@ -35,7 +31,6 @@ public abstract class Root2 : Entity public Guid Id { get; private set; } } - [Serializable] public class A : Root { [Field] @@ -60,12 +55,10 @@ public class A : Root public IntermediateStructure1 IndirectA { get; set; } } - [Serializable] public class B : Root2 { } - [Serializable] public class C : Root2 { [Field, Association(PairTo = "OneToOneMaster")] @@ -75,33 +68,28 @@ public class C : Root2 public IntermediateStructure1 IndirectA { get; set; } } - [Serializable] public class D : Root2 { [Field, Association(PairTo = "ManyToOneMaster")] public EntitySet OneToManyPaired { get; private set; } } - [Serializable] public class E : Root2 { } - [Serializable] public class F : Root2 { [Field, Association(PairTo = "OneToManyMaster")] public A ManyToOnePaired { get; set; } } - [Serializable] public class G : Root2 { [Field, Association(PairTo = "ManyToManyMaster")] public EntitySet ManytoManyPaired { get; private set; } } - [Serializable] public class H : Root2 { [Field] @@ -116,14 +104,12 @@ public class I : A } - [Serializable] public class IntermediateStructure1 : Structure { [Field] public IntermediateStructure2 IntermediateStructure2 { get; set; } } - [Serializable] public class IntermediateStructure2 : Structure { [Field] @@ -133,6 +119,7 @@ public class IntermediateStructure2 : Structure namespace Xtensive.Orm.Tests.Model { + [TestFixture, Category("Model")] public class AssociationTest : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() diff --git a/Orm/Xtensive.Orm.Tests/Model/AutoGenericsOverrideTest.cs b/Orm/Xtensive.Orm.Tests/Model/AutoGenericsOverrideTest.cs index ca48394be6..d366dbc5c7 100644 --- a/Orm/Xtensive.Orm.Tests/Model/AutoGenericsOverrideTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/AutoGenericsOverrideTest.cs @@ -37,7 +37,7 @@ public class MyChildType : MyBaseType } } - [TestFixture] + [TestFixture, Category("Model")] public class AutoGenericsOverrideTest : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() diff --git a/Orm/Xtensive.Orm.Tests/Model/CycleReferenceTest.cs b/Orm/Xtensive.Orm.Tests/Model/CycleReferenceTest.cs index 0b1ee963b3..8d405c9da9 100644 --- a/Orm/Xtensive.Orm.Tests/Model/CycleReferenceTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/CycleReferenceTest.cs @@ -7,10 +7,11 @@ using System; using System.Reflection; using NUnit.Framework; +using Xtensive.Orm.Configuration; +using Xtensive.Orm.Tests.Model.CycleReferenceTestModel; namespace Xtensive.Orm.Tests.Model.CycleReferenceTestModel { - [Serializable] [HierarchyRoot] public class Parent : Entity { @@ -24,12 +25,10 @@ public class Parent : Entity public Neighbor Neighbor { get; set; } } - [Serializable] public class Child : Parent { } - [Serializable] [HierarchyRoot] public class Neighbor : Entity { @@ -43,21 +42,16 @@ public class Neighbor : Entity namespace Xtensive.Orm.Tests.Model { - [TestFixture] - public class CycleReferenceTest + [TestFixture, Category("Model")] + public class CycleReferenceTest : DomainBuildabilityTest { - [Test] - // [ExpectedException(typeof(InvalidOperationException))] - public void CombinedTest() + protected override DomainConfiguration BuildConfiguration() { var config = DomainConfigurationFactory.Create(); - config.Types.RegisterCaching(Assembly.GetExecutingAssembly(), "Xtensive.Orm.Tests.Model.CycleReferenceTestModel"); - - using (var domain = Domain.Build(config)) - using (var session = domain.OpenSession()) - using (var t = session.OpenTransaction()) { - t.Complete(); - } + config.Types.Register(typeof(Parent)); + config.Types.Register(typeof(Child)); + config.Types.Register(typeof(Neighbor)); + return config; } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Model/CyclicContainedStructureTest.cs b/Orm/Xtensive.Orm.Tests/Model/CyclicContainedStructureTest.cs index fb0466a542..9e2e3bd0c9 100644 --- a/Orm/Xtensive.Orm.Tests/Model/CyclicContainedStructureTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/CyclicContainedStructureTest.cs @@ -8,28 +8,23 @@ using System.Linq; using System.Reflection; using NUnit.Framework; -using Xtensive.Core; -using Xtensive.Orm.Configuration; namespace Xtensive.Orm.Tests.Model.ReferenceTestModel { #region Cyclic referenced structures - [Serializable] public class S1 : Structure { [Field] public S2 Value { get; set; } } - [Serializable] public class S2 : Structure { [Field] public S3 Value { get; set; } } - [Serializable] public class S3 : Structure { [Field] @@ -40,14 +35,12 @@ public class S3 : Structure #region Cyclic contained structures with inheritance - [Serializable] public class Parent : Structure { [Field] public Child Value { get; set; } } - [Serializable] public class Child : Parent { } @@ -57,7 +50,7 @@ public class Child : Parent namespace Xtensive.Orm.Tests.Model { - [TestFixture] + [TestFixture, Category("Model")] public class CyclicContainedStructureTest { [Test] @@ -66,7 +59,7 @@ public void MainTest() var config = DomainConfigurationFactory.Create(); config.UpgradeMode = DomainUpgradeMode.Recreate; config.Types.RegisterCaching(Assembly.GetExecutingAssembly(), "Xtensive.Orm.Tests.Model.ReferenceTestModel"); - var ex = Assert.Throws(() => Domain.Build(config)); + var ex = Assert.Throws(() => Domain.Build(config).Dispose()); Assert.That(ex.Message.StartsWith("At least one loop have been found"), Is.True); } } diff --git a/Orm/Xtensive.Orm.Tests/Model/CyclicHierarchyDependenciesTest.cs b/Orm/Xtensive.Orm.Tests/Model/CyclicHierarchyDependenciesTest.cs index f84a01c60c..028fc2be19 100644 --- a/Orm/Xtensive.Orm.Tests/Model/CyclicHierarchyDependenciesTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/CyclicHierarchyDependenciesTest.cs @@ -6,13 +6,10 @@ using System; using NUnit.Framework; -using Xtensive.Core; -using Xtensive.Orm.Configuration; using Xtensive.Orm.Tests.CyclicHierarchyDependenciesModel; namespace Xtensive.Orm.Tests.CyclicHierarchyDependenciesModel { - [Serializable] [HierarchyRoot] public class H1 : Entity { @@ -23,7 +20,6 @@ public class H1 : Entity public H3 Second { get; private set; } } - [Serializable] [HierarchyRoot] public class H2 : Entity { @@ -34,7 +30,6 @@ public class H2 : Entity public H3 Second { get; private set; } } - [Serializable] [HierarchyRoot] public class H3 : Entity { @@ -48,7 +43,7 @@ public class H3 : Entity namespace Xtensive.Orm.Tests.Model { - [TestFixture] + [TestFixture, Category("Model")] public class CyclicHierarchyDependenciesTest { [Test] @@ -57,7 +52,7 @@ public void MainTest() var config = DomainConfigurationFactory.Create(); config.UpgradeMode = DomainUpgradeMode.Recreate; config.Types.RegisterCaching(typeof(H1).Assembly, typeof(H1).Namespace); - var ex = Assert.Throws(() => Domain.Build(config)); + var ex = Assert.Throws(() => Domain.Build(config).Dispose()); Assert.That(ex.Message.StartsWith("At least one loop have been found"), Is.True); } } diff --git a/Orm/Xtensive.Orm.Tests/Model/DomainBuildabilityTest.cs b/Orm/Xtensive.Orm.Tests/Model/DomainBuildabilityTest.cs new file mode 100644 index 0000000000..cee063ca8f --- /dev/null +++ b/Orm/Xtensive.Orm.Tests/Model/DomainBuildabilityTest.cs @@ -0,0 +1,30 @@ +// Copyright (C) 2009-2020 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System; +using NUnit.Framework; +using Xtensive.Orm.Configuration; + +namespace Xtensive.Orm.Tests.Model +{ + [TestFixture, Category("Model")] + public abstract class DomainBuildabilityTest + { + [Test] + public void DomainBuildTest() + { + var configuration = BuildConfiguration(); + Assert.DoesNotThrow(() => Domain.Build(configuration).Dispose()); + } + + [Test] + public void DomainBuildAsyncTest() + { + var configuration = BuildConfiguration(); + Assert.DoesNotThrowAsync(async () => (await Domain.BuildAsync(configuration)).Dispose()); + } + + protected abstract DomainConfiguration BuildConfiguration(); + } +} diff --git a/Orm/Xtensive.Orm.Tests/Model/FieldConverterTest.cs b/Orm/Xtensive.Orm.Tests/Model/FieldConverterTest.cs index 786edf234e..28537a612c 100644 --- a/Orm/Xtensive.Orm.Tests/Model/FieldConverterTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/FieldConverterTest.cs @@ -5,18 +5,16 @@ // Created: 2009.11.20 using System; -using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.IO; -using System.Runtime.Serialization.Formatters.Binary; +using System.Runtime.Serialization; using NUnit.Framework; using Xtensive.Orm.Configuration; using Xtensive.Orm.Tests.Model.FieldConverterTestModel; namespace Xtensive.Orm.Tests.Model.FieldConverterTestModel { - [Serializable] [HierarchyRoot] public class Person : Entity { @@ -49,8 +47,8 @@ public DateTime? Date private static byte[] Serialize(ObservableCollection collection) { using (var ms = new MemoryStream()) { - var bf = new BinaryFormatter(); - bf.Serialize(ms, collection); + var dcSerializer = new DataContractSerializer(typeof(ObservableCollection), new[] { typeof(int) }); + dcSerializer.WriteObject(ms, collection); return ms.ToArray(); } } @@ -58,8 +56,8 @@ private static byte[] Serialize(ObservableCollection collection) private static ObservableCollection Deserialize(byte[] bytes) { using (var ms = new MemoryStream(bytes)) { - var bf = new BinaryFormatter(); - return (ObservableCollection) bf.Deserialize(ms); + var dcSerializer = new DataContractSerializer(typeof(ObservableCollection), new[] { typeof(int) }); + return (ObservableCollection) dcSerializer.ReadObject(ms); } } @@ -91,12 +89,13 @@ void Collection_CollectionChanged(object sender, NotifyCollectionChangedEventArg namespace Xtensive.Orm.Tests.Model { + [TestFixture, Category("Model")] public class FieldConverterTest : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof (Person).Assembly, typeof (Person).Namespace); + config.Types.Register(typeof (Person)); return config; } diff --git a/Orm/Xtensive.Orm.Tests/Model/FullText/DynamicallyDefinedFieldsAndIndexesTest.cs b/Orm/Xtensive.Orm.Tests/Model/FullText/DynamicallyDefinedFieldsAndIndexesTest.cs index 2e7e0a368c..d52dd74b23 100644 --- a/Orm/Xtensive.Orm.Tests/Model/FullText/DynamicallyDefinedFieldsAndIndexesTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/FullText/DynamicallyDefinedFieldsAndIndexesTest.cs @@ -134,6 +134,7 @@ private void DefineFullTextIndex(DomainModelDef model) namespace Xtensive.Orm.Tests.Model { + [TestFixture, Category("Model")] public class DynamicallyDefinedFieldsAndIndexesTest : AutoBuildTest { protected override void CheckRequirements() diff --git a/Orm/Xtensive.Orm.Tests/Model/FullText/IndexOnStructureFieldNamingTest.cs b/Orm/Xtensive.Orm.Tests/Model/FullText/IndexOnStructureFieldNamingTest.cs index 589276bd73..d4cc80c320 100644 --- a/Orm/Xtensive.Orm.Tests/Model/FullText/IndexOnStructureFieldNamingTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/FullText/IndexOnStructureFieldNamingTest.cs @@ -114,6 +114,7 @@ public class BaseEntity : Entity namespace Xtensive.Orm.Tests.Model { + [TestFixture, Category("Model")] public class IndexOnStructureFieldNamingTest : AutoBuildTest { private static readonly List UnderscoreRuleExpectedColumns = new List { diff --git a/Orm/Xtensive.Orm.Tests/Model/FullText/IndexOnStructureFieldTest.cs b/Orm/Xtensive.Orm.Tests/Model/FullText/IndexOnStructureFieldTest.cs index 5b3c0ee365..6e2c6877ed 100644 --- a/Orm/Xtensive.Orm.Tests/Model/FullText/IndexOnStructureFieldTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/FullText/IndexOnStructureFieldTest.cs @@ -104,6 +104,7 @@ public class BaseEntity : Entity namespace Xtensive.Orm.Tests.Model { + [TestFixture, Category("Model")] public class IndexOnStructureFieldTest : AutoBuildTest { [Test] diff --git a/Orm/Xtensive.Orm.Tests/Model/GenericManyToManyTest.cs b/Orm/Xtensive.Orm.Tests/Model/GenericManyToManyTest.cs index fc5677d0c1..f3df4a4138 100644 --- a/Orm/Xtensive.Orm.Tests/Model/GenericManyToManyTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/GenericManyToManyTest.cs @@ -5,6 +5,7 @@ // Created: 2010.03.03 using NUnit.Framework; +using Xtensive.Orm.Configuration; namespace Xtensive.Orm.Tests.Model { @@ -43,22 +44,15 @@ public class Target : Entity namespace Xtensive.Orm.Tests.Model { - [TestFixture] - public class GenericManyToManyTest : AutoBuildTest + [TestFixture, Category("Model")] + public class GenericManyToManyTest : DomainBuildabilityTest { - - protected override Xtensive.Orm.Configuration.DomainConfiguration BuildConfiguration() + protected override DomainConfiguration BuildConfiguration() { - var configuration = base.BuildConfiguration(); + var configuration = DomainConfigurationFactory.Create(); configuration.Types.Register(typeof (Target)); configuration.Types.Register(typeof (Source)); return configuration; } - - [Test] - public void CombinedTest() - { - - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Model/HierarchyRootValidationTest.cs b/Orm/Xtensive.Orm.Tests/Model/HierarchyRootValidationTest.cs index ae69ec17cc..41d415e8da 100644 --- a/Orm/Xtensive.Orm.Tests/Model/HierarchyRootValidationTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/HierarchyRootValidationTest.cs @@ -20,7 +20,7 @@ namespace Xtensive.Orm.Tests.Model { - [TestFixture] + [TestFixture, Category("Model")] public sealed class HierarchyRootValidationTest { private const string CantBeOfMsg = "can't be of"; @@ -1253,7 +1253,7 @@ public void IModuleModifications() typeof(Models.IModuleModifications.ModelDefModifier) }); - _ = Assert.Throws(() => domain = Domain.Build(configuration)); + _ = Assert.Throws(() => Domain.Build(configuration).Dispose()); // IModule changes HierarhyRootDef.IncludeTypeId configuration = CreateDomainConfiguration(new[] { diff --git a/Orm/Xtensive.Orm.Tests/Model/HierarchyTest.cs b/Orm/Xtensive.Orm.Tests/Model/HierarchyTest.cs index 706ed4f9b9..c30fdcffe9 100644 --- a/Orm/Xtensive.Orm.Tests/Model/HierarchyTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/HierarchyTest.cs @@ -24,7 +24,6 @@ public interface IA : I0 { } - [Serializable] public class A : Entity, IA { string I0.AName { get; set; } @@ -33,7 +32,6 @@ public class A : Entity, IA public string AName { get; set; } } - [Serializable] [HierarchyRoot] public class AB : A { @@ -44,17 +42,14 @@ public class AB : A public string ABName { get; set; } } - [Serializable] public class ABC : AB { } - [Serializable] public abstract class B : Entity { } - [Serializable] [HierarchyRoot] public class BC : B { @@ -62,7 +57,6 @@ public class BC : B public Guid ID { get; private set; } } - [Serializable] [HierarchyRoot] public class BD : B { @@ -73,7 +67,6 @@ public class BD : B public string AName { get; set; } } - [Serializable] [HierarchyRoot] public class BE : B { @@ -81,14 +74,12 @@ public class BE : B public int ID { get; private set; } } - [Serializable] public class IdentifiableEntity : Entity { [Field, Key] public Guid Id { get; private set; } } - [Serializable] [HierarchyRoot] public class MyEntity : IdentifiableEntity { @@ -130,6 +121,7 @@ public void OnDefinitionsBuilt(BuildingContext context, DomainModelDef model) namespace Xtensive.Orm.Tests.Model { + [TestFixture, Category("Model")] public class HierarchyTest : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() @@ -159,21 +151,29 @@ public override void TestFixtureTearDown() [Test] public void MainTest() { - Assert.That(Domain.Model.Types.Contains(typeof (A)), Is.False); - Assert.That(Domain.Model.Types[typeof (AB)], Is.Not.Null); - Assert.That(Domain.Model.Types[typeof (AB)].Fields["ID"], Is.Not.Null); - Assert.That(Domain.Model.Types[typeof (AB)].Fields["ABName"], Is.Not.Null); - Assert.That(Domain.Model.Types[typeof (AB)].Fields["AName"], Is.Not.Null); - Assert.That(Domain.Model.Types[typeof (AB)].Fields["ABName"].DeclaringType, Is.EqualTo(Domain.Model.Types[typeof (AB)])); - Assert.That(Domain.Model.Types[typeof (AB)].Fields["AName"].DeclaringType, Is.EqualTo(Domain.Model.Types[typeof (AB)])); - Assert.That(Domain.Model.Types[typeof (AB)].Hierarchy.Root, Is.EqualTo(Domain.Model.Types[typeof (AB)])); - Assert.That(Domain.Model.Types[typeof (ABC)].Hierarchy.Root, Is.EqualTo(Domain.Model.Types[typeof (AB)])); - Assert.That(Domain.Model.Types[typeof (ABC)].Hierarchy, Is.EqualTo(Domain.Model.Types[typeof (AB)].Hierarchy)); - Assert.That(Domain.Model.Types[typeof (AB)].Fields["ID"].ValueType, Is.EqualTo(typeof (long))); - Assert.That(Domain.Model.Types[typeof (ABC)].Fields["ID"].ValueType, Is.EqualTo(typeof (long))); - Assert.That(Domain.Model.Types[typeof (BC)].Fields["ID"].ValueType, Is.EqualTo(typeof (Guid))); - Assert.That(Domain.Model.Types[typeof (BD)].Fields["ID"].ValueType, Is.EqualTo(typeof (long))); - Assert.That(Domain.Model.Types[typeof (BE)].Fields["ID"].ValueType, Is.EqualTo(typeof (int))); + var modelTypes = Domain.Model.Types; + + Assert.That(modelTypes.Contains(typeof (A)), Is.False); + + var abType = modelTypes[typeof (AB)]; + Assert.That(abType, Is.Not.Null); + Assert.That(abType.Fields["ID"], Is.Not.Null); + Assert.That(abType.Fields["ID"].ValueType, Is.EqualTo(typeof(long))); + Assert.That(abType.Fields["ABName"], Is.Not.Null); + Assert.That(abType.Fields["AName"], Is.Not.Null); + Assert.That(abType.Fields["ABName"].DeclaringType, Is.EqualTo(abType)); + Assert.That(abType.Fields["AName"].DeclaringType, Is.EqualTo(abType)); + Assert.That(abType.Hierarchy.Root, Is.EqualTo(abType)); + + var abcType = modelTypes[typeof(ABC)]; + Assert.That(abcType.Hierarchy.Root, Is.EqualTo(abType)); + Assert.That(abcType.Hierarchy, Is.EqualTo(abType.Hierarchy)); + Assert.That(abcType.Fields["ID"].ValueType, Is.EqualTo(typeof (long))); + + var bcType = modelTypes[typeof (BC)]; + Assert.That(bcType.Fields["ID"].ValueType, Is.EqualTo(typeof (Guid))); + Assert.That(modelTypes[typeof(BD)].Fields["ID"].ValueType, Is.EqualTo(typeof (long))); + Assert.That(modelTypes[typeof(BE)].Fields["ID"].ValueType, Is.EqualTo(typeof (int))); } [Test] diff --git a/Orm/Xtensive.Orm.Tests/Model/IndexedStructureFieldTest.cs b/Orm/Xtensive.Orm.Tests/Model/IndexedStructureFieldTest.cs index 89a04c2362..58f24a3ccc 100644 --- a/Orm/Xtensive.Orm.Tests/Model/IndexedStructureFieldTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/IndexedStructureFieldTest.cs @@ -51,19 +51,15 @@ public class Indexed2 : Entity, IHierarchical2 } } - public class IndexedStructureFieldTest : AutoBuildTest + [TestFixture, Category("Model")] + public class IndexedStructureFieldTest : DomainBuildabilityTest { protected override DomainConfiguration BuildConfiguration() { - var configuration = base.BuildConfiguration(); + var configuration = DomainConfigurationFactory.Create(); configuration.NamingConvention.NamingRules = NamingRules.UnderscoreDots; configuration.Types.RegisterCaching(typeof(Hierarchy).Assembly, typeof(Hierarchy).Namespace); return configuration; } - - [Test] - public void Test() - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Model/InheritanceSchemaTest.cs b/Orm/Xtensive.Orm.Tests/Model/InheritanceSchemaTest.cs index 4a355e4aaa..4cc48c0369 100644 --- a/Orm/Xtensive.Orm.Tests/Model/InheritanceSchemaTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/InheritanceSchemaTest.cs @@ -149,6 +149,7 @@ protected override InheritanceSchema InheritanceSchema namespace Xtensive.Orm.Tests.Model.InheritanceSchemaTests { + [TestFixture, Category("Model")] public abstract class InheritanceSchemaTestBase : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() @@ -165,6 +166,12 @@ public override void TestFixtureTearDown() SingleTableInheritanceBuilder.IsEnabled = false; base.TestFixtureTearDown(); } + + [Test] + public virtual void MainTest() + { + Domain.Model.Dump(); + } } public class ClassTableInheritanceTest : InheritanceSchemaTestBase @@ -176,12 +183,6 @@ protected override DomainConfiguration BuildConfiguration() SingleTableInheritanceBuilder.IsEnabled = false; return dc; } - - [Test] - public virtual void MainTest() - { - Domain.Model.Dump(); - } } public class ConcreteTableInheritanceTest : InheritanceSchemaTestBase @@ -193,12 +194,6 @@ protected override DomainConfiguration BuildConfiguration() SingleTableInheritanceBuilder.IsEnabled = false; return configuration; } - - [Test] - public virtual void MainTest() - { - Domain.Model.Dump(); - } } public class SingleTableInheritanceTest : InheritanceSchemaTestBase @@ -210,11 +205,5 @@ protected override DomainConfiguration BuildConfiguration() SingleTableInheritanceBuilder.IsEnabled = true; return configuration; } - - [Test] - public virtual void MainTest() - { - Domain.Model.Dump(); - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Model/InheritedKeyFieldTest.cs b/Orm/Xtensive.Orm.Tests/Model/InheritedKeyFieldTest.cs index 070ad3cc56..eb43abbe29 100644 --- a/Orm/Xtensive.Orm.Tests/Model/InheritedKeyFieldTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/InheritedKeyFieldTest.cs @@ -8,17 +8,16 @@ using Xtensive.Orm; using Xtensive.Orm.Configuration; using InheritedKeyFieldModel; +using NUnit.Framework; namespace InheritedKeyFieldModel { - [Serializable] public class H0 : Entity { [Field] public virtual int Id { get; private set; } } - [Serializable] [HierarchyRoot] public class H1 : H0 { @@ -32,7 +31,6 @@ public override int Id } } - [Serializable] [HierarchyRoot] public class H2 : H0 { @@ -49,12 +47,14 @@ public override int Id namespace Xtensive.Orm.Tests.Model { - public class InheritedKeyFieldTest : AutoBuildTest + [TestFixture, Category("Model")] + public class InheritedKeyFieldTest : DomainBuildabilityTest { protected override DomainConfiguration BuildConfiguration() { - var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof (H0).Assembly, typeof (H0).Namespace); + var config = DomainConfigurationFactory.Create(); + config.Types.Register(typeof (H0)); + config.Types.Register(typeof (H2)); return config; } } diff --git a/Orm/Xtensive.Orm.Tests/Model/LibraryTest.cs b/Orm/Xtensive.Orm.Tests/Model/LibraryTest.cs index da80d5b424..b6a567864d 100644 --- a/Orm/Xtensive.Orm.Tests/Model/LibraryTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/LibraryTest.cs @@ -23,7 +23,6 @@ namespace Xtensive.Orm.Tests.Model.LibraryModel { - [Serializable] public class IdentityCard : Structure { [Field(Length = 64)] @@ -36,7 +35,6 @@ public class IdentityCard : Structure public string LastName { get; set; } } - [Serializable] public class Passport : Structure { [Field] @@ -46,7 +44,6 @@ public class Passport : Structure public IdentityCard Card { get; set; } } - [Serializable] [HierarchyRoot] public class Person : Entity { @@ -70,7 +67,6 @@ public Passport Passport public EntitySet Reviews { get; private set; } } - [Serializable] [Index("PenName:DESC", Name = "IX_PENNAME")] public class Author : Person { @@ -81,7 +77,6 @@ public class Author : Person public EntitySet Books { get; private set; } } - [Serializable] [KeyGenerator(KeyGeneratorKind.None)] [HierarchyRoot] public class Book : Entity @@ -104,7 +99,6 @@ public Book(string isbn) } } - [Serializable] [KeyGenerator(KeyGeneratorKind.None)] [HierarchyRoot] public class BookReview : Entity diff --git a/Orm/Xtensive.Orm.Tests/Model/NameBuilderTest.cs b/Orm/Xtensive.Orm.Tests/Model/NameBuilderTest.cs index c7c9406380..a0d5dcd3fd 100644 --- a/Orm/Xtensive.Orm.Tests/Model/NameBuilderTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/NameBuilderTest.cs @@ -97,7 +97,7 @@ public class Point : Structure namespace Xtensive.Orm.Tests.Model { - [TestFixture] + [TestFixture, Category("Model")] public class NameBuilderTest : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() diff --git a/Orm/Xtensive.Orm.Tests/Model/NonPublicFieldTest.cs b/Orm/Xtensive.Orm.Tests/Model/NonPublicFieldTest.cs index d64c7a15d6..05afdc5688 100644 --- a/Orm/Xtensive.Orm.Tests/Model/NonPublicFieldTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/NonPublicFieldTest.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Model.NonPublicFieldTestModel { - [Serializable] [HierarchyRoot] public class MyEntity : Entity { @@ -46,6 +45,7 @@ public bool ValidateState() namespace Xtensive.Orm.Tests.Model { + [TestFixture, Category("Model")] public class NonPublicFieldTest : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() diff --git a/Orm/Xtensive.Orm.Tests/Model/PairTest.cs b/Orm/Xtensive.Orm.Tests/Model/PairTest.cs index d2384a3c01..1bed3ac017 100644 --- a/Orm/Xtensive.Orm.Tests/Model/PairTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/PairTest.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.PairModel { - [Serializable] [HierarchyRoot] public class Master : Entity { @@ -22,14 +21,13 @@ public class Master : Entity public Slave Slave { get; set; } } - [Serializable] [HierarchyRoot] public class Slave : Entity { [Field, Key] public int Id { get; private set; } - [Field , Association(PairTo = "Slave")] + [Field , Association(PairTo = nameof(PairModel.Master.Slave))] public Master Master { get; set; } } @@ -37,13 +35,14 @@ public class Slave : Entity namespace Xtensive.Orm.Tests.Model { - [TestFixture] + [TestFixture, Category("Model")] public class PairTest : AutoBuildTest { protected override Xtensive.Orm.Configuration.DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); - config.Types.RegisterCaching(Assembly.GetExecutingAssembly(), typeof(Master).Namespace); + config.Types.Register(typeof(Master)); + config.Types.Register(typeof(Slave)); return config; } diff --git a/Orm/Xtensive.Orm.Tests/Model/ReferencedKeys.cs b/Orm/Xtensive.Orm.Tests/Model/ReferencedKeys.cs index 7fbf5c2da8..7b39651954 100644 --- a/Orm/Xtensive.Orm.Tests/Model/ReferencedKeys.cs +++ b/Orm/Xtensive.Orm.Tests/Model/ReferencedKeys.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Model.ReferencedKeysModel { - [Serializable] [KeyGenerator(KeyGeneratorKind.None)] [HierarchyRoot] public class Country : Entity @@ -28,7 +27,6 @@ public Country(string name) } } - [Serializable] [KeyGenerator(KeyGeneratorKind.None)] [HierarchyRoot] public class City : Entity @@ -47,20 +45,15 @@ public City(Country country, string name) } namespace Xtensive.Orm.Tests.Model -{ - [TestFixture] - public class ReferencedKeys : AutoBuildTest +{ + public class ReferencedKeys : DomainBuildabilityTest { protected override DomainConfiguration BuildConfiguration() { - var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof (Country).Assembly, typeof (Country).Namespace); + var config = DomainConfigurationFactory.Create(); + config.Types.Register(typeof(Country)); + config.Types.Register(typeof(City)); return config; } - - [Test] - public void MainTest() - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Model/RemoveDotsAndHypensTest.cs b/Orm/Xtensive.Orm.Tests/Model/RemoveDotsAndHypensTest.cs index d48c2c1a24..eff2161de9 100644 --- a/Orm/Xtensive.Orm.Tests/Model/RemoveDotsAndHypensTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/RemoveDotsAndHypensTest.cs @@ -43,6 +43,7 @@ public class MetaInfo : Entity } } + [TestFixture, Category("Model")] public class RemoveDotsAndHypensTest : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() diff --git a/Orm/Xtensive.Orm.Tests/Model/SelfContainedStructureTest.cs b/Orm/Xtensive.Orm.Tests/Model/SelfContainedStructureTest.cs index e0d93f48e5..65dab9baea 100644 --- a/Orm/Xtensive.Orm.Tests/Model/SelfContainedStructureTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/SelfContainedStructureTest.cs @@ -6,13 +6,11 @@ using System; using NUnit.Framework; -using Xtensive.Core; using Xtensive.Orm.Configuration; using Xtensive.Orm.Tests.Model.SelfContainedStructureModel; namespace Xtensive.Orm.Tests.Model.SelfContainedStructureModel { - [Serializable] public class SelfContained : Structure { [Field] @@ -22,24 +20,27 @@ public class SelfContained : Structure namespace Xtensive.Orm.Tests.Model { - public class SelfContainedStructureTest : AutoBuildTest + public class SelfContainedStructureTest { - protected override DomainConfiguration BuildConfiguration() + [Test] + public void DomainBuildTest() { - var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof (SelfContained).Assembly, typeof (SelfContained).Namespace); - return config; + var configuration = BuildConfiguration(); + _ = Assert.Throws(() => Domain.Build(configuration).Dispose()); } - protected override Domain BuildDomain(DomainConfiguration configuration) + [Test] + public void DomainBuildAsyncTest() { - Domain domain = null; - try { - domain = Domain.Build(configuration); - } - catch (DomainBuilderException) { - } - return domain; + var configuration = BuildConfiguration(); + _ = Assert.ThrowsAsync(async () => (await Domain.BuildAsync(configuration)).Dispose()); + } + + private static DomainConfiguration BuildConfiguration() + { + var config = DomainConfigurationFactory.Create(); + config.Types.Register(typeof(SelfContained)); + return config; } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Model/SerializationTest.cs b/Orm/Xtensive.Orm.Tests/Model/SerializationTest.cs index 3c4a3cd165..3d1ddc1c09 100644 --- a/Orm/Xtensive.Orm.Tests/Model/SerializationTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/SerializationTest.cs @@ -1,10 +1,11 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2009-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Denis Krjuchkov // Created: 2009.05.21 using System.IO; +using System.Text.Json; using NUnit.Framework; using Xtensive.Orm.Configuration; using Xtensive.Orm.Model; diff --git a/Orm/Xtensive.Orm.Tests/Model/StringKeyTest.cs b/Orm/Xtensive.Orm.Tests/Model/StringKeyTest.cs index 8b59bd9844..3da3ba8514 100644 --- a/Orm/Xtensive.Orm.Tests/Model/StringKeyTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/StringKeyTest.cs @@ -5,13 +5,14 @@ // Created: 2009.06.25 using System; +using System.Threading.Tasks; using NUnit.Framework; +using Xtensive.Core; using Xtensive.Orm.Configuration; using Xtensive.Orm.Tests.Model.StringKeyTestModel; namespace Xtensive.Orm.Tests.Model.StringKeyTestModel { - [Serializable] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] public class Product : Entity @@ -28,18 +29,13 @@ public Product(string code) : base(code) { } namespace Xtensive.Orm.Tests.Model { - public class StringKeyTest : AutoBuildTest + public class StringKeyTest : DomainBuildabilityTest { protected override DomainConfiguration BuildConfiguration() { - var config = base.BuildConfiguration(); - config.Types.Register(typeof (Product)); + var config = DomainConfigurationFactory.Create(); + config.Types.Register(typeof(Product)); return config; } - - [Test] - public void MainTest() - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Model/UnicodeNamesTest.cs b/Orm/Xtensive.Orm.Tests/Model/UnicodeNamesTest.cs index 2e42621686..8e899c0e04 100644 --- a/Orm/Xtensive.Orm.Tests/Model/UnicodeNamesTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/UnicodeNamesTest.cs @@ -27,9 +27,8 @@ public void MainTest() { Require.ProviderIsNot(StorageProvider.MySql | StorageProvider.Firebird); var config = DomainConfigurationFactory.Create(); - config.Types.RegisterCaching(typeof(Энимал).Assembly, typeof(Энимал).Namespace); - var domain = Domain.Build(config); - domain.Dispose(); + config.Types.Register(typeof(Энимал).Assembly, typeof(Энимал).Namespace); + using var domain = Domain.Build(config); } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Model/VersionInfoTest.cs b/Orm/Xtensive.Orm.Tests/Model/VersionInfoTest.cs index a9788c41b2..16d8a16438 100644 --- a/Orm/Xtensive.Orm.Tests/Model/VersionInfoTest.cs +++ b/Orm/Xtensive.Orm.Tests/Model/VersionInfoTest.cs @@ -8,15 +8,13 @@ using System.Reflection; using System.Linq; using NUnit.Framework; -using Xtensive.Core; -using Xtensive.Orm.Tests; using Xtensive.Orm.Tests.Model.VersionInfoTests.ValidModel; + #region Models namespace Xtensive.Orm.Tests.Model.VersionInfoTests.InvalidModel1 { - [Serializable] [HierarchyRoot] public class Parent : Entity { @@ -27,7 +25,6 @@ public class Parent : Entity public string ParentVersionField { get; set; } } - [Serializable] public class Child : Parent { [Field, Version] @@ -37,7 +34,6 @@ public class Child : Parent namespace Xtensive.Orm.Tests.Model.VersionInfoTests.InvalidModel2 { - [Serializable] [HierarchyRoot] public class Parent : Entity { @@ -48,7 +44,6 @@ public class Parent : Entity namespace Xtensive.Orm.Tests.Model.VersionInfoTests.InvalidModel3 { - [Serializable] [HierarchyRoot] public class Parent : Entity { @@ -62,7 +57,6 @@ public class Parent : Entity namespace Xtensive.Orm.Tests.Model.VersionInfoTests.ValidModel { - [Serializable] [HierarchyRoot] public class Parent : Entity { @@ -76,14 +70,12 @@ public class Parent : Entity public string ParentNonVersionField { get; set; } } - [Serializable] public class Child : Parent { [Field] public string ChildNonVersionField { get; set; } } - [Serializable] [HierarchyRoot] public class Simple : Entity { @@ -112,7 +104,6 @@ public class Simple : Entity public byte[] ByteArrayField { get; set; } } - [Serializable] public class SimpleStructure : Structure { [Field] @@ -130,8 +121,6 @@ public class SimpleStructure : Structure namespace Xtensive.Orm.Tests.Model { - - [TestFixture] public class VersionInfoTest { @@ -153,68 +142,47 @@ public Domain BuildDomain(string @namespace) public void DenyKeyFieldsTest() { AssertEx.Throws(() => - BuildDomain("Xtensive.Orm.Tests.Model.VersionInfoTests.InvalidModel2")); + BuildDomain("Xtensive.Orm.Tests.Model.VersionInfoTests.InvalidModel2").Dispose()); } [Test] public void DenyLazyLoadFieldsTest() { AssertEx.Throws(() => - BuildDomain("Xtensive.Orm.Tests.Model.VersionInfoTests.InvalidModel3")); + BuildDomain("Xtensive.Orm.Tests.Model.VersionInfoTests.InvalidModel3").Dispose()); } [Test] public void VersionFieldsTest() { - var domain = BuildDomain("Xtensive.Orm.Tests.Model.VersionInfoTests.ValidModel"); + using var domain = BuildDomain("Xtensive.Orm.Tests.Model.VersionInfoTests.ValidModel"); var model = domain.Model; var parentType = model.Types[typeof (Parent)]; - Assert.That(parentType.GetVersionFields().Any(field => field==parentType.Fields["ParentVersionField"]), Is.True); - Assert.That(parentType.GetVersionFields().Any(field => field==parentType.Fields["ParentNonVersionField"]), Is.False); + var versionFields = parentType.GetVersionFields(); + Assert.That(versionFields.Any(field => field == parentType.Fields["ParentVersionField"]), Is.True); + Assert.That(versionFields.Any(field => field == parentType.Fields["ParentNonVersionField"]), Is.False); var childType = model.Types[typeof (Child)]; - Assert.That(childType.GetVersionFields().Any(field => field==childType.Fields["ParentVersionField"]), Is.True); - Assert.That(childType.GetVersionFields().Any(field => field==childType.Fields["ParentNonVersionField"]), Is.False); - Assert.That(childType.GetVersionFields().Any(field => field==childType.Fields["ChildNonVersionField"]), Is.False); + versionFields = childType.GetVersionFields(); + Assert.That(versionFields.Any(field => field == childType.Fields["ParentVersionField"]), Is.True); + Assert.That(versionFields.Any(field => field == childType.Fields["ParentNonVersionField"]), Is.False); + Assert.That(versionFields.Any(field => field == childType.Fields["ChildNonVersionField"]), Is.False); var simpleType = model.Types[typeof (Simple)]; - Assert.That(simpleType.GetVersionColumns().Any(pair => pair.Field==simpleType.Fields["NonLazyField1"]), Is.True); - Assert.That(simpleType.GetVersionColumns().Any(pair => pair.Field==simpleType.Fields["NonLazyField2"]), Is.True); - Assert.That(simpleType.GetVersionColumns().Any(pair => pair.Field==simpleType.Fields["ReferenceField.Id"]), Is.True); - Assert.That(simpleType.GetVersionColumns().Any(pair => pair.Field==simpleType.Fields["Id"]), Is.False); - Assert.That(simpleType.GetVersionColumns().Any(pair => pair.Field==simpleType.Fields["TypeId"]), Is.False); - Assert.That(simpleType.GetVersionColumns().Any(pair => pair.Field==simpleType.Fields["LazyField"]), Is.False); - Assert.That(simpleType.GetVersionColumns().Any(pair => pair.Field==simpleType.Fields["CollectionField"]), Is.False); - Assert.That(simpleType.GetVersionColumns().Any(pair => pair.Field==simpleType.Fields["StructureField"]), Is.False); - Assert.That(simpleType.GetVersionColumns().Any(pair => pair.Field==simpleType.Fields["StructureField.NonLazyField"]), Is.True); - Assert.That(simpleType.GetVersionColumns().Any(pair => pair.Field==simpleType.Fields["StructureField.LazyField"]), Is.False); - Assert.That(simpleType.GetVersionColumns().Any(pair => pair.Field==simpleType.Fields["StructureField.ReferenceField.Id"]), Is.True); - Assert.That(simpleType.GetVersionColumns().Any(pair => pair.Field==simpleType.Fields["ByteArrayField"]), Is.False); - } - - [Test] - public void SerializeVersionInfoTest() - { - var domain = BuildDomain("Xtensive.Orm.Tests.Model.VersionInfoTests.ValidModel"); - VersionInfo version; - - using (var session = domain.OpenSession()) { - using (var transactionScope = session.OpenTransaction()) { - var instance = new Simple(); - instance.NonLazyField1 = "Value"; - instance.NonLazyField2 = 123; - instance.StructureField = new SimpleStructure {NonLazyField = "Value"}; - instance.ReferenceField = instance; - version = instance.VersionInfo; - transactionScope.Complete(); - } - } - - Assert.That(version.IsVoid, Is.False); - var versionClone = Cloner.Clone(version); - Assert.That(versionClone.IsVoid, Is.False); - Assert.That(versionClone, Is.EqualTo(version)); + var versionColumns = simpleType.GetVersionColumns(); + Assert.That(versionColumns.Any(pair => pair.Field == simpleType.Fields["NonLazyField1"]), Is.True); + Assert.That(versionColumns.Any(pair => pair.Field == simpleType.Fields["NonLazyField2"]), Is.True); + Assert.That(versionColumns.Any(pair => pair.Field == simpleType.Fields["ReferenceField.Id"]), Is.True); + Assert.That(versionColumns.Any(pair => pair.Field == simpleType.Fields["Id"]), Is.False); + Assert.That(versionColumns.Any(pair => pair.Field == simpleType.Fields["TypeId"]), Is.False); + Assert.That(versionColumns.Any(pair => pair.Field == simpleType.Fields["LazyField"]), Is.False); + Assert.That(versionColumns.Any(pair => pair.Field == simpleType.Fields["CollectionField"]), Is.False); + Assert.That(versionColumns.Any(pair => pair.Field == simpleType.Fields["StructureField"]), Is.False); + Assert.That(versionColumns.Any(pair => pair.Field == simpleType.Fields["StructureField.NonLazyField"]), Is.True); + Assert.That(versionColumns.Any(pair => pair.Field == simpleType.Fields["StructureField.LazyField"]), Is.False); + Assert.That(versionColumns.Any(pair => pair.Field == simpleType.Fields["StructureField.ReferenceField.Id"]), Is.True); + Assert.That(versionColumns.Any(pair => pair.Field == simpleType.Fields["ByteArrayField"]), Is.False); } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/AscxTemplate.cs b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/AscxTemplate.cs index d6a984433d..a4ad3b5a3f 100644 --- a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/AscxTemplate.cs +++ b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/AscxTemplate.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.ObjectModel.Cms { - [Serializable] public class AscxTemplate : ContentItem { diff --git a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentDirectory.cs b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentDirectory.cs index c26a2cf85c..0dcc248bb2 100644 --- a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentDirectory.cs +++ b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentDirectory.cs @@ -9,8 +9,7 @@ using System.Text; namespace Xtensive.Orm.Tests.ObjectModel.Cms -{ - [Serializable] +{ [HierarchyRoot] public class ContentDirectory : Entity diff --git a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentDirectoryCollection.cs b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentDirectoryCollection.cs index c8e2ba3b38..296b015c6f 100644 --- a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentDirectoryCollection.cs +++ b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentDirectoryCollection.cs @@ -4,9 +4,8 @@ // Created by: Alex Ilyin // Created: 2009.09.03 -using System.Runtime.Serialization; -using Xtensive.Orm; -using FieldInfo=Xtensive.Orm.Model.FieldInfo; + +using FieldInfo = Xtensive.Orm.Model.FieldInfo; namespace Xtensive.Orm.Tests.ObjectModel.Cms { @@ -24,10 +23,5 @@ protected ContentDirectoryCollection(Entity owner, FieldInfo field) : base(owner, field) { } - - protected ContentDirectoryCollection(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentFile.cs b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentFile.cs index 8e7523c00b..6ad5020241 100644 --- a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentFile.cs +++ b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentFile.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.ObjectModel.Cms { - [Serializable] public class ContentFile : ContentItem { diff --git a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentItem.cs b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentItem.cs index 764b8e56b2..001654fbdd 100644 --- a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentItem.cs +++ b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentItem.cs @@ -9,7 +9,6 @@ namespace Xtensive.Orm.Tests.ObjectModel.Cms { - [Serializable] [HierarchyRoot] public class ContentItem : Entity diff --git a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentItemCollection.cs b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentItemCollection.cs index ada5f002be..21748a3f12 100644 --- a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentItemCollection.cs +++ b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentItemCollection.cs @@ -4,8 +4,6 @@ // Created by: Alex Ilyin // Created: 2009.09.02 -using System.Runtime.Serialization; -using Xtensive.Orm; using Xtensive.Orm.Model; namespace Xtensive.Orm.Tests.ObjectModel.Cms @@ -26,10 +24,5 @@ protected ContentItemCollection(Entity owner, FieldInfo field) : base(owner, field) { } - - protected ContentItemCollection(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentReference.cs b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentReference.cs index 3d1132a6d3..63b36b4164 100644 --- a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentReference.cs +++ b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/ContentReference.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.ObjectModel.Cms { - [Serializable] [HierarchyRoot] public class ContentReference : Entity diff --git a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/HtmlContentItem.cs b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/HtmlContentItem.cs index a84e2f9d02..7bc65f93b4 100644 --- a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/HtmlContentItem.cs +++ b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/HtmlContentItem.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.ObjectModel.Cms { - [Serializable] public abstract class HtmlContentItem : ContentItem { diff --git a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/Menu.cs b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/Menu.cs index 4b1163de35..61dfa7e7d4 100644 --- a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/Menu.cs +++ b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/Menu.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.ObjectModel.Cms { - [Serializable] public class Menu : ContentItem { diff --git a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/NewsDirectory.cs b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/NewsDirectory.cs index 7a153857d8..360a0039ba 100644 --- a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/NewsDirectory.cs +++ b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/NewsDirectory.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.ObjectModel.Cms { - [Serializable] public class NewsDirectory : ContentDirectory { diff --git a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/NewsList.cs b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/NewsList.cs index bff6bfd7fb..68a4fa25ab 100644 --- a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/NewsList.cs +++ b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/NewsList.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.ObjectModel.Cms { - [Serializable] public class NewsList : ContentItem { diff --git a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/NewsPage.cs b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/NewsPage.cs index 8eb7649536..1634dfded8 100644 --- a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/NewsPage.cs +++ b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/NewsPage.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.ObjectModel.Cms { - [Serializable] public class NewsPage : Page { diff --git a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/Page.cs b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/Page.cs index 524821150e..29ec455bbf 100644 --- a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/Page.cs +++ b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/Page.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.ObjectModel.Cms { - [Serializable] public class Page : HtmlContentItem { diff --git a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/PageTemplate.cs b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/PageTemplate.cs index f60ddcdaeb..c39b3658de 100644 --- a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/PageTemplate.cs +++ b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/PageTemplate.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.ObjectModel.Cms { - [Serializable] public class PageTemplate : HtmlContentItem { diff --git a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/WebSite.cs b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/WebSite.cs index 240f191472..ff89bdb279 100644 --- a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/WebSite.cs +++ b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/WebSite.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.ObjectModel.Cms { - [Serializable] public class WebSite : ContentDirectory { diff --git a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/WebSiteUrl.cs b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/WebSiteUrl.cs index 4963719b56..4adc53177e 100644 --- a/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/WebSiteUrl.cs +++ b/Orm/Xtensive.Orm.Tests/ObjectModel/Cms/WebSiteUrl.cs @@ -9,7 +9,6 @@ namespace Xtensive.Orm.Tests.ObjectModel.Cms { - [Serializable] [HierarchyRoot] public class WebSiteUrl : Entity diff --git a/Orm/Xtensive.Orm.Tests/ObjectModel/GenericModel.cs b/Orm/Xtensive.Orm.Tests/ObjectModel/GenericModel.cs index 63c4df96fd..ab6f43b56f 100644 --- a/Orm/Xtensive.Orm.Tests/ObjectModel/GenericModel.cs +++ b/Orm/Xtensive.Orm.Tests/ObjectModel/GenericModel.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.ObjectModel.GenericModel { - [Serializable] [HierarchyRoot] public class A : Entity where T : A @@ -17,13 +16,11 @@ public class A : Entity public T Generic { get; private set; } } - [Serializable] public class B : A { } - [Serializable] public class C : A where T : A { diff --git a/Orm/Xtensive.Orm.Tests/ObjectModel/Interfaces/Alphabet.cs b/Orm/Xtensive.Orm.Tests/ObjectModel/Interfaces/Alphabet.cs index 9179eb4146..1e5ab25e88 100644 --- a/Orm/Xtensive.Orm.Tests/ObjectModel/Interfaces/Alphabet.cs +++ b/Orm/Xtensive.Orm.Tests/ObjectModel/Interfaces/Alphabet.cs @@ -34,7 +34,6 @@ public interface IComposite : IEntity string Second { get; set; } } - [Serializable] [HierarchyRoot(InheritanceSchema.ClassTable)] public class A : Entity, INamed { @@ -43,20 +42,17 @@ public class A : Entity, INamed public string Name { get; set; } } - [Serializable] public class B : A, INamed, ITagged { string INamed.Name { get; set; } public string Tag { get; set; } } - [Serializable] public class C : A, ITagged { string ITagged.Tag { get; set; } } - [Serializable] public class D : B, INamed, IComposite { string INamed.Name { get; set; } @@ -64,13 +60,11 @@ public class D : B, INamed, IComposite public string Second { get; set;} } - [Serializable] public class E : D, IComposite { string IComposite.First { get; set; } } - [Serializable] [HierarchyRoot(InheritanceSchema.ConcreteTable)] public class F : Entity, INamed { @@ -79,20 +73,17 @@ public class F : Entity, INamed public string Name { get; set; } } - [Serializable] public class G : F, INamed, ITagged { string INamed.Name { get; set; } public string Tag { get; set; } } - [Serializable] public class H : F, ITagged { string ITagged.Tag { get; set; } } - [Serializable] public class I : G, INamed, IComposite { string INamed.Name { get; set; } @@ -100,13 +91,11 @@ public class I : G, INamed, IComposite public string Second { get; set; } } - [Serializable] public class J : I, IComposite { string IComposite.First { get; set; } } - [Serializable] [HierarchyRoot(InheritanceSchema.SingleTable)] public class K : Entity, INamed { @@ -115,20 +104,17 @@ public class K : Entity, INamed public string Name { get; set; } } - [Serializable] public class L : K, INamed, ITagged { string INamed.Name { get; set; } public string Tag { get; set; } } - [Serializable] public class M : K, ITagged { string ITagged.Tag { get; set; } } - [Serializable] public class N : L, INamed, IComposite { string INamed.Name { get; set; } @@ -136,13 +122,11 @@ public class N : L, INamed, IComposite public string Second { get; set; } } - [Serializable] public class O : N, IComposite { string IComposite.First { get; set; } } - [Serializable] [HierarchyRoot(InheritanceSchema.ClassTable)] [TypeDiscriminatorValue(0, Default = true)] public class P : Entity, INamed @@ -156,7 +140,6 @@ public class P : Entity, INamed public string Name { get; set; } } - [Serializable] [TypeDiscriminatorValue(1)] public class Q : P, INamed, ITagged { @@ -164,14 +147,12 @@ public class Q : P, INamed, ITagged public string Tag { get; set; } } - [Serializable] [TypeDiscriminatorValue(2)] public class R : P, ITagged { string ITagged.Tag { get; set; } } - [Serializable] [TypeDiscriminatorValue(3)] public class S : Q, INamed, IComposite { @@ -180,14 +161,12 @@ public class S : Q, INamed, IComposite public string Second { get; set; } } - [Serializable] [TypeDiscriminatorValue(4)] public class T : S, IComposite { string IComposite.First { get; set; } } - [Serializable] [HierarchyRoot(InheritanceSchema.SingleTable)] [TypeDiscriminatorValue(0, Default = true)] public class U : Entity, INamed @@ -201,7 +180,6 @@ public class U : Entity, INamed public string Name { get; set; } } - [Serializable] [TypeDiscriminatorValue(1)] public class V : U, INamed, ITagged { @@ -209,14 +187,12 @@ public class V : U, INamed, ITagged public string Tag { get; set; } } - [Serializable] [TypeDiscriminatorValue(2)] public class W : U, ITagged { string ITagged.Tag { get; set; } } - [Serializable] [TypeDiscriminatorValue(3)] public class X : V, INamed, IComposite { @@ -225,7 +201,6 @@ public class X : V, INamed, IComposite public string Second { get; set; } } - [Serializable] [TypeDiscriminatorValue(4)] public class Y : X, IComposite { diff --git a/Orm/Xtensive.Orm.Tests/ObjectModel/Interfaces/Slavery.cs b/Orm/Xtensive.Orm.Tests/ObjectModel/Interfaces/Slavery.cs index 21e7f2e907..49af210538 100644 --- a/Orm/Xtensive.Orm.Tests/ObjectModel/Interfaces/Slavery.cs +++ b/Orm/Xtensive.Orm.Tests/ObjectModel/Interfaces/Slavery.cs @@ -35,7 +35,6 @@ public interface IMaster : IMaster EntitySet XSlaves { get; } } - [Serializable] [HierarchyRoot] public class Slave : Entity, ISlave> { @@ -48,7 +47,6 @@ public class Slave : Entity, ISlave> } - [Serializable] [HierarchyRoot] public class Master : Entity, IMaster { diff --git a/Orm/Xtensive.Orm.Tests/Rse/IncludeProviderTest.cs b/Orm/Xtensive.Orm.Tests/Rse/IncludeProviderTest.cs index 307d41aac3..8ba4b1ed41 100644 --- a/Orm/Xtensive.Orm.Tests/Rse/IncludeProviderTest.cs +++ b/Orm/Xtensive.Orm.Tests/Rse/IncludeProviderTest.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Tests.Rse { - [Serializable] [TestFixture, Category("Rse")] public class IncludeProviderTest: ChinookDOModelTest { diff --git a/Orm/Xtensive.Orm.Tests/Storage/AbstractGenericsTest.cs b/Orm/Xtensive.Orm.Tests/Storage/AbstractGenericsTest.cs index 21f957f910..6682506d79 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/AbstractGenericsTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/AbstractGenericsTest.cs @@ -86,11 +86,11 @@ public void MediaTest() config.Types.Register(typeof(Track)); config.Types.Register(typeof(SimpleTrack)); config.Types.Register(typeof(ComplexTrack)); - var domain = Domain.Build(config); + using (var domain = Domain.Build(config)) using (var session = domain.OpenSession()) using (var t = session.OpenTransaction()) { - new SimpleTrack(TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(10), new SimpleMedia() {Description = "Simple", Foo = 23}); - new ComplexTrack(TimeSpan.FromMinutes(6), TimeSpan.FromMinutes(15), new ComplexMedia() {Description = "Simple", Bar = DateTime.Now}); + _ = new SimpleTrack(TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(10), new SimpleMedia() { Description = "Simple", Foo = 23 }); + _ = new ComplexTrack(TimeSpan.FromMinutes(6), TimeSpan.FromMinutes(15), new ComplexMedia() { Description = "Simple", Bar = DateTime.Now }); var listSimpleMedia = session.Query.All>().ToList(); var listComplexMedia = session.Query.All>().ToList(); Assert.That(listSimpleMedia.Count, Is.EqualTo(1)); diff --git a/Orm/Xtensive.Orm.Tests/Storage/ActivatorTest.cs b/Orm/Xtensive.Orm.Tests/Storage/ActivatorTest.cs index 7a67ba21da..2eaac4dca0 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/ActivatorTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/ActivatorTest.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Storage.ActivatorModel { - [Serializable] [HierarchyRoot] public abstract class Ancestor : Entity { @@ -21,14 +20,12 @@ public abstract class Ancestor : Entity public int ID { get; private set; } } - [Serializable] public class Descendant : Ancestor { [Field] public int Number { get; set; } } - [Serializable] [HierarchyRoot] public class InitializebleClass : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/AnotherValidationTest.cs b/Orm/Xtensive.Orm.Tests/Storage/AnotherValidationTest.cs index 41854024ca..a3ba3348f0 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/AnotherValidationTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/AnotherValidationTest.cs @@ -517,60 +517,62 @@ private Domain BuildDomain(bool isImmediate) [Test] public void ModelValidationTest() { - var domain = BuildDomain(false); - var passportType = domain.Model.Types[typeof (model1.Passport)]; + using (var domain = BuildDomain(false)) { + var passportType = domain.Model.Types[typeof(model1.Passport)]; - Assert.That(passportType.HasValidators, Is.EqualTo(true)); - Assert.That(passportType.Validators.Count, Is.EqualTo(0)); + Assert.That(passportType.HasValidators, Is.EqualTo(true)); + Assert.That(passportType.Validators.Count, Is.EqualTo(0)); - var passportTypeField = passportType.Fields["Number"]; - Assert.That(passportTypeField.HasValidators, Is.EqualTo(true)); - Assert.That(passportTypeField.Validators.Count, Is.EqualTo(2)); + var passportTypeField = passportType.Fields["Number"]; + Assert.That(passportTypeField.HasValidators, Is.EqualTo(true)); + Assert.That(passportTypeField.Validators.Count, Is.EqualTo(2)); - passportTypeField = passportType.Fields["Series"]; - Assert.That(passportTypeField.HasValidators, Is.EqualTo(true)); - Assert.That(passportTypeField.Validators.Count, Is.EqualTo(3)); + passportTypeField = passportType.Fields["Series"]; + Assert.That(passportTypeField.HasValidators, Is.EqualTo(true)); + Assert.That(passportTypeField.Validators.Count, Is.EqualTo(3)); - passportTypeField = passportType.Fields["Department"]; - Assert.That(passportTypeField.HasValidators, Is.EqualTo(true)); - Assert.That(passportTypeField.Validators.Count, Is.EqualTo(1)); + passportTypeField = passportType.Fields["Department"]; + Assert.That(passportTypeField.HasValidators, Is.EqualTo(true)); + Assert.That(passportTypeField.Validators.Count, Is.EqualTo(1)); - passportTypeField = passportType.Fields["DepartmentNumber"]; - Assert.That(passportTypeField.HasValidators, Is.EqualTo(true)); - Assert.That(passportTypeField.Validators.Count, Is.EqualTo(3)); + passportTypeField = passportType.Fields["DepartmentNumber"]; + Assert.That(passportTypeField.HasValidators, Is.EqualTo(true)); + Assert.That(passportTypeField.Validators.Count, Is.EqualTo(3)); - passportTypeField = passportType.Fields["DistributeDate"]; - Assert.That(passportTypeField.HasValidators, Is.EqualTo(true)); - Assert.That(passportTypeField.Validators.Count, Is.EqualTo(1)); + passportTypeField = passportType.Fields["DistributeDate"]; + Assert.That(passportTypeField.HasValidators, Is.EqualTo(true)); + Assert.That(passportTypeField.Validators.Count, Is.EqualTo(1)); + } - domain = BuildDomain(true); - var passportType1 = domain.Model.Types[typeof (model2.Passport)]; + using (var domain = BuildDomain(true)) { + var passportType1 = domain.Model.Types[typeof(model2.Passport)]; - passportTypeField = passportType1.Fields["Number"]; - Assert.That(passportTypeField.HasValidators, Is.EqualTo(true)); - Assert.That(passportTypeField.HasImmediateValidators, Is.EqualTo(true)); - Assert.That(passportTypeField.Validators.Count, Is.EqualTo(2)); + var passportTypeField = passportType1.Fields["Number"]; + Assert.That(passportTypeField.HasValidators, Is.EqualTo(true)); + Assert.That(passportTypeField.HasImmediateValidators, Is.EqualTo(true)); + Assert.That(passportTypeField.Validators.Count, Is.EqualTo(2)); - passportTypeField = passportType1.Fields["Series"]; - Assert.That(passportTypeField.HasImmediateValidators, Is.EqualTo(true)); - Assert.That(passportTypeField.HasValidators, Is.EqualTo(true)); - Assert.That(passportTypeField.Validators.Count, Is.EqualTo(3)); + passportTypeField = passportType1.Fields["Series"]; + Assert.That(passportTypeField.HasImmediateValidators, Is.EqualTo(true)); + Assert.That(passportTypeField.HasValidators, Is.EqualTo(true)); + Assert.That(passportTypeField.Validators.Count, Is.EqualTo(3)); - passportTypeField = passportType1.Fields["Department"]; - Assert.That(passportTypeField.HasImmediateValidators, Is.EqualTo(true)); - Assert.That(passportTypeField.HasValidators, Is.EqualTo(true)); - Assert.That(passportTypeField.Validators.Count, Is.EqualTo(1)); + passportTypeField = passportType1.Fields["Department"]; + Assert.That(passportTypeField.HasImmediateValidators, Is.EqualTo(true)); + Assert.That(passportTypeField.HasValidators, Is.EqualTo(true)); + Assert.That(passportTypeField.Validators.Count, Is.EqualTo(1)); - passportTypeField = passportType1.Fields["DepartmentNumber"]; - Assert.That(passportTypeField.HasImmediateValidators, Is.EqualTo(true)); - Assert.That(passportTypeField.HasValidators, Is.EqualTo(true)); - Assert.That(passportTypeField.Validators.Count, Is.EqualTo(3)); + passportTypeField = passportType1.Fields["DepartmentNumber"]; + Assert.That(passportTypeField.HasImmediateValidators, Is.EqualTo(true)); + Assert.That(passportTypeField.HasValidators, Is.EqualTo(true)); + Assert.That(passportTypeField.Validators.Count, Is.EqualTo(3)); - passportTypeField = passportType1.Fields["DistributeDate"]; - Assert.That(passportTypeField.HasImmediateValidators, Is.EqualTo(true)); - Assert.That(passportTypeField.HasValidators, Is.EqualTo(true)); - Assert.That(passportTypeField.Validators.Count, Is.EqualTo(1)); + passportTypeField = passportType1.Fields["DistributeDate"]; + Assert.That(passportTypeField.HasImmediateValidators, Is.EqualTo(true)); + Assert.That(passportTypeField.HasValidators, Is.EqualTo(true)); + Assert.That(passportTypeField.Validators.Count, Is.EqualTo(1)); + } } #endregion @@ -582,10 +584,10 @@ public void NotNullOrEmptyConstraintOnValidDataAdditionTest() using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { Assert.DoesNotThrow( - ()=> { - new model1.Measure {Name = "kilogramm", ShortName = "kg"}; - new model1.Measure {Name = "gramm", ShortName = "g"}; - new model1.Measure {Name = "liter"}; + () => { + _ = new model1.Measure {Name = "kilogramm", ShortName = "kg"}; + _ = new model1.Measure {Name = "gramm", ShortName = "g"}; + _ = new model1.Measure {Name = "liter"}; session.Validate(); }); } @@ -598,10 +600,10 @@ public void ImmediateNotNullOrEmptyConstraintOnValidDataAdditionTest() using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { Assert.DoesNotThrow( - ()=> { - new model2.Measure {Name = "kilogramm", ShortName = "kg"}; - new model2.Measure {Name = "gramm", ShortName = "g"}; - new model2.Measure {Name = "liter"}; + () => { + _ = new model2.Measure {Name = "kilogramm", ShortName = "kg"}; + _ = new model2.Measure {Name = "gramm", ShortName = "g"}; + _ = new model2.Measure {Name = "liter"}; }); } } @@ -612,8 +614,8 @@ public void NotNullOrEmptyConstraintOnNotValidDataAdditionTest() using (var domain = BuildDomain(false)) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws(() => { - new model1.Measure {Name = "", ShortName = "kg/m"}; + _ = Assert.Throws(() => { + _ = new model1.Measure {Name = "", ShortName = "kg/m"}; session.Validate(); }); } @@ -625,9 +627,9 @@ public void ImmediateNotNullOrEmptyConstraintOnNotValidDataAdditionTest() using (var domain = BuildDomain(true)) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { - new model2.Measure {Name = "", ShortName = "kg/m"}; + _ = new model2.Measure {Name = "", ShortName = "kg/m"}; }); } } @@ -640,7 +642,7 @@ public void NotNullConstraintOnValidDataAdditionTest() using (var transaction = session.OpenTransaction()) { Assert.DoesNotThrow(()=> { var measure = new model1.Measure {Name = "kilogramm", ShortName = "kg"}; - new model1.Product {Name = "Banana", Measure = measure}; + _ = new model1.Product {Name = "Banana", Measure = measure}; session.Validate(); }); } @@ -655,7 +657,7 @@ public void ImmediateNotNullConstraintOnValidDataAdditionTest() Assert.DoesNotThrow( () => { var measure = new model2.Measure {Name = "kilogramm", ShortName = "kg"}; - new model2.Product {Name = "Banana", Measure = measure}; + _ = new model2.Product {Name = "Banana", Measure = measure}; }); } } @@ -666,8 +668,8 @@ public void NotNullConstraintOnNotValidDataAdditionTest() using (var domain = BuildDomain(false)) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws(()=> { - new model1.Product {Name = "Banana"}; + _ = Assert.Throws(()=> { + _ = new model1.Product {Name = "Banana"}; session.Validate(); }); } @@ -679,9 +681,9 @@ public void ImmediateNotNullConstraintOnNotValidDataAdditionTest() using (var domain = BuildDomain(true)) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { - new model2.Product {Name = "Banana", Measure = null}; + _ = new model2.Product {Name = "Banana", Measure = null}; }); } } @@ -721,7 +723,7 @@ public void NotEmptyConstraintOnNotValidDataAdditionTest() using (var domain = BuildDomain(false)) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model1.Measure {Name = "kilogramm"}; var product = new model1.Product {Name = "", Measure = measure}; @@ -736,7 +738,7 @@ public void ImmediateNotEmptyConstraintOnNotValidDataAdditionTest() using (var domain = BuildDomain(true)) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model2.Measure {Name = "kilogramm"}; var product = new model2.Product {Name = "", Measure = measure}; @@ -754,7 +756,7 @@ public void RangeConstraintOnValidDataAdditionTest() () => { var measure = new model1.Measure {Name = "kilogramm"}; var product = new model1.Product {Name = "Banana", Measure = measure}; - new model1.Review {Product = product, Text = "Bananas is very tasty", Rating = 5}; + _ = new model1.Review {Product = product, Text = "Bananas is very tasty", Rating = 5}; session.Validate(); }); } @@ -770,7 +772,7 @@ public void ImmediateRangeConstraintOnValidDataAdditionTest() () => { var measure = new model2.Measure {Name = "kilogramm"}; var product = new model2.Product {Name = "Banana", Measure = measure}; - new model2.Review {Product = product, Text = "Bananas is very tasty", Rating = 5}; + _ = new model2.Review {Product = product, Text = "Bananas is very tasty", Rating = 5}; }); } } @@ -781,11 +783,11 @@ public void RangeConstraintOnNotValidDataAdditionTest() using (var domain = BuildDomain(false)) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model1.Measure {Name = "kilogramm"}; var product = new model1.Product {Name = "Banana", Measure = measure}; - new model1.Review {Product = product, Text = "Bananas is very tasty", Rating = 6}; + _ = new model1.Review {Product = product, Text = "Bananas is very tasty", Rating = 6}; session.Validate(); }); } @@ -797,11 +799,11 @@ public void ImmediateRangeConstraintOnNotValidDataAdditionTest() using (var domain = BuildDomain(true)) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model2.Measure {Name = "kilogramm"}; var product = new model2.Product {Name = "Banana", Measure = measure}; - new model2.Review {Product = product, Text = "Bananas is very tasty", Rating = 6}; + _ = new model2.Review {Product = product, Text = "Bananas is very tasty", Rating = 6}; }); } } @@ -841,7 +843,7 @@ public void LengthConstraintInStructureOnNotValidDataAdditionTest() using (var domain = BuildDomain(false)) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var passport = new model1.Passport {Number = "357867", Series = "223", Department = "\"Horns & Hooves\" Corp.", DepartmentNumber = "358-845", DistributeDate = new DateTime(2012, 12, 1)}; var customer = new model1.Customer {FirstName = "Alexey", LastName = "Kulakov", Birthday = new DateTime(2000, 3, 8), Passport = passport, Email = "login@domain.ru"}; @@ -870,7 +872,7 @@ public void LengthConstraintOnNotValidDataAdditionTest() using (var domain = BuildDomain(false)) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model1.Measure {Name = "kilogramm", ShortName = "kg"}; var product = new model1.Product {Name = "Banana", Measure = measure}; @@ -886,7 +888,7 @@ public void ImmediateLengthConstraintOnNotValidDataAdditionTest() using (var domain = BuildDomain(true)) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model2.Measure {Name = "kilogramm", ShortName = "kg"}; var product = new model2.Product {Name = "Banana", Measure = measure}; @@ -901,7 +903,7 @@ public void RegexConstraintInStructureOnNotValidData() using (var domain = BuildDomain(false)) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var passport = new model1.Passport {Number = "3578", Series = "2233", Department = "\"Horns & Hooves\" Corp.", DepartmentNumber = "358-845", DistributeDate = new DateTime(2012, 12, 1)}; var customer = new model1.Customer {FirstName = "Alexey", LastName = "Kulakov", Birthday = new DateTime(2000, 3, 8), Passport = passport, Email = "login@domain.ru"}; @@ -930,7 +932,7 @@ public void RegexConstraintOnNotValidData() using (var domain = BuildDomain(false)) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var passport = new model1.Passport {Number = "357878", Series = "2233", Department = "\"Horns & Hooves\" Corp.", DepartmentNumber = "358-845", DistributeDate = new DateTime(2012, 12, 1)}; var customer = new model1.Customer {FirstName = "Alexey", LastName = "Kulakov", Birthday = new DateTime(2000, 3, 8), Passport = passport, Email = "login@domain.ru", Phone = "878d8re7878"}; @@ -945,7 +947,7 @@ public void ImmediateRegexConstraintOnNotValidData() using (var domain = BuildDomain(true)) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var passport = new model2.Passport {Number = "878597", Series = "2233", Department = "\"Horns & Hooves\" Corp.", DepartmentNumber = "358-845", DistributeDate = new DateTime(2012, 12, 1)}; var customer = new model2.Customer {FirstName = "Alexey", LastName = "Kulakov", Birthday = new DateTime(2000, 3, 8), Passport = passport, Email = "login@domain.ru", Phone = "878d8re7878"}; @@ -961,11 +963,11 @@ public void EmailConstraintOnValidDataAdditionTest() using (var transaction = session.OpenTransaction()) { foreach (var email in validEmails) { Assert.DoesNotThrow( - ()=> { - var passport = new model1.Passport {Number = "898597", Series = "2233", Department = "\"Horns & Hooves\" Corp.", DepartmentNumber = "358-845", DistributeDate = new DateTime(2012, 12, 1)}; - var customer = new model1.Customer {FirstName = "Alexey", LastName = "Kulakov", Birthday = new DateTime(2000, 3, 8), Passport = passport, Email = email}; - session.Validate(); - }); + () => { + var passport = new model1.Passport { Number = "898597", Series = "2233", Department = "\"Horns & Hooves\" Corp.", DepartmentNumber = "358-845", DistributeDate = new DateTime(2012, 12, 1) }; + var customer = new model1.Customer { FirstName = "Alexey", LastName = "Kulakov", Birthday = new DateTime(2000, 3, 8), Passport = passport, Email = email }; + session.Validate(); + }); } } } @@ -978,10 +980,10 @@ public void ImmediateEmailConstraintOnValidDataAdditionTest() using (var transaction = session.OpenTransaction()) { foreach (var email in validEmails) { Assert.DoesNotThrow( - () => { - var passport = new model2.Passport {Number = "898597", Series = "2233", Department = "\"Horns & Hooves\" Corp.", DepartmentNumber = "358-845", DistributeDate = new DateTime(2012, 12, 1)}; - var customer = new model2.Customer {FirstName = "Alexey", LastName = "Kulakov", Birthday = new DateTime(2000, 3, 8), Passport = passport, Email = email}; - }); + () => { + var passport = new model2.Passport {Number = "898597", Series = "2233", Department = "\"Horns & Hooves\" Corp.", DepartmentNumber = "358-845", DistributeDate = new DateTime(2012, 12, 1)}; + var customer = new model2.Customer {FirstName = "Alexey", LastName = "Kulakov", Birthday = new DateTime(2000, 3, 8), Passport = passport, Email = email}; + }); } } } @@ -993,12 +995,12 @@ public void EmailConstraintOnNotValidDataAdditionTest() using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { foreach (var email in notValidEmails) { - Assert.Throws( - () => { - var passport = new model1.Passport {Number = "898597", Series = "2233", Department = "\"Horns & Hooves\" Corp.", DepartmentNumber = "358-845", DistributeDate = new DateTime(2012, 12, 1)}; - var customer = new model1.Customer {FirstName = "Alexey", LastName = "Kulakov", Birthday = new DateTime(2000, 3, 8), Passport = passport, Email = email}; - session.Validate(); - }); + _ = Assert.Throws( + () => { + var passport = new model1.Passport {Number = "898597", Series = "2233", Department = "\"Horns & Hooves\" Corp.", DepartmentNumber = "358-845", DistributeDate = new DateTime(2012, 12, 1)}; + var customer = new model1.Customer {FirstName = "Alexey", LastName = "Kulakov", Birthday = new DateTime(2000, 3, 8), Passport = passport, Email = email}; + session.Validate(); + }); } } } @@ -1010,11 +1012,11 @@ public void ImmediateEmailConstraintOnNotValidDataAdditionTest() using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { foreach (var email in notValidEmails) { - Assert.Throws( - () => { - var passport = new model2.Passport {Number = "898597", Series = "2233", Department = "\"Horns & Hooves\" Corp.", DepartmentNumber = "358-845", DistributeDate = new DateTime(2012, 12, 1)}; - var customer = new model2.Customer {FirstName = "Alexey", LastName = "Kulakov", Birthday = new DateTime(2000, 3, 8), Passport = passport, Email = email}; - }); + _ = Assert.Throws( + () => { + var passport = new model2.Passport {Number = "898597", Series = "2233", Department = "\"Horns & Hooves\" Corp.", DepartmentNumber = "358-845", DistributeDate = new DateTime(2012, 12, 1)}; + var customer = new model2.Customer {FirstName = "Alexey", LastName = "Kulakov", Birthday = new DateTime(2000, 3, 8), Passport = passport, Email = email}; + }); } } } @@ -1054,7 +1056,7 @@ public void PastConstraintInStructureOnNotValidDataAdditionTest() using (var domain = BuildDomain(false)) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var passport = new model1.Passport {Number = "898597", Series = "2233", Department = "\"Horns & Hooves\" Corp.", DepartmentNumber = "358-845", DistributeDate = DateTime.Now.AddSeconds(2)}; var customer = new model1.Customer {FirstName = "Alexey", LastName = "Kulakov", Birthday = new DateTime(2000, 3, 8), Passport = passport, Email = "login@domain.ru"}; @@ -1088,7 +1090,7 @@ public void PastConstraintOnValidDataAdditionTest() var product = new model1.Product { Name = "Banana", Measure = new model1.Measure { Name = "kilogramm" } }; var passport = new model1.Passport {Number = "898597", Series = "2233", Department = "\"Horns & Hooves\" Corp.", DepartmentNumber = "358-845", DistributeDate = DateTime.Now}; var customer = new model1.Customer {FirstName = "Alexey", LastName = "Kulakov", Birthday = new DateTime(2000, 3, 8), Passport = passport, Email = "login@domain.ru"}; - new model1.Order {Customer = customer, Product = product, Date = DateTime.Now, DeliveryIsOrdered = true, DeliveryDate = DateTime.Now.AddDays(1)}; + _ = new model1.Order {Customer = customer, Product = product, Date = DateTime.Now, DeliveryIsOrdered = true, DeliveryDate = DateTime.Now.AddDays(1)}; session.Validate(); }); } @@ -1105,7 +1107,7 @@ public void ImmediatePastConstraintOnValidDataAdditionTest() var product = new model2.Product {Name = "Banana", Measure = new model2.Measure {Name = "kilogramm"}}; var passport = new model2.Passport {Number = "898597", Series = "2233", Department = "\"Horns & Hooves\" Corp.", DepartmentNumber = "358-845", DistributeDate = DateTime.Now}; var customer = new model2.Customer {FirstName = "Alexey", LastName = "Kulakov", Birthday = new DateTime(2000, 3, 8), Passport = passport, Email = "login@domain.ru"}; - new model2.Order {Customer = customer, Product = product, Date = DateTime.Now, DeliveryIdOrdered = true, DeliveryDate = DateTime.Now.AddDays(1)}; + _ = new model2.Order {Customer = customer, Product = product, Date = DateTime.Now, DeliveryIdOrdered = true, DeliveryDate = DateTime.Now.AddDays(1)}; }); } } @@ -1116,12 +1118,12 @@ public void PastConstraintOnNotValidDataAdditionTest() using (var domain = BuildDomain(false)) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( ()=> { var product = new model1.Product {Name = "Banana", Measure = new model1.Measure {Name = "kilogramm"}}; var passport = new model1.Passport {Number = "898597", Series = "2233", Department = "\"Horns & Hooves\" Corp.", DepartmentNumber = "358-845", DistributeDate = DateTime.Now}; var customer = new model1.Customer {FirstName = "Alexey", LastName = "Kulakov", Birthday = new DateTime(2000, 3, 8), Passport = passport, Email = "login@domain.ru"}; - new model1.Order {Customer = customer, Product = product, Date = DateTime.Now.AddMinutes(2), DeliveryIsOrdered = true, DeliveryDate = DateTime.Now.AddDays(1)}; + _ = new model1.Order {Customer = customer, Product = product, Date = DateTime.Now.AddMinutes(2), DeliveryIsOrdered = true, DeliveryDate = DateTime.Now.AddDays(1)}; session.Validate(); }); } @@ -1133,12 +1135,12 @@ public void ImmediatePastConstraintOnNotValidDataAdditionTest() using (var domain = BuildDomain(true)) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var product = new model2.Product {Name = "Banana", Measure = new model2.Measure {Name = "kilogramm"}}; var passport = new model2.Passport {Number = "898597", Series = "2233", Department = "\"Horns & Hooves\" Corp.", DepartmentNumber = "358-845", DistributeDate = DateTime.Now}; var customer = new model2.Customer {FirstName = "Alexey", LastName = "Kulakov", Birthday = new DateTime(2000, 3, 8), Passport = passport, Email = "login@domain.ru"}; - new model2.Order {Customer = customer, Product = product, Date = DateTime.Now.AddMinutes(2), DeliveryIdOrdered = true, DeliveryDate = DateTime.Now.AddDays(1)}; + _ = new model2.Order {Customer = customer, Product = product, Date = DateTime.Now.AddMinutes(2), DeliveryIdOrdered = true, DeliveryDate = DateTime.Now.AddDays(1)}; }); } } @@ -1154,7 +1156,7 @@ public void FutureConstraintOnValidDataAdditionTest() var product = new model1.Product {Name = "Banana", Measure = new model1.Measure {Name = "kilogramm"}}; var passport = new model1.Passport {Number = "898597", Series = "2233", Department = "\"Horns & Hooves\" Corp.", DepartmentNumber = "358-845", DistributeDate = DateTime.Now}; var customer = new model1.Customer {FirstName = "Alexey", LastName = "Kulakov", Birthday = new DateTime(2000, 3, 8), Passport = passport, Email = "login@domain.ru"}; - new model1.Order {Customer = customer, Product = product, Date = DateTime.Now, DeliveryIsOrdered = true, DeliveryDate = DateTime.Now.AddDays(1)}; + _ = new model1.Order {Customer = customer, Product = product, Date = DateTime.Now, DeliveryIsOrdered = true, DeliveryDate = DateTime.Now.AddDays(1)}; session.Validate(); }); } @@ -1171,7 +1173,7 @@ public void ImmediateFutureConstraintOnValidDataAdditionTest() var product = new model2.Product {Name = "Banana", Measure = new model2.Measure {Name = "kilogramm"}}; var passport = new model2.Passport {Number = "898597", Series = "2233", Department = "\"Horns & Hooves\" Corp.", DepartmentNumber = "358-845", DistributeDate = DateTime.Now}; var customer = new model2.Customer {FirstName = "Alexey", LastName = "Kulakov", Birthday = new DateTime(2000, 3, 8), Passport = passport, Email = "login@domain.ru"}; - new model2.Order {Customer = customer, Product = product, Date = DateTime.Now, DeliveryIdOrdered = true, DeliveryDate = DateTime.Now.AddDays(1)}; + _ = new model2.Order {Customer = customer, Product = product, Date = DateTime.Now, DeliveryIdOrdered = true, DeliveryDate = DateTime.Now.AddDays(1)}; }); } } @@ -1182,12 +1184,12 @@ public void FutureConstraintOnNotValidDataAdditionTest() using (var domain = BuildDomain(false)) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var product = new model1.Product {Name = "Banana", Measure = new model1.Measure {Name = "kilogramm"}}; var passport = new model1.Passport {Number = "898597", Series = "2233", Department = "\"Horns & Hooves\" Corp.", DepartmentNumber = "358-845", DistributeDate = DateTime.Now}; var customer = new model1.Customer {FirstName = "Alexey", LastName = "Kulakov", Birthday = new DateTime(2000, 3, 8), Passport = passport, Email = "login@domain.ru"}; - new model1.Order {Customer = customer, Product = product, Date = DateTime.Now, DeliveryIsOrdered = true, DeliveryDate = DateTime.Now}; + _ = new model1.Order {Customer = customer, Product = product, Date = DateTime.Now, DeliveryIsOrdered = true, DeliveryDate = DateTime.Now}; session.Validate(); }); } @@ -1199,12 +1201,12 @@ public void ImmediateFutureConstraintOnNotValidDataAdditionTest() using (var domain = BuildDomain(true)) using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var product = new model2.Product {Name = "Banana", Measure = new model2.Measure {Name = "kilogramm"}}; var passport = new model2.Passport {Number = "898597", Series = "2233", Department = "\"Horns & Hooves\" Corp.", DepartmentNumber = "358-845", DistributeDate = DateTime.Now}; var customer = new model2.Customer {FirstName = "Alexey", LastName = "Kulakov", Birthday = new DateTime(2000, 3, 8), Passport = passport, Email = "login@domain.ru"}; - new model2.Order {Customer = customer, Product = product, Date = DateTime.Now, DeliveryIdOrdered = true, DeliveryDate = DateTime.Now}; + _ = new model2.Order {Customer = customer, Product = product, Date = DateTime.Now, DeliveryIdOrdered = true, DeliveryDate = DateTime.Now}; session.Validate(); }); } @@ -1271,7 +1273,7 @@ public void InheritedFieldsConstraintsOnNotValidDataAdditionTest() using (var domain = BuildDomain(false)) using (var session = domain.OpenSession()) { using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model1.Measure { Name = "measure", @@ -1292,7 +1294,7 @@ public void InheritedFieldsConstraintsOnNotValidDataAdditionTest() }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model1.Measure { Name = "measure", @@ -1313,7 +1315,7 @@ public void InheritedFieldsConstraintsOnNotValidDataAdditionTest() }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model1.Measure { Name = "measure", @@ -1334,7 +1336,7 @@ public void InheritedFieldsConstraintsOnNotValidDataAdditionTest() }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model1.Measure { Name = "measure", @@ -1355,7 +1357,7 @@ public void InheritedFieldsConstraintsOnNotValidDataAdditionTest() }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model1.Measure { Name = "measure", @@ -1376,7 +1378,7 @@ public void InheritedFieldsConstraintsOnNotValidDataAdditionTest() }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model1.Measure { Name = "measure", @@ -1397,7 +1399,7 @@ public void InheritedFieldsConstraintsOnNotValidDataAdditionTest() }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model1.Measure { Name = "measure", @@ -1418,7 +1420,7 @@ public void InheritedFieldsConstraintsOnNotValidDataAdditionTest() }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model1.Measure { Name = "measure", @@ -1439,7 +1441,7 @@ public void InheritedFieldsConstraintsOnNotValidDataAdditionTest() }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model1.Measure { Name = "measure", @@ -1468,7 +1470,7 @@ public void ImmediateInheritedFieldsConstraintsOnNotValidDataAdditionTest() using (var domain = BuildDomain(true)) using (var session = domain.OpenSession()) { using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model2.Measure { Name = "measure", @@ -1488,7 +1490,7 @@ public void ImmediateInheritedFieldsConstraintsOnNotValidDataAdditionTest() }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model2.Measure { Name = "measure", @@ -1508,7 +1510,7 @@ public void ImmediateInheritedFieldsConstraintsOnNotValidDataAdditionTest() }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model2.Measure { Name = "measure", @@ -1528,7 +1530,7 @@ public void ImmediateInheritedFieldsConstraintsOnNotValidDataAdditionTest() }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model2.Measure { Name = "measure", @@ -1548,7 +1550,7 @@ public void ImmediateInheritedFieldsConstraintsOnNotValidDataAdditionTest() }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model2.Measure { Name = "measure", @@ -1568,7 +1570,7 @@ public void ImmediateInheritedFieldsConstraintsOnNotValidDataAdditionTest() }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model2.Measure { Name = "measure", @@ -1588,7 +1590,7 @@ public void ImmediateInheritedFieldsConstraintsOnNotValidDataAdditionTest() }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model2.Measure { Name = "measure", @@ -1608,7 +1610,7 @@ public void ImmediateInheritedFieldsConstraintsOnNotValidDataAdditionTest() }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model2.Measure { Name = "measure", @@ -1628,7 +1630,7 @@ public void ImmediateInheritedFieldsConstraintsOnNotValidDataAdditionTest() }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model2.Measure { Name = "measure", @@ -1656,7 +1658,7 @@ public void OverridedFieldConsraintAdditionTest() using (var domain = BuildDomain(false)) using (var session = domain.OpenSession()) { using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model1.Measure { Name = "measure", @@ -1706,7 +1708,7 @@ public void ImmediateOverridedFieldConsraintAdditionTest() using (var domain = BuildDomain(true)) using (var session = domain.OpenSession()) { using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { var measure = new model2.Measure { Name = "measure", @@ -1900,12 +1902,12 @@ public void NotNullOrEmptyConstraintOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { measure.Name = ""; session.Validate(); }); - Assert.Throws( + _ = Assert.Throws( () => { measure.Name = null; session.Validate(); @@ -1925,11 +1927,11 @@ public void ImmediateNotNullOrEmptyConstraintOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { measure.Name = ""; }); - Assert.Throws( + _ = Assert.Throws( () => { measure.Name = null; }); @@ -1989,7 +1991,7 @@ public void NotNullConstraintOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { product.Measure = null; session.Validate(); @@ -2009,7 +2011,7 @@ public void ImmediateNotNullConstraintOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { product.Measure = null; }); @@ -2029,7 +2031,7 @@ public void NotEmptyConstraintOnValidDataChangingTest() } using (var transaction = session.OpenTransaction()) { Assert.DoesNotThrow( - ()=> { + () => { product.Name = "Orange"; session.Validate(); }); @@ -2049,7 +2051,7 @@ public void ImmediateNotEmptyConstraintOnValidDataChangingTest() } using (var transaction = session.OpenTransaction()) { Assert.DoesNotThrow( - ()=> { + () => { product.Name = "Orange"; }); } @@ -2067,7 +2069,7 @@ public void NotEmptyConstraintOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { product.Name = ""; session.Validate(); @@ -2087,7 +2089,7 @@ public void ImmediateNotEmptyConstraintOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { product.Name = ""; }); @@ -2107,7 +2109,7 @@ public void RangeConstraintOnValidDataChangingTest() } using (var transaction = session.OpenTransaction()) { Assert.DoesNotThrow( - ()=> { + () => { review.Rating = 2; session.Validate(); }); @@ -2127,7 +2129,7 @@ public void ImmediateRangeConstraintOnValidDataChangingTest() } using (var transaction = session.OpenTransaction()) { Assert.DoesNotThrow( - ()=> { + () => { review.Rating = 2; }); } @@ -2145,7 +2147,7 @@ public void RangeConstraintOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { review.Rating = 6; session.Validate(); @@ -2165,7 +2167,7 @@ public void ImmediateRangeConstraintOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { review.Rating = 6; }); @@ -2185,7 +2187,7 @@ public void LengthAndRegexConstraintOnValidDataChangingTest() } using (var transaction = session.OpenTransaction()) { Assert.DoesNotThrow( - ()=> { + () => { customer.Passport.Series = "6743"; customer.Passport.Number = "868764"; session.Validate(); @@ -2207,7 +2209,7 @@ public void ImmediateLengthAndRegexConstraintOnValidDataChangingTest() } using (var transaction = session.OpenTransaction()) { Assert.DoesNotThrow( - ()=> { + () => { customer.Passport.Series = "7643"; customer.Passport.Number = "797834"; }); @@ -2226,8 +2228,8 @@ public void LengthConstraintInStructureOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( - ()=> { + _ = Assert.Throws( + () => { customer.Passport.Series = "674"; customer.Passport.Number = "868764"; session.Validate(); @@ -2248,8 +2250,8 @@ public void ImmediateLengthConstraintInStructureOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( - ()=> { + _ = Assert.Throws( + () => { customer.Passport.Series = "764"; customer.Passport.Number = "797834"; }); @@ -2268,7 +2270,7 @@ public void LengthConstraingOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { review.Text = "5"; session.Validate(); @@ -2288,7 +2290,7 @@ public void ImmediateLengthConstraingOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { review.Text = "5"; }); @@ -2307,13 +2309,13 @@ public void RegexConstraintInStructureOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { customer.Passport.Series = "6748"; customer.Passport.Number = "8687"; session.Validate(); }); - Assert.Throws( + _ = Assert.Throws( () => { customer.Passport.Series = "6748"; customer.Passport.Number = "8687av"; @@ -2334,12 +2336,12 @@ public void ImmediateRegexConstraintInStructureOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { customer.Passport.Series = "7648"; customer.Passport.Number = "7978"; }); - Assert.Throws( + _ = Assert.Throws( () => { customer.Passport.Series = "7648"; customer.Passport.Number = "7978av"; @@ -2359,7 +2361,7 @@ public void RegexConstraintOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { customer.Phone = "88dfg78dfg"; session.Validate(); @@ -2380,7 +2382,7 @@ public void ImmediateRegexConstraintOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { customer.Phone = "88dfg78dfg"; }); @@ -2443,7 +2445,7 @@ public void EmailConstraintOnNotValidDataChangingData() } using (var transaction = session.OpenTransaction()) { foreach (var email in notValidEmails) { - Assert.Throws( + _ = Assert.Throws( () => { customer.Email = email; session.Validate(); @@ -2465,7 +2467,7 @@ public void ImmediateEmailConstraintOnNotValidDataChangingData() } using (var transaction = session.OpenTransaction()) { foreach (var email in notValidEmails) { - Assert.Throws( + _ = Assert.Throws( () => { customer.Email = email; }); @@ -2524,7 +2526,7 @@ public void PastConstraintInStructureOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { customer.Passport.DistributeDate = DateTime.Now.AddSeconds(2); session.Validate(); @@ -2545,7 +2547,7 @@ public void ImmediatePastConstraintInStructureOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { customer.Passport.DistributeDate = DateTime.Now.AddSeconds(2); }); @@ -2604,7 +2606,7 @@ public void PastConstraintOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { order.Date = DateTime.Now.AddSeconds(2); session.Validate(); @@ -2625,7 +2627,7 @@ public void ImmediatePastConstraintOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { order.Date = DateTime.Now.AddSeconds(2); }); @@ -2683,7 +2685,7 @@ public void FutureConstraintOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { order.DeliveryDate = DateTime.Now; session.Validate(); @@ -2703,7 +2705,7 @@ public void ImmediateFutureConstraintOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { order.DeliveryDate = DateTime.Now; }); @@ -2779,63 +2781,63 @@ public void InheritedFieldsConstraintsOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { childClass.NotEmptyString = ""; session.Validate(); }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { childClass.NotNullOrEmptyString = ""; session.Validate(); }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { childClass.NotNullOrEmptyString = null; session.Validate(); }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { childClass.NotNullString = null; session.Validate(); }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { childClass.FutureDateTime = DateTime.Now; session.Validate(); }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { childClass.IntValueInRange = 11; session.Validate(); }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { childClass.PastDateTime = DateTime.Now.AddSeconds(2); session.Validate(); }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { childClass.StringForRegexValidation = "%&%%"; session.Validate(); }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { childClass.LimitedLengthString = "uuuuujhgdfhjdfhgjfdhgfjdhghfg"; session.Validate(); @@ -2855,55 +2857,55 @@ public void ImmediateInheritedFieldsConstraintsOnNotValidDataChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { childClass.NotEmptyString = ""; }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { childClass.NotNullOrEmptyString = ""; }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { childClass.NotNullOrEmptyString = null; }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { childClass.NotNullString = null; }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { childClass.FutureDateTime = DateTime.Now; }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { childClass.IntValueInRange = 11; }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { childClass.PastDateTime = DateTime.Now.AddSeconds(2); }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { childClass.StringForRegexValidation = "%&%%"; }); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { childClass.LimitedLengthString = "uuuuujhgdfhjdfhgjfdhgfjdhghfg"; }); @@ -2924,7 +2926,7 @@ public void OverridedFieldConsraintChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { childClass.OverridedField = ""; session.Validate(); @@ -2953,7 +2955,7 @@ public void ImmediateOverridedFieldConsraintChangingTest() transaction.Complete(); } using (var transaction = session.OpenTransaction()) { - Assert.Throws( + _ = Assert.Throws( () => { childClass.OverridedField = ""; }); diff --git a/Orm/Xtensive.Orm.Tests/Storage/BatchingTest.cs b/Orm/Xtensive.Orm.Tests/Storage/BatchingTest.cs index 8903628ec5..46c743c196 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/BatchingTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/BatchingTest.cs @@ -54,7 +54,6 @@ private void DbCommandExecutedHandler(object sender, DbCommandEventArgs e) namespace Xtensive.Orm.Tests.Storage { - [Serializable] public class BatchingTest : AutoBuildTest { private const int TotalEntities = 10; diff --git a/Orm/Xtensive.Orm.Tests/Storage/ClusteredIndexesTest.cs b/Orm/Xtensive.Orm.Tests/Storage/ClusteredIndexesTest.cs index 2556e2da36..417e4f63f2 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/ClusteredIndexesTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/ClusteredIndexesTest.cs @@ -9,8 +9,6 @@ using System.Linq; using System.Linq.Expressions; using NUnit.Framework; -//using Xtensive.Core; -using Xtensive.Orm.Tests; using Xtensive.Sql.Model; using Xtensive.Orm.Configuration; using Xtensive.Orm.Model; @@ -360,7 +358,9 @@ private void BuildDomain(DomainUpgradeMode upgradeMode) foreach (var type in domainTypes) config.Types.Register(type); - config.Types.RegisterCaching(typeof (SingleTableSchemaModifier).Assembly, typeof (SingleTableSchemaModifier).Namespace); + config.Types.Register(typeof(SingleTableSchemaModifier)); + config.Types.Register(typeof(ConcreteTableSchemaModifier)); + config.Types.Register(typeof(ClassTableSchemaModifier)); config.UpgradeMode = upgradeMode; if (inheritanceSchema!=null) @@ -380,7 +380,8 @@ private void InitializeTest(InheritanceSchema? schema, IEnumerable types) private void RunFailureTest(Type badType) { - InitializeTest(null, new[] {badType}); + InitializeTest(null, new[] { badType }); + AssertEx.Throws(() => BuildDomain(DomainUpgradeMode.Recreate)); } diff --git a/Orm/Xtensive.Orm.Tests/Storage/CompiledQueryTest.cs b/Orm/Xtensive.Orm.Tests/Storage/CompiledQueryTest.cs index f0a360db45..cd652c52a4 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/CompiledQueryTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/CompiledQueryTest.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Storage { - [Serializable] public class CompiledQueryTest : ChinookDOModelTest { [Test] diff --git a/Orm/Xtensive.Orm.Tests/Storage/ConnectionAccessorTest.cs b/Orm/Xtensive.Orm.Tests/Storage/ConnectionAccessorTest.cs index 41d42876ba..e99915a554 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/ConnectionAccessorTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/ConnectionAccessorTest.cs @@ -8,7 +8,6 @@ using System.Linq; using System.Text; using NUnit.Framework; -using Xtensive.Core; using Xtensive.Orm.Providers; using Xtensive.Sql; using Xtensive.Orm.Tests.Storage.ConnectionAccessorsModel; @@ -153,9 +152,7 @@ public void NoDefaultConstructorTest() domainConfig.Types.Register(typeof(DummyEntity)); domainConfig.Types.Register(typeof(NoDefaultConstructorAccessor)); - Domain domain = null; - _ = Assert.Throws(() => domain = Domain.Build(domainConfig)); - domain.DisposeSafely(); + _ = Assert.Throws(() => Domain.Build(domainConfig).Dispose()); } [Test] @@ -166,9 +163,7 @@ public void NoDefaultConstructorAsyncTest() domainConfig.Types.Register(typeof(DummyEntity)); domainConfig.Types.Register(typeof(NoDefaultConstructorAccessor)); - Domain domain = null; - _ = Assert.ThrowsAsync(async () => domain = await Domain.BuildAsync(domainConfig)); - domain.DisposeSafely(); + _ = Assert.ThrowsAsync(async () => (await Domain.BuildAsync(domainConfig)).Dispose()); } [Test] diff --git a/Orm/Xtensive.Orm.Tests/Storage/CoreServicesTest.cs b/Orm/Xtensive.Orm.Tests/Storage/CoreServicesTest.cs index 3b6544632e..ef730c2cf3 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/CoreServicesTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/CoreServicesTest.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Storage.CoreServicesModel { - [Serializable] [HierarchyRoot] public class MyEntity : Entity { @@ -90,7 +89,6 @@ public MyEntity() } } - [Serializable] public class MyStructure : Structure { [Field] diff --git a/Orm/Xtensive.Orm.Tests/Storage/CustomEntitySetTest.cs b/Orm/Xtensive.Orm.Tests/Storage/CustomEntitySetTest.cs index 6838124db0..0bea858621 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/CustomEntitySetTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/CustomEntitySetTest.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Storage.CustomEntitySetModel { - [Serializable] [HierarchyRoot] public class Root : Entity { @@ -19,7 +18,6 @@ public class Root : Entity public int Id { get; private set; } } - [Serializable] public class Master : Root { [Field] @@ -32,7 +30,6 @@ public class Master : Root public CustomEntitySet ManyToMany { get; private set; } } - [Serializable] public class Slave : Root { [Field, Association(PairTo = "OneToMany")] diff --git a/Orm/Xtensive.Orm.Tests/Storage/DataErrorInfo.cs b/Orm/Xtensive.Orm.Tests/Storage/DataErrorInfo.cs index dcb8719a26..85e01f7f0b 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/DataErrorInfo.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/DataErrorInfo.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Storage.DataErrorInfoTestModel { - [Serializable] [HierarchyRoot] public class Person : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/DisableSaveChangesTest.cs b/Orm/Xtensive.Orm.Tests/Storage/DisableSaveChangesTest.cs index 7cff20b1c4..00019589aa 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/DisableSaveChangesTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/DisableSaveChangesTest.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Storage.DisableSaveChangesTestModel { - [Serializable] [HierarchyRoot] public class Killer : Entity { @@ -34,7 +33,6 @@ public void Kill(Victim victim) } } - [Serializable] [HierarchyRoot] public class Victim : Entity { @@ -63,7 +61,6 @@ public void Resurrect() } } - [Serializable] [HierarchyRoot] public class Node : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/EntitySetTest.cs b/Orm/Xtensive.Orm.Tests/Storage/EntitySetTest.cs index a3192b43bb..f32d23dec5 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/EntitySetTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/EntitySetTest.cs @@ -28,7 +28,6 @@ public class Publisher : Entity public EntitySet Books { get; private set; } } - [Serializable] [HierarchyRoot] public class Book : Entity { @@ -42,7 +41,6 @@ public class Book : Entity public Author Author { get; private set; } } - [Serializable] [HierarchyRoot] public class Author : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/FieldDefaultValueTest.cs b/Orm/Xtensive.Orm.Tests/Storage/FieldDefaultValueTest.cs index 1ff52eaed2..a2bc12aab5 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/FieldDefaultValueTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/FieldDefaultValueTest.cs @@ -97,7 +97,6 @@ public EnumKeyEntity(OneTwo id) {} } - [Serializable] [HierarchyRoot] public class X : Entity { @@ -270,7 +269,6 @@ public class X : Entity } [HierarchyRoot] - [Serializable] public class Y : Entity { [Field, Key] @@ -281,7 +279,6 @@ public class Y : Entity } [HierarchyRoot] - [Serializable] public class Z : Entity { [Field, Key] @@ -300,16 +297,29 @@ namespace Xtensive.Orm.Tests.Storage [TestFixture] public class FieldDefaultValueTest : AutoBuildTest { + private bool supportsDefaultForArrays = false; + private bool supportsDefaultForLongString = false; + + public override void TestFixtureSetUp() + { + (supportsDefaultForArrays, supportsDefaultForLongString) = StorageProviderInfo.Instance.Provider switch { + StorageProvider.Firebird => (false, true), + StorageProvider.MySql => (false, false), + _ => (true, true) + }; + base.TestFixtureSetUp(); + } + protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); config.Types.Register(typeof(XRef)); config.Types.Register(typeof(EnumKeyEntity)); config.Types.Register(typeof(X)); - if (SupportsDefaultForLongString()) { + if (supportsDefaultForLongString) { config.Types.Register(typeof(Y)); } - if (SupportsDefaultForArrays()) { + if (supportsDefaultForArrays) { config.Types.Register(typeof(Z)); } return config; @@ -328,11 +338,11 @@ public void DefaultValuesTest() _ = new EnumKeyEntity(CodeRegistry.EnumKeyValue); keyX = new X().Key; - if (SupportsDefaultForLongString()) { + if (supportsDefaultForLongString) { keyY = new Y().Key; } - if(SupportsDefaultForArrays()) { + if(supportsDefaultForArrays) { keyZ = new Z().Key; } t.Complete(); @@ -399,11 +409,11 @@ public void DefaultValuesTest() Assert.That(x.Ref, Is.Not.Null); Assert.That(x.EnumKeyEntityRef, Is.Not.Null); - if (SupportsDefaultForLongString()) { + if (supportsDefaultForLongString) { var y = session.Query.SingleOrDefault(keyY); Assert.That(y.FLongString, Is.EqualTo("default value")); } - if (SupportsDefaultForArrays()) { + if (supportsDefaultForArrays) { var z = session.Query.SingleOrDefault(keyZ); Assert.That(z.FByteArray, Is.EqualTo(new byte[] { 10, 10, 10, 10 })); Assert.That(z.FLongByteArray, Is.EqualTo(new byte[] { 10, 10, 10, 10 })); @@ -420,30 +430,13 @@ public void ValidateTest() var configuration = BuildConfiguration(); configuration.UpgradeMode = DomainUpgradeMode.Validate; configuration.Types.Register(typeof(X)); - if (SupportsDefaultForLongString()) { + if (supportsDefaultForLongString) { configuration.Types.Register(typeof(Y)); } - if (SupportsDefaultForArrays()) { + if (supportsDefaultForArrays) { configuration.Types.Register(typeof(Z)); } - var domain = Domain.Build(configuration); - domain.Dispose(); - } - - private bool SupportsDefaultForArrays() - { - switch (StorageProviderInfo.Instance.Provider) { - case StorageProvider.Firebird: - case StorageProvider.MySql: - return false; - default: - return true; - } - } - - private bool SupportsDefaultForLongString() - { - return StorageProviderInfo.Instance.Provider != StorageProvider.MySql; + using var domain = Domain.Build(configuration); } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Storage/FieldSqlDefaultTest.cs b/Orm/Xtensive.Orm.Tests/Storage/FieldSqlDefaultTest.cs index d11bfb6ba1..e39fdf4ec7 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/FieldSqlDefaultTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/FieldSqlDefaultTest.cs @@ -10,19 +10,20 @@ using Xtensive.Orm.Building; using Xtensive.Orm.Building.Definitions; using Xtensive.Orm.Configuration; +using Xtensive.Orm.Services; using Xtensive.Orm.Tests.Storage.FieldSqlDefaultTestModel; namespace Xtensive.Orm.Tests.Storage.FieldSqlDefaultTestModel { [HierarchyRoot] - public class TestEntity1 : Entity + public class ExtendedTypesEntity : Entity { [Field (DefaultSqlExpression = "newid()"), Key] public Guid Id { get; private set; } } [HierarchyRoot] - public class TestEntity : Entity + public class GeneralTypesEntity : Entity { [Field (DefaultSqlExpression = "1"), Key] public int Id { get; private set; } @@ -79,7 +80,7 @@ public void OnDefinitionsBuilt(BuildingContext context, DomainModelDef model) return; } - var field = model.Types[nameof(TestEntity)].Fields[nameof(TestEntity.FDateTime)]; + var field = model.Types[nameof(GeneralTypesEntity)].Fields[nameof(GeneralTypesEntity.FDateTime)]; field.DefaultValue = FormatDate(new DateTime(2012, 12, 12)); field.DefaultSqlExpression = $"'{FormatDate(new DateTime(2013, 12, 13))}'"; } @@ -93,28 +94,47 @@ namespace Xtensive.Orm.Tests.Storage [TestFixture] public class FieldSqlDefaultTest : AutoBuildTest { - [Test] - public void MainTest() + protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); configuration.UpgradeMode = DomainUpgradeMode.Recreate; - configuration.Types.Register(typeof(TestEntity)); - configuration.Types.Register(typeof(OracleDefaultValueModifier)); - Domain = Domain.Build(configuration); + configuration.Types.Register(typeof(GeneralTypesEntity)); + var storageInfo = StorageProviderInfo.Instance; + if (storageInfo.CheckProviderIs(StorageProvider.Oracle)) { + configuration.Types.Register(typeof(OracleDefaultValueModifier)); + } + if(storageInfo.CheckProviderIs(StorageProvider.SqlServer)) { + configuration.Types.Register(typeof(ExtendedTypesEntity)); + } + return configuration; + } + protected override void PopulateData() + { var driver = TestSqlDriver.Create(Domain.Configuration.ConnectionInfo); using (var connection = driver.CreateConnection()) { - connection.Open(); - var command = connection.CreateCommand(); var translator = driver.Translator; - command.CommandText = $"INSERT INTO {translator.QuoteIdentifier("TestEntity")}({translator.QuoteIdentifier("Id")}) values(1)"; - _ = command.ExecuteNonQuery(); + connection.Open(); + using (var command = connection.CreateCommand()) { + command.CommandText = $"INSERT INTO {translator.QuoteIdentifier("GeneralTypesEntity")}({translator.QuoteIdentifier("Id")}) values(1)"; + _ = command.ExecuteNonQuery(); + } + if (StorageProviderInfo.Instance.CheckProviderIs(StorageProvider.SqlServer)) { + using (var command = connection.CreateCommand()) { + command.CommandText = "INSERT INTO [ExtendedTypesEntity] DEFAULT VALUES;"; + _ = command.ExecuteNonQuery(); + } + } connection.Close(); } + } + [Test] + public void MainTest() + { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().First(); + var entity = session.Query.All().First(); Assert.That(entity.Id, Is.EqualTo(1)); Assert.That(entity.FByte, Is.EqualTo(64)); Assert.That(entity.FSByte, Is.EqualTo(65)); @@ -137,24 +157,10 @@ public void MainTest() public void DefaultValueTestForKeyFieldTest() { Require.ProviderIs(StorageProvider.SqlServer); - var configuration = base.BuildConfiguration(); - configuration.UpgradeMode = DomainUpgradeMode.Recreate; - configuration.Types.Register(typeof (TestEntity1)); - Domain = Domain.Build(configuration); - var driver = TestSqlDriver.Create(Domain.Configuration.ConnectionInfo); - using (var connection = driver.CreateConnection()) { - connection.Open(); - var command = connection.CreateCommand(); - var translator = driver.Translator; - command.CommandText = $"INSERT INTO {translator.QuoteIdentifier("TestEntity1")} DEFAULT VALUES;"; - _ = command.ExecuteNonQuery(); - connection.Close(); - } - using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().FirstOrDefault(); + var entity = session.Query.All().FirstOrDefault(); Assert.That(entity, Is.Not.Null); Assert.That(entity.Id, Is.Not.Null); } diff --git a/Orm/Xtensive.Orm.Tests/Storage/ForeignKeyTest.cs b/Orm/Xtensive.Orm.Tests/Storage/ForeignKeyTest.cs index 79fa4f50f7..fefc4f8ab8 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/ForeignKeyTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/ForeignKeyTest.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Storage.ForeignKeys { - [Serializable] [KeyGenerator(KeyGeneratorKind.Custom, Name = "DualInt")] [HierarchyRoot] public class User : Entity @@ -38,7 +37,6 @@ public class User : Entity public EntitySet Projects { get; private set; } } - [Serializable] [KeyGenerator(KeyGeneratorKind.Custom, Name = "DualInt")] [HierarchyRoot] public class Company : Entity @@ -56,7 +54,6 @@ public class Company : Entity public User Director { get; set; } } - [Serializable] [KeyGenerator(KeyGeneratorKind.Custom, Name = "DualInt")] [HierarchyRoot] public class Project : Entity @@ -74,7 +71,6 @@ public class Project : Entity public EntitySet Users { get; private set; } } - [Serializable] public class ForeignUser : User { [Field] diff --git a/Orm/Xtensive.Orm.Tests/Storage/GeneralBehaviorTest.cs b/Orm/Xtensive.Orm.Tests/Storage/GeneralBehaviorTest.cs index 495490a74c..98ea880e16 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/GeneralBehaviorTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/GeneralBehaviorTest.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Storage.GeneralBehaviorTestModel { - [Serializable] [HierarchyRoot] public abstract class Person : Entity { @@ -22,14 +21,12 @@ public abstract class Person : Entity public string Name { get; set; } } - [Serializable] public class Customer : Person { [Field, Association(PairTo = "Customer")] public EntitySet Orders { get; private set; } } - [Serializable] [HierarchyRoot] public class Order : Entity { @@ -43,7 +40,6 @@ public class Order : Entity public Customer Customer { get; set; } } - [Serializable] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] public class CustomerOrder : Entity diff --git a/Orm/Xtensive.Orm.Tests/Storage/IntermediateQueryTest.cs b/Orm/Xtensive.Orm.Tests/Storage/IntermediateQueryTest.cs index 9a0853c094..561fa6b7c4 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/IntermediateQueryTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/IntermediateQueryTest.cs @@ -53,7 +53,6 @@ public Child() } } - [Serializable] public class IntermediateQueryTest : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() diff --git a/Orm/Xtensive.Orm.Tests/Storage/IoC/ServiceTestBase.cs b/Orm/Xtensive.Orm.Tests/Storage/IoC/ServiceTestBase.cs index a3e3487142..4cde1fdbaf 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/IoC/ServiceTestBase.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/IoC/ServiceTestBase.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Storage.IoC.Model { - [Serializable] [HierarchyRoot] public class MyEntity : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/KeysTest.cs b/Orm/Xtensive.Orm.Tests/Storage/KeysTest.cs index 100316b8de..501669dcbb 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/KeysTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/KeysTest.cs @@ -1,8 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. -// Created by: -// Created: 2008.09.17 +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. using System; using NUnit.Framework; @@ -103,7 +101,6 @@ public class Test : Entity public TimeSpan Key15 { get; private set; } } - [Serializable] [HierarchyRoot] public class Container : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/LazyLoadTest.cs b/Orm/Xtensive.Orm.Tests/Storage/LazyLoadTest.cs index a8bc1b57a5..060d872251 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/LazyLoadTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/LazyLoadTest.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Storage.BookAuthorModel { - [Serializable] [HierarchyRoot] public class Book : Entity { @@ -31,7 +30,6 @@ public class Book : Entity public Author Author { get; set; } } - [Serializable] [HierarchyRoot] public class Author : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/LegacyDb/AnimalDbBaseTest.cs b/Orm/Xtensive.Orm.Tests/Storage/LegacyDb/AnimalDbBaseTest.cs index 4036f33500..3cc6e52269 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/LegacyDb/AnimalDbBaseTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/LegacyDb/AnimalDbBaseTest.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Storage.LegacyDb.AnimalDbTestModel { - [Serializable] [HierarchyRoot(InheritanceSchema = InheritanceSchema.SingleTable)] [TypeDiscriminatorValue("Animal", Default = true)] public class Animal : Entity @@ -36,19 +35,16 @@ public class Animal : Entity public Person Owner { get; set; } } - [Serializable] [TypeDiscriminatorValue("Dog")] public class Dog : Animal { } - [Serializable] [TypeDiscriminatorValue("Cat")] public class Cat : Animal { } - [Serializable] [HierarchyRoot] public abstract class Person : Entity { @@ -63,7 +59,6 @@ public abstract class Person : Entity public string ElementType { get; private set; } } - [Serializable] [TypeDiscriminatorValue("Cat")] public class CatLover : Person { @@ -76,7 +71,6 @@ public class CatLover : Person public EntitySet Pets { get; private set; } } - [Serializable] [TypeDiscriminatorValue("Dog")] public class DogLover : Person { @@ -88,7 +82,6 @@ public class DogLover : Person public EntitySet Pets { get; private set; } } - [Serializable] [HierarchyRoot(InheritanceSchema = InheritanceSchema.ConcreteTable)] public abstract class VetClinic : Entity { @@ -106,7 +99,6 @@ public abstract class VetClinic : Entity public abstract void Kill(Animal victim); } - [Serializable] public class DogClinic : VetClinic { public override void Heal(Animal patient) @@ -120,7 +112,6 @@ public override void Kill(Animal victim) } } - [Serializable] public class CatClinic : VetClinic { public override void Heal(Animal patient) diff --git a/Orm/Xtensive.Orm.Tests/Storage/LegacyDb/DateAndTimeColumnsTest.cs b/Orm/Xtensive.Orm.Tests/Storage/LegacyDb/DateAndTimeColumnsTest.cs index 11a6d95f07..32492c7ac6 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/LegacyDb/DateAndTimeColumnsTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/LegacyDb/DateAndTimeColumnsTest.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Storage.LegacyDb.CrazyColumns2008TestModel { - [Serializable] [HierarchyRoot] public class Crazy : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/LegacyDb/SqlServerSmallDateTimeTest.cs b/Orm/Xtensive.Orm.Tests/Storage/LegacyDb/SqlServerSmallDateTimeTest.cs index b6b95c6090..4bfd4df560 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/LegacyDb/SqlServerSmallDateTimeTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/LegacyDb/SqlServerSmallDateTimeTest.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Storage.LegacyDb.CrazyColumns2005TestModel { - [Serializable] [HierarchyRoot] public class Crazy : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/ManyToManyValidationTest.cs b/Orm/Xtensive.Orm.Tests/Storage/ManyToManyValidationTest.cs index c5f1baecda..ee8122b447 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/ManyToManyValidationTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/ManyToManyValidationTest.cs @@ -6,7 +6,6 @@ using System; using System.Linq; -using System.Runtime.Serialization; using NUnit.Framework; using Xtensive.Orm.Configuration; using Xtensive.Orm.Model; @@ -78,11 +77,6 @@ protected EntitySetValidatedByOwner(Entity owner, FieldInfo field) : base(owner, field) { } - - protected EntitySetValidatedByOwner(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } diff --git a/Orm/Xtensive.Orm.Tests/Storage/MemoryProviderTest.cs b/Orm/Xtensive.Orm.Tests/Storage/MemoryProviderTest.cs index a230cdcec2..23929311fe 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/MemoryProviderTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/MemoryProviderTest.cs @@ -66,34 +66,34 @@ public void MainTest() var domain = Domain.Build(configuration); var singleConnection = Upgrader.Connection; - Assert.That(domain.StorageProviderInfo.Supports(ProviderFeatures.SingleConnection)); - - using (var session = domain.OpenSession()) - using (var tx = session.OpenTransaction()) { - _ = new TheEntity {Value = "in-memory"}; - CheckSingleConnection(session, singleConnection); - tx.Complete(); - } - - using (var session = domain.OpenSession()) - using (var tx = session.OpenTransaction()) { - var theEntity = session.Query.All().Single(); - Assert.That(theEntity.Value, Is.EqualTo("in-memory")); - CheckSingleConnection(session, singleConnection); - tx.Complete(); - } - - using (var session = domain.OpenSession()) { - AssertEx.ThrowsInvalidOperationException(() => domain.OpenSession()); - } - - using (var session = domain.OpenSession()) - using (var tx = session.OpenTransaction()) { - CheckSingleConnection(session, singleConnection); + using (domain) { + Assert.That(domain.StorageProviderInfo.Supports(ProviderFeatures.SingleConnection)); + + using (var session = domain.OpenSession()) + using (var tx = session.OpenTransaction()) { + _ = new TheEntity { Value = "in-memory" }; + CheckSingleConnection(session, singleConnection); + tx.Complete(); + } + + using (var session = domain.OpenSession()) + using (var tx = session.OpenTransaction()) { + var theEntity = session.Query.All().Single(); + Assert.That(theEntity.Value, Is.EqualTo("in-memory")); + CheckSingleConnection(session, singleConnection); + tx.Complete(); + } + + using (var session = domain.OpenSession()) { + AssertEx.ThrowsInvalidOperationException(() => domain.OpenSession()); + } + + using (var session = domain.OpenSession()) + using (var tx = session.OpenTransaction()) { + CheckSingleConnection(session, singleConnection); + } } - domain.Dispose(); - Assert.DoesNotThrow(() => singleConnection.State.ToString()); Assert.That(singleConnection.State, Is.EqualTo(ConnectionState.Closed)); } diff --git a/Orm/Xtensive.Orm.Tests/Storage/Modules/Assembly0.cs b/Orm/Xtensive.Orm.Tests/Storage/Modules/Assembly0.cs index 5e43cc8c78..f52c5c6507 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Modules/Assembly0.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Modules/Assembly0.cs @@ -10,7 +10,6 @@ namespace Modules.Model { - [Serializable] [HierarchyRoot] public class Simple0 : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/Modules/Assembly1.cs b/Orm/Xtensive.Orm.Tests/Storage/Modules/Assembly1.cs index 1e456dae45..ef0dc3ca81 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Modules/Assembly1.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Modules/Assembly1.cs @@ -14,7 +14,6 @@ namespace Modules.Model { - [Serializable] [HierarchyRoot] public class Simple1 : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/Modules/Assembly2.cs b/Orm/Xtensive.Orm.Tests/Storage/Modules/Assembly2.cs index 8fe613592c..11c6c0cd9a 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Modules/Assembly2.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Modules/Assembly2.cs @@ -15,7 +15,6 @@ namespace Modules.Model { - [Serializable] [HierarchyRoot] public class Simple2 : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/Multimapping/CycleReferencesDetectionTest.cs b/Orm/Xtensive.Orm.Tests/Storage/Multimapping/CycleReferencesDetectionTest.cs index 6db8a9f812..9910e616e6 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Multimapping/CycleReferencesDetectionTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Multimapping/CycleReferencesDetectionTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2012 Xtensive LLC. +// Copyright (C) 2012 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Denis Krjuchkov @@ -105,19 +105,18 @@ private void BuildDomain(bool allowCycles, params int?[] databaseIndexes) configuration.MappingRules.Map(types[i].Namespace).ToDatabase(name); } - var domain = Domain.Build(configuration); + using (var domain = Domain.Build(configuration)) { - Assert.That(domain.Configuration.IsMultidatabase); + Assert.That(domain.Configuration.IsMultidatabase); - for (int i = 0; i < types.Length; i++) { - var expected = names[i]; - if (expected==null) - continue; - var actual = domain.Model.Types[types[i]].MappingDatabase; - Assert.That(actual, Is.EqualTo(expected)); + for (int i = 0; i < types.Length; i++) { + var expected = names[i]; + if (expected == null) + continue; + var actual = domain.Model.Types[types[i]].MappingDatabase; + Assert.That(actual, Is.EqualTo(expected)); + } } - - domain.Dispose(); } public override void TestFixtureSetUp() diff --git a/Orm/Xtensive.Orm.Tests/Storage/NorthwindValidateTest.cs b/Orm/Xtensive.Orm.Tests/Storage/NorthwindValidateTest.cs index 51fa265c80..3fec3d770a 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/NorthwindValidateTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/NorthwindValidateTest.cs @@ -15,10 +15,9 @@ public class NorthwindValidateTest [Test] public void MainTest() { - var initialDomain = BuildDomain(DomainUpgradeMode.Recreate); - initialDomain.Dispose(); - var validatedDomain = BuildDomain(DomainUpgradeMode.Validate); - validatedDomain.Dispose(); + using (var initialDomain = BuildDomain(DomainUpgradeMode.Recreate)) { } + + using (var validatedDomain = BuildDomain(DomainUpgradeMode.Validate)) { } } public Domain BuildDomain(DomainUpgradeMode mode) diff --git a/Orm/Xtensive.Orm.Tests/Storage/NotifyXxxTest.cs b/Orm/Xtensive.Orm.Tests/Storage/NotifyXxxTest.cs index 39017022eb..0610a9e782 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/NotifyXxxTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/NotifyXxxTest.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Tests.Storage.NotifyXxxTests { - [Serializable] [HierarchyRoot] public class Book : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/OperationOrderTest.cs b/Orm/Xtensive.Orm.Tests/Storage/OperationOrderTest.cs index 9cdf4f109b..979a78b8a4 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/OperationOrderTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/OperationOrderTest.cs @@ -17,7 +17,6 @@ namespace Xtensive.Orm.Tests.Storage.OperationOrderTest { - [Serializable] [HierarchyRoot] public class Book : Entity { @@ -37,7 +36,7 @@ public override string ToString() } [TestFixture] - public class OperationOrderTest : AutoBuildTest + public class VoidOperationOrderTest : AutoBuildTest { private static bool disabled = false; private static object expectedTarget = null; @@ -62,20 +61,20 @@ public void StandardTest() using (DisableEvents()) { b = new Book(); } - - AssertOperations(b, new [] {"Entity.SetValue"}); + + AssertOperations(b, new[] { "Entity.SetValue" }); b.Title = "Book"; - AssertOperations(b.Referenecs, new [] {"EntitySet.AddItem"}); - b.Referenecs.Add(b); + AssertOperations(b.Referenecs, new[] { "EntitySet.AddItem" }); + _ = b.Referenecs.Add(b); - AssertOperations(b.Referenecs, new [] {"EntitySet.RemoveItem"}); - b.Referenecs.Remove(b); + AssertOperations(b.Referenecs, new[] { "EntitySet.RemoveItem" }); + _ = b.Referenecs.Remove(b); - AssertOperations(b.Referenecs, new [] {"EntitySet.Clear"}); + AssertOperations(b.Referenecs, new[] { "EntitySet.Clear" }); b.Referenecs.Clear(); - AssertOperations(b, new [] {"Entity.Remove"}); + AssertOperations(b, new[] { "Entity.Remove" }); b.Remove(); // tx.Complete(); @@ -87,10 +86,6 @@ public void StandardTest() private static void BindEvents(Session session) { - var operations = session.Operations; - operations.OutermostOperationStarting += (s, ea) => InOperation(s, ea); - operations.NestedOperationStarting += (s, ea) => InOperation(s, ea); - var events = session.Events; events.EntityFieldValueSetting += (s, ea) => BeforeOperation(ea.Entity, "Entity.SetValue"); @@ -114,60 +109,6 @@ private static void BindEvents(Session session) events.EntitySetClearCompleted += (s, ea) => AfterOperation(ea.EntitySet, "EntitySet.Clear"); } - private static void InOperation(object sender, OperationEventArgs ea) - { - if (disabled) - return; - - object target = null; - if (ea.Operation is EntitySetOperation) { - var eso = (EntitySetOperation) ea.Operation; - var entity = Session.Demand().Query.Single(eso.Key); - target = entity.GetProperty(eso.Field.Name); - } - else if (ea.Operation is EntityOperation) { - var eo = (EntityOperation) ea.Operation; - target = Session.Demand().Query.Single(eo.Key); - } - else if (ea.Operation is EntitiesRemoveOperation) { - var ero = (EntitiesRemoveOperation) ea.Operation; - target = Session.Demand().Query.Single(ero.Keys.Single()); - } - else - return; - - if (target!=expectedTarget) - return; - if ((ea.Operation.Type & OperationType.System)!=OperationType.System) - return; - - string prefix = null; - if (target is Entity) - prefix = "Entity"; - else if (target is EntitySetBase) - prefix = "EntitySet"; - else - return; - - string suffix = null; - if (ea.Operation.GetType()==typeof(EntityFieldSetOperation)) - suffix = "SetValue"; - else if (ea.Operation.GetType()==typeof(EntitiesRemoveOperation)) - suffix = "Remove"; - - else if (ea.Operation.GetType()==typeof(EntitySetItemAddOperation)) - suffix = "AddItem"; - else if (ea.Operation.GetType()==typeof(EntitySetItemRemoveOperation)) - suffix = "RemoveItem"; - else if (ea.Operation.GetType()==typeof (EntitySetClearOperation)) - suffix = "Clear"; - else - return; - - string operation = $"{prefix}.{suffix}"; - InOperation(target, operation); - } - public static IDisposable DisableEvents() { var oldDisabled = disabled; @@ -187,13 +128,13 @@ public static void BeforeOperation(object target, string operation) { if (disabled) return; - if (target!=expectedTarget) + if (target != expectedTarget) return; TestLog.Info($"Before '{operation}'"); var lastOperation = (lastOperationIndex < 0) ? null : expectedOperations[lastOperationIndex]; if (lastOperation != operation) { - if (lastOperationState!=-2 && lastOperationState!=1) + if (lastOperationState != -2 && lastOperationState != 1) Assert.Fail("Invalid notification order: no 'after' event."); lastOperationIndex++; lastOperation = expectedOperations[lastOperationIndex]; @@ -202,7 +143,7 @@ public static void BeforeOperation(object target, string operation) lastOperationState = -1; } else { - if (lastOperationState>=0) + if (lastOperationState >= 0) Assert.Fail("Invalid notification order: 'before' event is unexpected here."); } } @@ -211,7 +152,7 @@ public static void InOperation(object target, string operation) { if (disabled) return; - if (target!=expectedTarget) + if (target != expectedTarget) return; TestLog.Info($"In '{operation}'"); @@ -219,9 +160,9 @@ public static void InOperation(object target, string operation) if (lastOperation != operation) Assert.Fail("Invalid notification order: no 'before' event."); else { - if (lastOperationState==-1) + if (lastOperationState == -1) lastOperationState = 0; - if (lastOperationState!=0) + if (lastOperationState != 0) Assert.Fail("Invalid notification order: 'in' event is unexpected here."); } } @@ -230,7 +171,7 @@ public static void AfterOperation(object target, string operation) { if (disabled) return; - if (target!=expectedTarget) + if (target != expectedTarget) return; TestLog.Info($"After '{operation}'"); @@ -238,9 +179,9 @@ public static void AfterOperation(object target, string operation) if (lastOperation != operation) Assert.Fail("Invalid notification order: no 'before' event."); else { - if (lastOperationState==0) + if (lastOperationState == 0) lastOperationState = 1; - if (lastOperationState!=1) + if (lastOperationState != -1) Assert.Fail("Invalid notification order: 'after' event is unexpected here."); } } diff --git a/Orm/Xtensive.Orm.Tests/Storage/PartialIndexTest.cs b/Orm/Xtensive.Orm.Tests/Storage/PartialIndexTest.cs index 45a064f737..bb9a8c4f10 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/PartialIndexTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/PartialIndexTest.cs @@ -549,51 +549,34 @@ namespace Xtensive.Orm.Tests.Storage [TestFixture] public class PartialIndexTest { - private Domain domain; - [OneTimeSetUp] public void TestFixtureSetUp() => Require.AllFeaturesSupported(ProviderFeatures.PartialIndexes); - [TearDown] - public void TearDown() => CleanDomain(); - - private void CleanDomain() + private Domain BuildDomain(IEnumerable entities, DomainUpgradeMode mode) { - if (domain==null) - return; - try { - domain.Dispose(); - } - finally { - domain = null; - } - } - - private void BuildDomain(IEnumerable entities, DomainUpgradeMode mode) - { - CleanDomain(); var config = DomainConfigurationFactory.Create(); foreach (var entity in entities) { config.Types.Register(entity); } config.UpgradeMode = mode; - domain = Domain.Build(config); + return Domain.Build(config); } private void AssertBuildSuccess(params Type[] entities) { - BuildDomain(entities, DomainUpgradeMode.Recreate); - var partialIndexes = domain.Model.RealIndexes - .Where(index => index.IsPartial && index.FilterExpression != null && index.Filter != null) - .ToList(); - Assert.That(partialIndexes, Is.Not.Empty); + using (var domain = BuildDomain(entities, DomainUpgradeMode.Recreate)) { + var partialIndexes = domain.Model.RealIndexes + .Where(index => index.IsPartial && index.FilterExpression != null && index.Filter != null) + .ToList(); + Assert.That(partialIndexes, Is.Not.Empty); + } } private void AssertBuildFailure(params Type[] entities) { - AssertEx.Throws(() => BuildDomain(entities, DomainUpgradeMode.Recreate)); + AssertEx.Throws(() => BuildDomain(entities, DomainUpgradeMode.Recreate).Dispose()); } [Test] @@ -680,8 +663,9 @@ public void ValidateTestForPgSql() && type != typeof(FilterOnComplexReferenceField3) && type != typeof(FilterOnComplexReferenceField4)) .ToList(); - BuildDomain(types, DomainUpgradeMode.Recreate); - BuildDomain(types, DomainUpgradeMode.Validate); + using (BuildDomain(types, DomainUpgradeMode.Recreate)) { } + + Assert.DoesNotThrow(() => BuildDomain(types, DomainUpgradeMode.Validate).Dispose()); } [Test, RequireSqlServer] @@ -697,8 +681,9 @@ public void ValidateTestForSqlServer() && type != typeof(FilterOnComplexReferenceField3) && type != typeof(FilterOnComplexReferenceField4)) .ToList(); - BuildDomain(types, DomainUpgradeMode.Recreate); - BuildDomain(types, DomainUpgradeMode.Validate); + using (BuildDomain(types, DomainUpgradeMode.Recreate)) { } + + Assert.DoesNotThrow(() => BuildDomain(types, DomainUpgradeMode.Validate).Dispose()); } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Storage/Performance/CrudModel/NonPairedSimplestContainerItem.cs b/Orm/Xtensive.Orm.Tests/Storage/Performance/CrudModel/NonPairedSimplestContainerItem.cs index e1f06a2f5d..231f21956f 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Performance/CrudModel/NonPairedSimplestContainerItem.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Performance/CrudModel/NonPairedSimplestContainerItem.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.Storage.Performance.CrudModel { - [Serializable] [HierarchyRoot] public sealed class NonPairedSimplestContainerItem : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/Performance/CrudModel/PairedSimplestContainerItem.cs b/Orm/Xtensive.Orm.Tests/Storage/Performance/CrudModel/PairedSimplestContainerItem.cs index b5e1dcd150..6f834931d2 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Performance/CrudModel/PairedSimplestContainerItem.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Performance/CrudModel/PairedSimplestContainerItem.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.Storage.Performance.CrudModel { - [Serializable] [HierarchyRoot] public class PairedSimplestContainerItem : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/Performance/CrudModel/Simplest.cs b/Orm/Xtensive.Orm.Tests/Storage/Performance/CrudModel/Simplest.cs index a1fc174191..6da1f6b7b3 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Performance/CrudModel/Simplest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Performance/CrudModel/Simplest.cs @@ -10,7 +10,6 @@ namespace Xtensive.Orm.Tests.Storage.Performance.CrudModel { - [Serializable] [HierarchyRoot] [Index("Value")] public class Simplest : Entity diff --git a/Orm/Xtensive.Orm.Tests/Storage/Performance/CrudModel/SimplestContainer.cs b/Orm/Xtensive.Orm.Tests/Storage/Performance/CrudModel/SimplestContainer.cs index 5569524b3c..bdb304d0dd 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Performance/CrudModel/SimplestContainer.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Performance/CrudModel/SimplestContainer.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.Storage.Performance.CrudModel { - [Serializable] [HierarchyRoot] public sealed class SimplestContainer : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/Prefetch/Model.cs b/Orm/Xtensive.Orm.Tests/Storage/Prefetch/Model.cs index 3a5e6e3668..86b3b5d2ed 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Prefetch/Model.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Prefetch/Model.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Storage.Prefetch.Model { - [Serializable] [HierarchyRoot] public class Simple : Entity { @@ -25,7 +24,6 @@ public class Simple : Entity public string Value { get; set;} } - [Serializable] [HierarchyRoot] public abstract class Person : Entity { @@ -46,7 +44,6 @@ protected Person(int id) {} } - [Serializable] public abstract class AdvancedPerson : Person { [Field] @@ -62,7 +59,6 @@ protected AdvancedPerson(int id) {} } - [Serializable] public class Customer : AdvancedPerson { [Field, Association(PairTo = "Customer", OnTargetRemove = OnRemoveAction.Clear)] @@ -82,14 +78,12 @@ public Customer(int id) {} } - [Serializable] public class Supplier : AdvancedPerson { [Field, Association(PairTo = "Supplier")] public EntitySet Products { get; private set;} } - [Serializable] public class Employee : AdvancedPerson, IEnumerable { @@ -107,7 +101,6 @@ IEnumerator IEnumerable.GetEnumerator() } } - [Serializable] [HierarchyRoot] public class Order : Entity { @@ -127,7 +120,6 @@ public class Order : Entity public EntitySet Details { get; private set; } } - [Serializable] [HierarchyRoot] public class OrderDetail : Entity { @@ -144,7 +136,6 @@ public class OrderDetail : Entity public int Count { get; set; } } - [Serializable] [HierarchyRoot] public abstract class AbstractProduct : Entity { @@ -155,7 +146,6 @@ public abstract class AbstractProduct : Entity public string Name { get; set; } } - [Serializable] public class Product : AbstractProduct { [Field] @@ -168,14 +158,12 @@ public interface IHasCategory : IEntity string Category { get; set; } } - [Serializable] public class PersonalProduct : AbstractProduct { [Field] public Employee Employee { get; set; } } - [Serializable] [HierarchyRoot] public class Book : Entity, IHasCategory @@ -197,7 +185,6 @@ public class Book : Entity, public EntitySet TranslationTitles { get; private set; } } - [Serializable] [HierarchyRoot] public class Author : Entity { @@ -222,7 +209,6 @@ public interface ITitle : IEntity Book Book { get; set; } } - [Serializable] [HierarchyRoot] public class Title : Entity, ITitle @@ -238,7 +224,6 @@ public class Title : Entity, public string Language { get; set; } } - [Serializable] [HierarchyRoot] public class AnotherTitle : Entity, ITitle @@ -260,7 +245,6 @@ public interface IPublisher : IEntity EntitySet Distributors { get; } } - [Serializable] [HierarchyRoot] public class Publisher : Entity, IPublisher @@ -287,7 +271,6 @@ public interface IBookShop : IEntity EntitySet Suppliers { get; } } - [Serializable] [HierarchyRoot] public class BookShop : Entity, IBookShop @@ -308,8 +291,7 @@ public interface IReferenceToSelf : IEntity [Field] IReferenceToSelf Reference { get; set; } } - - [Serializable] + [HierarchyRoot] public class ReferenceToSelf : Entity, IReferenceToSelf @@ -323,7 +305,6 @@ public class ReferenceToSelf : Entity, public IReferenceToSelf Reference { get; set; } } - [Serializable] public class Offer : Structure { [Field] @@ -339,7 +320,6 @@ public class Offer : Structure public int Lazy { get; set; } } - [Serializable] public class IntermediateOffer : Structure { [Field] @@ -352,7 +332,6 @@ public class IntermediateOffer : Structure public Offer RealOffer { get; set; } } - [Serializable] [HierarchyRoot] public class OfferContainer : Entity { @@ -372,7 +351,6 @@ public class OfferContainer : Entity public int Lazy { get; set; } } - [Serializable] [HierarchyRoot] public class LazyClass : Entity { @@ -386,7 +364,6 @@ public class LazyClass : Entity public int LazyInt { get; set; } } - [Serializable] [HierarchyRoot] public class IdOnly : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/BooleanHandlingTest.cs b/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/BooleanHandlingTest.cs index f48a7c3ae4..ee791001e3 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/BooleanHandlingTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/BooleanHandlingTest.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Tests.Storage.Providers.Sql.BooleanHandlingTestModel { - [Serializable] [HierarchyRoot] public class MyEntity : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/CharSupportTest.cs b/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/CharSupportTest.cs index a1bc62dedc..2cc41b7e89 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/CharSupportTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/CharSupportTest.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Tests.Storage.Providers.Sql.CharSupportTestModel { - [Serializable] [HierarchyRoot] class MyEntity : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/TableReferenceTest.cs b/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/TableReferenceTest.cs index 0be3d1ae73..73c43cc770 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/TableReferenceTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Providers/Sql/TableReferenceTest.cs @@ -20,7 +20,6 @@ namespace Xtensive.Orm.Tests.Storage.Providers.Sql.TableReferenceTestModel { - [Serializable] [KeyGenerator(KeyGeneratorKind.None)] [HierarchyRoot] public class ABase: Entity @@ -35,7 +34,6 @@ public class ABase: Entity public Guid Id3A { get; private set; } } - [Serializable] [Index("JustField1", "JustField2")] [Index("JustField3")] public class A : ABase @@ -70,7 +68,6 @@ public class A : ABase public B ManyToOne { get; set; } } - [Serializable] [KeyGenerator(KeyGeneratorKind.None)] [HierarchyRoot] public class BBase:Entity @@ -82,7 +79,6 @@ public class BBase:Entity public byte Id2 { get; private set; } } - [Serializable] public class B : BBase { @@ -108,7 +104,6 @@ public class B : BBase /// /// Self-references /// - [Serializable] [HierarchyRoot] public class C : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/Randomized/Tree.cs b/Orm/Xtensive.Orm.Tests/Storage/Randomized/Tree.cs index 540ef2c5d3..d3df5a63df 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Randomized/Tree.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Randomized/Tree.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Storage.Randomized { - [Serializable] [HierarchyRoot] public sealed class Tree : Entity, IEnumerable diff --git a/Orm/Xtensive.Orm.Tests/Storage/Randomized/TreeNode.cs b/Orm/Xtensive.Orm.Tests/Storage/Randomized/TreeNode.cs index 93e09ca58a..cdb6d4164e 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/Randomized/TreeNode.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/Randomized/TreeNode.cs @@ -9,7 +9,6 @@ namespace Xtensive.Orm.Tests.Storage.Randomized { - [Serializable] [HierarchyRoot] public sealed class TreeNode : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/ReadOnlySupport/ReadOnlyStorageTestBase.cs b/Orm/Xtensive.Orm.Tests/Storage/ReadOnlySupport/ReadOnlyStorageTestBase.cs index af045d3229..1b8cb81cff 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/ReadOnlySupport/ReadOnlyStorageTestBase.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/ReadOnlySupport/ReadOnlyStorageTestBase.cs @@ -36,8 +36,7 @@ public abstract class ReadOnlyStorageTestBase [Test] public void DomainBuildTest() { - BuildReadOnlyDomain(); - Assert.DoesNotThrow(()=>BuildReadOnlyDomain()); + Assert.DoesNotThrow(() => BuildReadOnlyDomain().Dispose()); } [Test] diff --git a/Orm/Xtensive.Orm.Tests/Storage/ReadRemovedObjectTest.cs b/Orm/Xtensive.Orm.Tests/Storage/ReadRemovedObjectTest.cs index 00cafcaa1f..bfbecf50a3 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/ReadRemovedObjectTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/ReadRemovedObjectTest.cs @@ -16,7 +16,6 @@ namespace Xtensive.Orm.Tests.Storage.ReadRemovedObjectTest { - [Serializable] [HierarchyRoot] public class Book : Entity { @@ -27,7 +26,6 @@ public class Book : Entity public string Title { get; set; } } - [Serializable] public class CoolBook : Book { [Field] diff --git a/Orm/Xtensive.Orm.Tests/Storage/RefTest.cs b/Orm/Xtensive.Orm.Tests/Storage/RefTest.cs index 579ab88506..781a84bf01 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/RefTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/RefTest.cs @@ -25,12 +25,12 @@ public class RefTest : AutoBuildTest protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof (Author).Assembly, typeof (Author).Namespace); + config.Types.Register(typeof (Author)); return config; } [Test] - public void CombinedTest() + public void MainTest() { Key authorKey; Ref authorRef; @@ -43,8 +43,6 @@ public void CombinedTest() tx.Complete(); } - authorRef = Cloner.Clone(authorRef); - using (var session = Domain.OpenSession()) using (var tx = session.OpenTransaction()) { Assert.That(authorRef.Key, Is.EqualTo(authorKey)); @@ -53,7 +51,6 @@ public void CombinedTest() Assert.That(author.Key, Is.EqualTo(authorRef.Key)); tx.Complete(); } - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Storage/ReferentialIntegrityTest.cs b/Orm/Xtensive.Orm.Tests/Storage/ReferentialIntegrityTest.cs index 302f6a334f..5f89f8b750 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/ReferentialIntegrityTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/ReferentialIntegrityTest.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.ReferentialIntegrityModel { - [Serializable] [HierarchyRoot] public class Root : Entity { @@ -22,7 +21,6 @@ public class Root : Entity private int Id { get; set; } } - [Serializable] public class A : Root { [Field, Association(OnTargetRemove = OnRemoveAction.Clear)] @@ -35,21 +33,18 @@ public class A : Root public string Name { get; set; } } - [Serializable] public class B : Root { [Field, Association(OnTargetRemove = OnRemoveAction.Cascade, PairTo = "B")] public A A { get; set; } } - [Serializable] public class C : Root { [Field, Association(OnTargetRemove = OnRemoveAction.Cascade, PairTo = "C")] public A A { get; set; } } - [Serializable] public class Master : Root { [Field, Association(OnTargetRemove = OnRemoveAction.Clear)] @@ -62,7 +57,6 @@ public class Master : Root public EntitySet ManyToMany { get; private set; } } - [Serializable] public class Slave : Root { [Field, Association(PairTo = "OneToMany")] @@ -72,7 +66,6 @@ public class Slave : Root public EntitySet ManyToMany { get; private set; } } - [Serializable] [HierarchyRoot] public class Container : Entity { @@ -88,7 +81,6 @@ public class Container : Entity public Package Package2 { get; set; } } - [Serializable] [HierarchyRoot] public class Package : Entity { @@ -100,7 +92,6 @@ public class Package : Entity public EntitySet Items { get; private set; } } - [Serializable] [HierarchyRoot] public class PackageItem : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/SerializationTest.cs b/Orm/Xtensive.Orm.Tests/Storage/SerializationTest.cs deleted file mode 100644 index 2292eafa39..0000000000 --- a/Orm/Xtensive.Orm.Tests/Storage/SerializationTest.cs +++ /dev/null @@ -1,331 +0,0 @@ -// Copyright (C) 2009-2021 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Alex Kofman -// Created: 2009.03.19 - -using System; -using System.IO; -using System.Reflection; -using System.Runtime.Serialization.Formatters.Binary; -using NUnit.Framework; -using Xtensive.Orm.Configuration; -using Xtensive.Orm.Serialization; -using Xtensive.Orm.Tests.SerializationTestModel; - -namespace Xtensive.Orm.Tests.SerializationTestModel -{ - [Serializable] - [HierarchyRoot] - public class Company : Entity - { - [Field, Key] - public int Id { get; private set; } - - [Field] - public string Name { get; set; } - - [Field] - public Emploee Head { get; set;} - - public override string ToString() => Name; - } - - [Serializable] - [HierarchyRoot] - public class Emploee : Entity - { - [Field, Key] - public int Id { get; private set; } - - [Field] - public string Name { get; set; } - - [Field] - public Company Company { get; set;} - - public override string ToString() => Name; - - protected override void OnValidate() - { - if (string.IsNullOrEmpty(Name) || Company == null) { - throw new InvalidOperationException("Invalid îbject."); - } - } - } - - [Serializable] - [HierarchyRoot] - [KeyGenerator(KeyGeneratorKind.None)] - public class Country : Entity - { - [Field(Length = 100), Key] - public string Name { get; private set;} - -// [Field] -// public City Capital { get; set; } - - public Country(string name) : - base(name) - { - } - } - - [Serializable] - [HierarchyRoot] - [KeyGenerator(KeyGeneratorKind.None)] - public class City : Entity - { - [Field, Key(0)] - public Country Country { get; private set;} - - [Field(Length = 100), Key(1)] - public string Name { get; private set;} - - public City(Country country, string name) - : base(country, name) - { - } - } - - [Serializable] - public class Address : Structure - { - [Field] - public City City { get; set;} - - [Field] - public string Street { get; set;} - - [Field] - public string Number { get; set;} - } -} - -namespace Xtensive.Orm.Tests.Storage -{ - public class SerializationTest : AutoBuildTest - { - private readonly BinaryFormatter formatter = new BinaryFormatter(); - - protected override DomainConfiguration BuildConfiguration() - { - var config = base.BuildConfiguration(); - config.Types.RegisterCaching(typeof (Company).Assembly, typeof (Company).Namespace); - return config; - } - - - - - [Test] - public void SerializationOfComplexReferencesTest() - { - using (var session = Domain.OpenSession()) - using (var transactionScope = session.OpenTransaction()) { - - } - } - - [Test] - public void SerializationByReferenceTest() - { - using (var stream = new MemoryStream()) { - - var companyName = "Xtensive LLC"; - int companyId; - - using (var session = Domain.OpenSession()) - using (var transactionScope = session.OpenTransaction()) { - var company = new Company { Name = companyName }; - companyId = company.Id; - - using (new SerializationContext(entity => SerializationKind.ByReference).Activate()) { - formatter.Serialize(stream, company); - } - - // Can'not resolve deserialized entity - it's not commited in original session. - var ex = Assert.Throws( - delegate { - using (var session2 = Domain.OpenSession()) - using (session2.OpenTransaction()) { - stream.Position = 0; - _ = formatter.Deserialize(stream); - } - }); - Assert.That(ex.InnerException, Is.InstanceOf()); - - transactionScope.Complete(); - } - - using (var session = Domain.OpenSession()) - using (var transactionScope = session.OpenTransaction()) { - stream.Position = 0; - var companyKey = Key.Create(Domain, typeof(Company), companyId); - var company = (Company) session.Query.SingleOrDefault(companyKey); - - var deserializedCompany = (Company) formatter.Deserialize(stream); - - Assert.That(deserializedCompany, Is.SameAs(company)); - } - - using (var session = Domain.OpenSession()) - using (var transactionScope = session.OpenTransaction()) { - stream.Position = 0; - var company = (Company) formatter.Deserialize(stream); - - Assert.That(company.Name, Is.EqualTo(companyName)); - Assert.That(company.Id, Is.EqualTo(companyId)); - Assert.That(Session.Current, Is.EqualTo(company.Session)); - } - } - } - - [Test] - public void ReferencedKeysTest() - { - using (var stream = new MemoryStream()) { - - using (var session = Domain.OpenSession()) { - - Country russia; - - using (var transactionScope = session.OpenTransaction()) { - russia = new Country("Russia"); - transactionScope.Complete(); - } - - using (session.OpenTransaction()) { - var china = new Country("China"); - - var moscow = new City(russia, "Moscow"); - var ekaterinburg = new City(russia, "Ekaterinburg"); - var hongKong = new City(china, "Hong Kong"); - var beijing = new City(china, "Beijing"); - var guangzhou = new City(china, "Guangzhou"); - - //china.Capital = beijing; - //russia.Capital = moscow; - - var cities = new City[] { ekaterinburg, moscow, hongKong, guangzhou, beijing }; - - var serializationContext = new SerializationContext( - entity => entity == russia - ? SerializationKind.ByReference - : SerializationKind.ByValue); - - using (serializationContext.Activate()) { - formatter.Serialize(stream, cities); - } - // Rollback - } - } - - using (var session = Domain.OpenSession()) - using (session.OpenTransaction()) { - - var deserializationContext = new DeserializationContext(); - - City[] cities; - - using (deserializationContext.Activate()) { - stream.Position = 0; - cities = (City[]) formatter.Deserialize(stream); - } - - var ekaterinburg = cities[0]; - var moscow = cities[1]; - var hongKong = cities[2]; - var guangzhou = cities[3]; - - var russia = ekaterinburg.Country; - var china = guangzhou.Country; - - Assert.That(russia, Is.Not.Null); - Assert.That(china, Is.Not.Null); - - Assert.That(russia.Name, Is.EqualTo("Russia")); - Assert.That(china.Name, Is.EqualTo("China")); - - Assert.That(ekaterinburg.Name, Is.EqualTo("Ekaterinburg")); - Assert.That(moscow.Name, Is.EqualTo("Moscow")); - Assert.That(moscow.Country, Is.EqualTo(russia)); - Assert.That(hongKong.Name, Is.EqualTo("Hong Kong")); - Assert.That(hongKong.Country, Is.EqualTo(china)); - - //Assert.IsNull(russia.Capital); // russia was serialized by reference, not by value - // - //Assert.AreEqual(china.Capital.Name, "Beijing"); - } - } - } - - [Test] - public void ComplexTest() - { - using (var stream = new MemoryStream()) { - - int firstCompanyId; - - using (var session = Domain.OpenSession()) - using (var transactionScope = session.OpenTransaction()) { - var company = new Company { Name = "OpenTransaction lines" }; - firstCompanyId = company.Id; - transactionScope.Complete(); - } - - - using (var session = Domain.OpenSession()) - using (session.OpenTransaction()) { - var existingCompanyKey = Key.Create(Domain, typeof(Company), firstCompanyId); - var existingCompany = (Company) session.Query.SingleOrDefault(existingCompanyKey); - - var company = new Company { Name = "Region mobile" }; - var mike = new Emploee { Name = "Mike", Company = company }; - var alex = new Emploee { Name = "Alex", Company = company }; - var jef = new Emploee { Name = "Jef", Company = existingCompany }; - company.Head = alex; - - var array = new object[] { existingCompany, company, alex, jef }; - session.Validate(); - - var context = new SerializationContext( - entity => entity == existingCompany - ? SerializationKind.ByReference - : SerializationKind.ByValue); - - using (context.Activate()) { - formatter.Serialize(stream, array); - } - // Rollback - } - - using (var session = Domain.OpenSession()) - using (var transactionScope = session.OpenTransaction()) { - - object[] array; - stream.Position = 0; - - var deserializationContext = new DeserializationContext(); - - using (deserializationContext.Activate()) { - array = (object[]) formatter.Deserialize(stream); - } - - var oldCompany = (Company) array[0]; - var newCompany = (Company) array[1]; - var alex = (Emploee) array[2]; - var jef = (Emploee) array[3]; - - Assert.That(oldCompany.Id, Is.EqualTo(firstCompanyId)); - Assert.That(alex.Name, Is.EqualTo("Alex")); - Assert.That(jef.Name, Is.EqualTo("Jef")); - - Assert.That(jef.Company, Is.EqualTo(oldCompany)); - Assert.That(alex.Company, Is.EqualTo(newCompany)); - Assert.That(newCompany.Head, Is.EqualTo(alex)); - } - } - } - } -} diff --git a/Orm/Xtensive.Orm.Tests/Storage/SerializedQueryTest.cs b/Orm/Xtensive.Orm.Tests/Storage/SerializedQueryTest.cs deleted file mode 100644 index a2c6e34932..0000000000 --- a/Orm/Xtensive.Orm.Tests/Storage/SerializedQueryTest.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (C) 2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. -// Created by: Alexis Kochetov -// Created: 2010.02.25 - -using System; -using System.IO; -using NUnit.Framework; -using Xtensive.Core; -using Xtensive.Linq.SerializableExpressions; -using Xtensive.Orm.Linq; -using Xtensive.Orm.Configuration; -using Xtensive.Orm.Serialization; -using Xtensive.Orm.Tests.ObjectModel; -using Xtensive.Orm.Tests.ObjectModel.ChinookDO; -using System.Linq; -using Xtensive.Orm.Providers; - -namespace Xtensive.Orm.Tests.Storage -{ - [TestFixture] - public class SerializedQueryTest : ChinookDOModelTest - { - [Test] - public void CombinedTest() - { - Require.AllFeaturesSupported(ProviderFeatures.RowNumber); - var query = Session.Query.All() - .Where(c => c.Name=="MPEG audio file") - .Where(c => c.MediaTypeId > 0) - .Take(5) - .Skip(0); - - var serializableExpression = query.Expression.ToSerializableExpression(); - var serializedExpression = Cloner.Clone(serializableExpression); - - var deserializedExpression = serializedExpression.ToExpression(); - var deserializedQuery = new Queryable((QueryProvider) query.Provider, deserializedExpression); - var result = deserializedQuery.ToList(); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Storage/SessionEventsTest.cs b/Orm/Xtensive.Orm.Tests/Storage/SessionEventsTest.cs index f44f40ff4f..7940ff5d7c 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/SessionEventsTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/SessionEventsTest.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Storage.SessionEventsTestModel { - [Serializable] [HierarchyRoot] public class MegaEntity : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/SessionInitializationSqlTest.cs b/Orm/Xtensive.Orm.Tests/Storage/SessionInitializationSqlTest.cs index c4c24fce70..013624a9f5 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/SessionInitializationSqlTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/SessionInitializationSqlTest.cs @@ -33,14 +33,14 @@ public void MainTest() long id; - var domain1 = BuildDomain(MultidatabaseTest.Database1Name); + using (var domain1 = BuildDomain(MultidatabaseTest.Database1Name)) using (var session = domain1.OpenSession()) using (var tx = session.OpenTransaction()) { id = new TestEntity().Id; tx.Complete(); } - var domain2 = BuildDomain(MultidatabaseTest.Database2Name); + using (var domain2 = BuildDomain(MultidatabaseTest.Database2Name)) using (var session = domain2.OpenSession()) using (var tx = session.OpenTransaction()) { session.Services.Demand().RegisterInitializationSql(GetUseDatabaseScript(MultidatabaseTest.Database1Name)); diff --git a/Orm/Xtensive.Orm.Tests/Storage/SetFieldTest.cs b/Orm/Xtensive.Orm.Tests/Storage/SetFieldTest.cs index ed2bf61509..1427124279 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/SetFieldTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/SetFieldTest.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Storage.SetFieldTest { - [Serializable] [HierarchyRoot] public class Book : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/StructureReferencesAnEntityTest.cs b/Orm/Xtensive.Orm.Tests/Storage/StructureReferencesAnEntityTest.cs index 50381e2d2b..915c6ec283 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/StructureReferencesAnEntityTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/StructureReferencesAnEntityTest.cs @@ -34,7 +34,6 @@ public class SomeStructure : Structure } } - [Serializable] public class StructureReferencesAnEntityTest : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() diff --git a/Orm/Xtensive.Orm.Tests/Storage/StructureTest.cs b/Orm/Xtensive.Orm.Tests/Storage/StructureTest.cs index eb9f7e82d5..d6011dcc20 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/StructureTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/StructureTest.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Tests.Storage.StructureModel { - [Serializable] public class Point : Structure { [Field(Indexed = true)] @@ -44,7 +43,6 @@ public Point(int x, int y) } } - [Serializable] [Index("Vertex.Y")] [HierarchyRoot] public class Ray : Entity diff --git a/Orm/Xtensive.Orm.Tests/Storage/TransactionsTest.cs b/Orm/Xtensive.Orm.Tests/Storage/TransactionsTest.cs index 2dadf2cd3e..3f812eb3aa 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/TransactionsTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/TransactionsTest.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Storage.TransactionsTestModel { - [Serializable] [HierarchyRoot] public class Hexagon : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/TypeCompatibilityTest.cs b/Orm/Xtensive.Orm.Tests/Storage/TypeCompatibilityTest.cs index 6f562a6c27..5b40f338cb 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/TypeCompatibilityTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/TypeCompatibilityTest.cs @@ -60,7 +60,6 @@ public enum EULong : ulong #endregion - [Serializable] [HierarchyRoot] public class X : Entity { @@ -391,8 +390,7 @@ public void ValidateTest() var configuration = BuildConfiguration(); configuration.UpgradeMode = DomainUpgradeMode.Validate; configuration.Types.Register(typeof (X)); - var domain = Domain.Build(configuration); - domain.Dispose(); + using var domain = Domain.Build(configuration); } [Test] diff --git a/Orm/Xtensive.Orm.Tests/Storage/UnexpectedBehaviorTest.cs b/Orm/Xtensive.Orm.Tests/Storage/UnexpectedBehaviorTest.cs index 7a307b8e15..6501aa043c 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/UnexpectedBehaviorTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/UnexpectedBehaviorTest.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Storage.UnexpectedBehaviorTestModel { - [Serializable] [HierarchyRoot, KeyGenerator(KeyGeneratorKind.None)] public class UncreatableEntity : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/UpdateVersionTest.cs b/Orm/Xtensive.Orm.Tests/Storage/UpdateVersionTest.cs index b27eb49256..cc992d4201 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/UpdateVersionTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/UpdateVersionTest.cs @@ -10,13 +10,13 @@ using Xtensive.Core; using Xtensive.Orm.Configuration; using System.Linq; -using M=Xtensive.Orm.Model; +using M = Xtensive.Orm.Model; +using Xtensive.Orm.Tests.Storage.VersionModel; #region Model namespace Xtensive.Orm.Tests.Storage.VersionModel { - [Serializable] [HierarchyRoot] [KeyGenerator(null)] public class Address : Entity @@ -33,7 +33,6 @@ public Address(string city, string regionCode) } } - [Serializable] public class Phone : Structure { [Field] @@ -43,7 +42,6 @@ public class Phone : Structure public int Number { get; set; } } - [Serializable] [HierarchyRoot] public class Person : Entity { @@ -54,7 +52,6 @@ public class Person : Entity public string Name { get; set; } } - [Serializable] public class Customer : Person { [Field] @@ -64,7 +61,6 @@ public class Customer : Person public Phone Phone { get; set; } } - [Serializable] [HierarchyRoot] public class Author : Entity { @@ -87,7 +83,6 @@ public class Author : Entity public EntitySet Comments { get; private set; } } - [Serializable] [HierarchyRoot] public class Book : Entity { @@ -104,7 +99,6 @@ public class Book : Entity public EntitySet Authors { get; private set; } } - [Serializable] [HierarchyRoot] public class Comment : Entity { @@ -115,8 +109,6 @@ public class Comment : Entity public Author Author { get; set; } } - - [Serializable] public class VersionStructure : Structure { [Field] @@ -124,7 +116,6 @@ public class VersionStructure : Structure public int Version { get; set; } } - [Serializable] [HierarchyRoot] public class VersionEntity : Entity { @@ -151,7 +142,6 @@ protected override bool UpdateVersion(Entity changedEntity, M.FieldInfo changedF } } - [Serializable] [HierarchyRoot] public class ItemWithEntityVersion : Entity { @@ -171,7 +161,6 @@ protected override bool UpdateVersion(Entity changedEntity, M.FieldInfo changedF } } - [Serializable] [HierarchyRoot] public class ItemWithCustomVersions : Entity { @@ -191,7 +180,6 @@ protected override bool UpdateVersion(Entity changedEntity, M.FieldInfo changedF } } - [Serializable] [HierarchyRoot] public class ItemWithAutoVersions : Entity { @@ -231,8 +219,6 @@ public class ItemWithAutoVersions : Entity namespace Xtensive.Orm.Tests.Storage { - using VersionModel; - [TestFixture] public class UpdateVersionTest : AutoBuildTest { @@ -507,23 +493,5 @@ public void AutoUpdateVersionTest() } } } - - [Test] - public void SerializeVersionInfoTest() - { - VersionInfo versionInfo; - - using (var session = Domain.OpenSession()) { - using (var transactionScope = session.OpenTransaction()) { - var instance = new ItemWithAutoVersions(); - versionInfo = instance.VersionInfo; - transactionScope.Complete(); - } - } - Assert.That(versionInfo.IsVoid, Is.False); - var clone = Cloner.Clone(versionInfo); - Assert.That(clone.IsVoid, Is.False); - Assert.That(versionInfo==clone, Is.True); - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Storage/UpgradeModesTest.cs b/Orm/Xtensive.Orm.Tests/Storage/UpgradeModesTest.cs index e816e26eb3..ef0963081e 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/UpgradeModesTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/UpgradeModesTest.cs @@ -17,7 +17,6 @@ namespace Xtensive.Orm.Tests.Storage.UpgradeModesTest { - [Serializable] [HierarchyRoot] public class Book : Entity { @@ -28,7 +27,6 @@ public class Book : Entity public string Title { get; set; } } - [Serializable] [HierarchyRoot] public class Person : Entity { @@ -39,7 +37,6 @@ public class Person : Entity public string Title { get; set; } } - [Serializable] public class Author : Person { // Just to validate how model builder handles [Field(Nullable = ...)] @@ -227,7 +224,8 @@ private Dictionary BuildDomain(string type, DomainUpgradeMode upgrade try { Dictionary result = new Dictionary(); using (m = new Measurement("metrics")) - result = CheckTypeCount(typeCount, Domain.Build(cfg)); + using (var domain = Domain.Build(cfg)) + result = CheckTypeCount(typeCount, domain); Console.WriteLine($" Done, {m}"); return result; } diff --git a/Orm/Xtensive.Orm.Tests/Storage/ValidateOnlyModifiedFieldsTest.cs b/Orm/Xtensive.Orm.Tests/Storage/ValidateOnlyModifiedFieldsTest.cs index 487b9fa02c..18b9383bcf 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/ValidateOnlyModifiedFieldsTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/ValidateOnlyModifiedFieldsTest.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2003-2017 Xtensive LLC. +// Copyright (C) 2003-2017 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Julian Mamokin @@ -769,137 +769,142 @@ namespace Xtensive.Orm.Tests.Storage { public class ValidateOnlyModifiedFieldsTest { - private Domain domain; #region General [Test] public void PostPersistValidationTest() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model1.LengthTestEntity() { ValidatedIfChangedField = "Some string", ValidatedField = "Some string" }); - Assert.Throws(() => { - using (var session = domain.OpenSession()) { - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().Single(); - entity.ValidatedField = ""; - entity.ValidatedIfChangedField = ""; - session.SaveChanges(); - transaction.Complete(); + using (domain) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) { + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().Single(); + entity.ValidatedField = ""; + entity.ValidatedIfChangedField = ""; + session.SaveChanges(); + transaction.Complete(); + } } - } - }); + }); - Assert.DoesNotThrow(() => { - using (var session = domain.OpenSession()) { - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().Single(); - entity.ValidatedField = "valid"; - entity.ValidatedIfChangedField = "valid"; - session.SaveChanges(); - transaction.Complete(); + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) { + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().Single(); + entity.ValidatedField = "valid"; + entity.ValidatedIfChangedField = "valid"; + session.SaveChanges(); + transaction.Complete(); + } } - } - }); + }); + } } [Test] public void NewEntityValidationTest() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model1.LengthTestEntity() { ValidatedIfChangedField = "Some string", ValidatedField = "Some string" }); - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = new model1.LengthTestEntity() { - ValidatedField = string.Empty, - ValidatedIfChangedField = string.Empty - }; - transaction.Complete(); - } - }); + using (domain) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = new model1.LengthTestEntity() { + ValidatedField = string.Empty, + ValidatedIfChangedField = string.Empty + }; + transaction.Complete(); + } + }); - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = new model1.LengthTestEntity() { - ValidatedField = string.Empty, - ValidatedIfChangedField = string.Empty - }; - session.Validate(); - } - }); + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = new model1.LengthTestEntity() { + ValidatedField = string.Empty, + ValidatedIfChangedField = string.Empty + }; + session.Validate(); + } + }); - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = new model1.LengthTestEntity() { - ValidatedField = string.Empty, - ValidatedIfChangedField = string.Empty - }; - entity.Validate(); - } - }); + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = new model1.LengthTestEntity() { + ValidatedField = string.Empty, + ValidatedIfChangedField = string.Empty + }; + entity.Validate(); + } + }); - Assert.DoesNotThrow(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = new model1.LengthTestEntity() { - ValidatedField = "valid", - ValidatedIfChangedField = "valid" - }; - transaction.Complete(); - } - }); + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = new model1.LengthTestEntity() { + ValidatedField = "valid", + ValidatedIfChangedField = "valid" + }; + transaction.Complete(); + } + }); - Assert.DoesNotThrow(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = new model1.LengthTestEntity() { - ValidatedField = "valid", - ValidatedIfChangedField = "valid" - }; - session.Validate(); - } - }); + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = new model1.LengthTestEntity() { + ValidatedField = "valid", + ValidatedIfChangedField = "valid" + }; + session.Validate(); + } + }); - Assert.DoesNotThrow(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = new model1.LengthTestEntity() { - ValidatedField = "valid", - ValidatedIfChangedField = "valid" - }; - entity.Validate(); - } - }); + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = new model1.LengthTestEntity() { + ValidatedField = "valid", + ValidatedIfChangedField = "valid" + }; + entity.Validate(); + } + }); + } } [Test] public void UnchangedEntityTest() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model1.LengthTestEntity() { ValidatedIfChangedField = "Some string", ValidatedField = "Some string" }); - Assert.DoesNotThrow(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedField = entityToChange.ValidatedField; - transaction.Complete(); - } - }); + using (domain) { + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedField = entityToChange.ValidatedField; + transaction.Complete(); + } + }); - Assert.DoesNotThrow(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedField = entityToChange.ValidatedField; - session.Validate(); - } - }); + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedField = entityToChange.ValidatedField; + session.Validate(); + } + }); + } } #endregion @@ -908,429 +913,447 @@ public void UnchangedEntityTest() [Test] public void LengthConstraintTest1() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model1.LengthTestEntity() { ValidatedIfChangedField = "Some string", ValidatedField = "Some string" }); - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = ""; - Assert.Throws(() => { - session.Validate(); - }); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = ""; - Assert.Throws(() => { - entityToChange.Validate(); - }); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = ""; - var errors = session.ValidateAndGetErrors(); - var temp = errors; - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (domain) { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = ""; + _ = Assert.Throws(() => { + session.Validate(); + }); + } - Assert.Throws(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = "x"; - transaction.Complete(); + entityToChange.ValidatedIfChangedField = ""; + _ = Assert.Throws(() => { + entityToChange.Validate(); + }); } - }); - Assert.Throws(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedField = ""; - transaction.Complete(); + entityToChange.ValidatedIfChangedField = ""; + var errors = session.ValidateAndGetErrors(); + var temp = errors; + Assert.That(errors.Count, Is.EqualTo(1)); } - }); + + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = "x"; + transaction.Complete(); + } + }); + + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedField = ""; + transaction.Complete(); + } + }); + } } [Test] public void NotEmptyConstraintTest1() { - PrepareDomain(() => - new model1.NotEmptyTestEntity() { ValidatedIfChangedField = "Some string", ValidatedField = "Some string" }); - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = string.Empty; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = string.Empty; - Assert.Throws(() => entityToChange.Validate()); - } + var domain = PrepareDomain(() => + new model1.NotEmptyTestEntity() { ValidatedIfChangedField = "Some string", ValidatedField = "Some string" }); - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = string.Empty; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (domain) { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = string.Empty; + _ = Assert.Throws(() => session.Validate()); + } - Assert.Throws(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); entityToChange.ValidatedIfChangedField = string.Empty; - transaction.Complete(); + _ = Assert.Throws(() => entityToChange.Validate()); } - }); - Assert.Throws(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedField = string.Empty; - transaction.Complete(); + entityToChange.ValidatedIfChangedField = string.Empty; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); } - }); + + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = string.Empty; + transaction.Complete(); + } + }); + + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedField = string.Empty; + transaction.Complete(); + } + }); + } } [Test] public void NotNullConstraintTest1() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model1.NotNullTestEntity() { ValidatedIfChangedField = "Some string", ValidatedField = "Some string" }); - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = null; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = null; - Assert.Throws(() => entityToChange.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = null; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (domain) { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = null; + _ = Assert.Throws(() => session.Validate()); + } - Assert.Throws(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); entityToChange.ValidatedIfChangedField = null; - transaction.Complete(); + _ = Assert.Throws(() => entityToChange.Validate()); } - }); - Assert.Throws(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedField = null; - transaction.Complete(); + entityToChange.ValidatedIfChangedField = null; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); } - }); + + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = null; + transaction.Complete(); + } + }); + + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedField = null; + transaction.Complete(); + } + }); + } } [Test] public void NotNullOrEmptyConstraintTest1() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model1.NotNullOrEmptyTestEntity() { ValidatedIfChangedField = "Some string", ValidatedField = "Some string" }); - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = null; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = null; - Assert.Throws(() => entityToChange.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = null; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (domain) { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = null; + _ = Assert.Throws(() => session.Validate()); + } - Assert.Throws(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); entityToChange.ValidatedIfChangedField = null; - transaction.Complete(); + _ = Assert.Throws(() => entityToChange.Validate()); } - }); - Assert.Throws(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedField = null; - transaction.Complete(); + entityToChange.ValidatedIfChangedField = null; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); } - }); + + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = null; + transaction.Complete(); + } + }); + + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedField = null; + transaction.Complete(); + } + }); + } } [Test] public void PastConstraintTest1() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model1.PastConstraintTestEntity() { ValidatedIfChangedField = DateTime.Now - TimeSpan.FromHours(1), ValidatedField = DateTime.Now - TimeSpan.FromHours(1) }); - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = DateTime.Now + TimeSpan.FromHours(1); - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = DateTime.Now + TimeSpan.FromHours(1); - Assert.Throws(() => entityToChange.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = DateTime.Now + TimeSpan.FromHours(1); - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (domain) { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = DateTime.Now + TimeSpan.FromHours(1); + _ = Assert.Throws(() => session.Validate()); + } - Assert.Throws(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); entityToChange.ValidatedIfChangedField = DateTime.Now + TimeSpan.FromHours(1); - transaction.Complete(); + _ = Assert.Throws(() => entityToChange.Validate()); } - }); - Assert.Throws(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedField = DateTime.Now + TimeSpan.FromHours(1); - transaction.Complete(); + entityToChange.ValidatedIfChangedField = DateTime.Now + TimeSpan.FromHours(1); + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); } - }); + + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = DateTime.Now + TimeSpan.FromHours(1); + transaction.Complete(); + } + }); + + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedField = DateTime.Now + TimeSpan.FromHours(1); + transaction.Complete(); + } + }); + } } [Test] public void FutureConstraintTest1() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model1.FutureConstraintTestEntity() { ValidatedIfChangedField = DateTime.Now + TimeSpan.FromHours(1), ValidatedField = DateTime.Now + TimeSpan.FromHours(1) }); - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = DateTime.Now - TimeSpan.FromHours(1); - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = DateTime.Now - TimeSpan.FromHours(1); - Assert.Throws(() => entityToChange.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = DateTime.Now - TimeSpan.FromHours(1); - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (domain) { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = DateTime.Now - TimeSpan.FromHours(1); + _ = Assert.Throws(() => session.Validate()); + } - Assert.Throws(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); entityToChange.ValidatedIfChangedField = DateTime.Now - TimeSpan.FromHours(1); - transaction.Complete(); + _ = Assert.Throws(() => entityToChange.Validate()); } - }); - Assert.Throws(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedField = DateTime.Now - TimeSpan.FromHours(1); - transaction.Complete(); + entityToChange.ValidatedIfChangedField = DateTime.Now - TimeSpan.FromHours(1); + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); } - }); + + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = DateTime.Now - TimeSpan.FromHours(1); + transaction.Complete(); + } + }); + + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedField = DateTime.Now - TimeSpan.FromHours(1); + transaction.Complete(); + } + }); + } } [Test] public void EmailConstraintTest1() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model1.EmailConstraintTestEntity() { ValidatedIfChangedField = "julian1990@mail.ru", ValidatedField = "julian1990@mail.ru" }); - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = "lol"; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = "lol"; - Assert.Throws(() => entityToChange.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = "lol"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (domain) { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = "lol"; + _ = Assert.Throws(() => session.Validate()); + } - Assert.Throws(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); entityToChange.ValidatedIfChangedField = "lol"; - transaction.Complete(); + _ = Assert.Throws(() => entityToChange.Validate()); } - }); - Assert.Throws(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedField = "lol"; - transaction.Complete(); + entityToChange.ValidatedIfChangedField = "lol"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); } - }); + + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = "lol"; + transaction.Complete(); + } + }); + + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedField = "lol"; + transaction.Complete(); + } + }); + } } [Test] public void RangeConstraintTest1() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model1.RangeConstraintTestEntity() { ValidatedIfChangedField = 6, ValidatedField = 6 }); - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = 12; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = 12; - Assert.Throws(() => entityToChange.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = 12; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (domain) { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = 12; + _ = Assert.Throws(() => session.Validate()); + } - Assert.Throws(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); entityToChange.ValidatedIfChangedField = 12; - transaction.Complete(); + _ = Assert.Throws(() => entityToChange.Validate()); } - }); - Assert.Throws(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedField = 12; - transaction.Complete(); + entityToChange.ValidatedIfChangedField = 12; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); } - }); + + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = 12; + transaction.Complete(); + } + }); + + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedField = 12; + transaction.Complete(); + } + }); + } } [Test] public void RegExConstraintTest1() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model1.RegExConstraintTestEntity() { ValidatedIfChangedField = "abc", ValidatedField = "abc" }); - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = "***"; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = "***"; - Assert.Throws(() => entityToChange.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = "***"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (domain) { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = "***"; + _ = Assert.Throws(() => session.Validate()); + } - Assert.Throws(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); entityToChange.ValidatedIfChangedField = "***"; - transaction.Complete(); + _ = Assert.Throws(() => entityToChange.Validate()); } - }); - Assert.Throws(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedField = "***"; - transaction.Complete(); + entityToChange.ValidatedIfChangedField = "***"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); } - }); + + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = "***"; + transaction.Complete(); + } + }); + + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedField = "***"; + transaction.Complete(); + } + }); + } } #endregion @@ -1339,424 +1362,442 @@ public void RegExConstraintTest1() [Test] public void LengthConstraintTest2() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model2.LengthTestEntity() { ValidatedIfChangedField = "Some string", ValidatedField = "Some string" }); - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = ""; - Assert.Throws(() => { session.Validate(); }); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = ""; - Assert.Throws(() => { entityToChange.Validate(); }); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = ""; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (domain) { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = ""; + _ = Assert.Throws(() => { session.Validate(); }); + } - Assert.DoesNotThrow(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); entityToChange.ValidatedIfChangedField = ""; - transaction.Complete(); + _ = Assert.Throws(() => { entityToChange.Validate(); }); } - }); - Assert.DoesNotThrow(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedField = ""; - transaction.Complete(); + entityToChange.ValidatedIfChangedField = ""; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); } - }); + + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = ""; + transaction.Complete(); + } + }); + + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedField = ""; + transaction.Complete(); + } + }); + } } [Test] public void NotEmptyConstraintTest2() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model2.NotEmptyTestEntity() { ValidatedIfChangedField = "Some string", ValidatedField = "Some string" }); - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = string.Empty; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = string.Empty; - Assert.Throws(() => entityToChange.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = string.Empty; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (domain) { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = string.Empty; + _ = Assert.Throws(() => session.Validate()); + } - Assert.DoesNotThrow(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); entityToChange.ValidatedIfChangedField = string.Empty; - transaction.Complete(); + _ = Assert.Throws(() => entityToChange.Validate()); } - }); - Assert.DoesNotThrow(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedField = string.Empty; - transaction.Complete(); + entityToChange.ValidatedIfChangedField = string.Empty; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); } - }); + + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = string.Empty; + transaction.Complete(); + } + }); + + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedField = string.Empty; + transaction.Complete(); + } + }); + } } [Test] public void NotNullConstraintTest2() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model2.NotNullTestEntity() { ValidatedIfChangedField = "Some string", ValidatedField = "Some string" }); - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = null; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = null; - Assert.Throws(() => entityToChange.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = null; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (domain) { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = null; + _ = Assert.Throws(() => session.Validate()); + } - Assert.DoesNotThrow(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); entityToChange.ValidatedIfChangedField = null; - transaction.Complete(); + _ = Assert.Throws(() => entityToChange.Validate()); } - }); - Assert.DoesNotThrow(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedField = null; - transaction.Complete(); + entityToChange.ValidatedIfChangedField = null; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); } - }); + + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = null; + transaction.Complete(); + } + }); + + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedField = null; + transaction.Complete(); + } + }); + } } [Test] public void NotNullOrEmptyConstraintTest2() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model2.NotNullOrEmptyTestEntity() { ValidatedIfChangedField = "Some string", ValidatedField = "Some string" }); - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = null; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = null; - Assert.Throws(() => entityToChange.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = null; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (domain) { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = null; + _ = Assert.Throws(() => session.Validate()); + } - Assert.DoesNotThrow(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); entityToChange.ValidatedIfChangedField = null; - transaction.Complete(); + _ = Assert.Throws(() => entityToChange.Validate()); } - }); - Assert.DoesNotThrow(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedField = null; - transaction.Complete(); + entityToChange.ValidatedIfChangedField = null; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); } - }); + + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = null; + transaction.Complete(); + } + }); + + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedField = null; + transaction.Complete(); + } + }); + } } [Test] public void PastConstraintTest2() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model2.PastConstraintTestEntity() { ValidatedIfChangedField = DateTime.Now - TimeSpan.FromHours(1), ValidatedField = DateTime.Now - TimeSpan.FromHours(1) }); - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = DateTime.Now + TimeSpan.FromHours(1); - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = DateTime.Now + TimeSpan.FromHours(1); - Assert.Throws(() => entityToChange.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = DateTime.Now + TimeSpan.FromHours(1); - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (domain) { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = DateTime.Now + TimeSpan.FromHours(1); + _ = Assert.Throws(() => session.Validate()); + } - Assert.DoesNotThrow(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); entityToChange.ValidatedIfChangedField = DateTime.Now + TimeSpan.FromHours(1); - transaction.Complete(); + _ = Assert.Throws(() => entityToChange.Validate()); } - }); - Assert.DoesNotThrow(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedField = DateTime.Now + TimeSpan.FromHours(1); - transaction.Complete(); + entityToChange.ValidatedIfChangedField = DateTime.Now + TimeSpan.FromHours(1); + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); } - }); + + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = DateTime.Now + TimeSpan.FromHours(1); + transaction.Complete(); + } + }); + + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedField = DateTime.Now + TimeSpan.FromHours(1); + transaction.Complete(); + } + }); + } } [Test] public void FutureConstraintTest2() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model2.FutureConstraintTestEntity() { ValidatedIfChangedField = DateTime.Now + TimeSpan.FromHours(1), ValidatedField = DateTime.Now + TimeSpan.FromHours(1) }); - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = DateTime.Now - TimeSpan.FromHours(1); - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = DateTime.Now - TimeSpan.FromHours(1); - Assert.Throws(() => entityToChange.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = DateTime.Now - TimeSpan.FromHours(1); - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (domain) { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = DateTime.Now - TimeSpan.FromHours(1); + _ = Assert.Throws(() => session.Validate()); + } - Assert.DoesNotThrow(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); entityToChange.ValidatedIfChangedField = DateTime.Now - TimeSpan.FromHours(1); - transaction.Complete(); + _ = Assert.Throws(() => entityToChange.Validate()); } - }); - Assert.DoesNotThrow(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedField = DateTime.Now - TimeSpan.FromHours(1); - transaction.Complete(); + entityToChange.ValidatedIfChangedField = DateTime.Now - TimeSpan.FromHours(1); + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); } - }); + + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = DateTime.Now - TimeSpan.FromHours(1); + transaction.Complete(); + } + }); + + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedField = DateTime.Now - TimeSpan.FromHours(1); + transaction.Complete(); + } + }); + } } [Test] public void EmailConstraintTest2() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model2.EmailConstraintTestEntity() { ValidatedIfChangedField = "julian1990@mail.ru", ValidatedField = "julian1990@mail.ru" }); - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = "lol"; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()){ - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = "lol"; - Assert.Throws(() => entityToChange.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = "lol"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (domain) { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = "lol"; + _ = Assert.Throws(() => session.Validate()); + } - Assert.DoesNotThrow(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); entityToChange.ValidatedIfChangedField = "lol"; - transaction.Complete(); + _ = Assert.Throws(() => entityToChange.Validate()); } - }); - Assert.DoesNotThrow(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedField = "lol"; - transaction.Complete(); + entityToChange.ValidatedIfChangedField = "lol"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); } - }); + + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = "lol"; + transaction.Complete(); + } + }); + + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedField = "lol"; + transaction.Complete(); + } + }); + } } [Test] public void RangeConstraintTest2() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model2.RangeConstraintTestEntity() { ValidatedIfChangedField = 6, ValidatedField = 6 }); - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = 12; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = 12; - Assert.Throws(() => entityToChange.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = 12; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (domain) { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = 12; + _ = Assert.Throws(() => session.Validate()); + } - Assert.DoesNotThrow(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); entityToChange.ValidatedIfChangedField = 12; - transaction.Complete(); + _ = Assert.Throws(() => entityToChange.Validate()); } - }); - Assert.DoesNotThrow(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedField = 12; - transaction.Complete(); + entityToChange.ValidatedIfChangedField = 12; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); } - }); + + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = 12; + transaction.Complete(); + } + }); + + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedField = 12; + transaction.Complete(); + } + }); + } } [Test] public void RegExConstraintTest2() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model2.RegExConstraintTestEntity() { ValidatedIfChangedField = "abc", ValidatedField = "abc" }); - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = "***"; - Assert.Throws(() => session.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = "***"; - Assert.Throws(() => entityToChange.Validate()); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = "***"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (domain) { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = "***"; + _ = Assert.Throws(() => session.Validate()); + } - Assert.DoesNotThrow(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); entityToChange.ValidatedIfChangedField = "***"; - transaction.Complete(); + _ = Assert.Throws(() => entityToChange.Validate()); } - }); - Assert.DoesNotThrow(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedField = "***"; - transaction.Complete(); + entityToChange.ValidatedIfChangedField = "***"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); } - }); + + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = "***"; + transaction.Complete(); + } + }); + + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedField = "***"; + transaction.Complete(); + } + }); + } } #endregion @@ -1765,137 +1806,154 @@ public void RegExConstraintTest2() [Test] public void LengthConstraintTest3() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model3.LengthTestEntity() { ValidatedIfChangedField = "Some string", ValidatedField = "Some string" }); - - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = ""; - } - }); + + using (domain) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = ""; + } + }); + } } [Test] public void NotEmptyConstraintTest3() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model3.NotEmptyTestEntity() { ValidatedIfChangedField = "Some string", ValidatedField = "Some string" }); - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = string.Empty; - } - }); + using (domain) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = string.Empty; + } + }); + } } [Test] public void NotNullConstraintTest3() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model3.NotNullTestEntity() { ValidatedIfChangedField = "Some string", ValidatedField = "Some string" }); - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = null; - } - }); + using (domain) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = null; + } + }); + } } [Test] public void NotNullOrEmptyConstraintTest3() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model3.NotNullOrEmptyTestEntity() { ValidatedIfChangedField = "Some string", ValidatedField = "Some string" }); - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = null; - } - }); + using (domain) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = null; + } + }); + } } [Test] public void PastConstraintTest3() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model3.PastConstraintTestEntity() { ValidatedIfChangedField = DateTime.Now - TimeSpan.FromHours(1), ValidatedField = DateTime.Now - TimeSpan.FromHours(1) }); - - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = DateTime.Now + TimeSpan.FromHours(1); - } - }); + using (domain) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = DateTime.Now + TimeSpan.FromHours(1); + } + }); + } } [Test] public void FutureConstraintTest3() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model3.FutureConstraintTestEntity() { ValidatedIfChangedField = DateTime.Now + TimeSpan.FromHours(1), ValidatedField = DateTime.Now + TimeSpan.FromHours(1) }); - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = DateTime.Now - TimeSpan.FromHours(1); - } - }); + using (domain) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = DateTime.Now - TimeSpan.FromHours(1); + } + }); + } } [Test] public void EmailConstraintTest3() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model3.EmailConstraintTestEntity() { ValidatedIfChangedField = "julian1990@mail.ru", ValidatedField = "julian1990@mail.ru" }); - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = "lol"; - } - }); + using (domain) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = "lol"; + } + }); + } } [Test] public void RangeConstraintTest3() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model3.RangeConstraintTestEntity() { ValidatedIfChangedField = 6, ValidatedField = 6 }); - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = 12; - } - }); + using (domain) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = 12; + } + }); + } } [Test] public void RegExConstraintTest3() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model3.RegExConstraintTestEntity() { ValidatedIfChangedField = "abc", ValidatedField = "abc" }); - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = "***"; - } - }); + using (domain) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = "***"; + } + }); + } } #endregion @@ -1903,137 +1961,156 @@ public void RegExConstraintTest3() #region ValidateIfChanged_IsImmediate_SkipOnTransactionCommit [Test] - public void LengthConstraintTest4() { - PrepareDomain(() => + public void LengthConstraintTest4() + { + var domain = PrepareDomain(() => new model4.LengthTestEntity() { ValidatedIfChangedField = "Some string", ValidatedField = "Some string" }); - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = ""; - } - }); + using (domain) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = ""; + } + }); + } } [Test] public void NotEmptyConstraintTest4() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model4.NotEmptyTestEntity() { ValidatedIfChangedField = "Some string", ValidatedField = "Some string" }); - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = string.Empty; - } - }); + using (domain) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = string.Empty; + } + }); + } } [Test] public void NotNullConstraintTest4() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model4.NotNullTestEntity() { ValidatedIfChangedField = "Some string", ValidatedField = "Some string" }); - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = null; - } - }); + using (domain) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = null; + } + }); + } } [Test] public void NotNullOrEmptyConstraintTest4() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model4.NotNullOrEmptyTestEntity() { ValidatedIfChangedField = "Some string", ValidatedField = "Some string" }); - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = null; - } - }); + using (domain) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = null; + } + }); + } } [Test] public void PastConstraintTest4() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model4.PastConstraintTestEntity() { ValidatedIfChangedField = DateTime.Now - TimeSpan.FromHours(1), ValidatedField = DateTime.Now - TimeSpan.FromHours(1) }); - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = DateTime.Now + TimeSpan.FromHours(1); - } - }); + using (domain) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = DateTime.Now + TimeSpan.FromHours(1); + } + }); + } } [Test] public void FutureConstraintTest4() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model4.FutureConstraintTestEntity() { ValidatedIfChangedField = DateTime.Now + TimeSpan.FromHours(1), ValidatedField = DateTime.Now + TimeSpan.FromHours(1) }); - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = DateTime.Now - TimeSpan.FromHours(1); - } - }); + using (domain) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = DateTime.Now - TimeSpan.FromHours(1); + } + }); + } } [Test] public void EmailConstraintTest4() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model4.EmailConstraintTestEntity() { ValidatedIfChangedField = "julian1990@mail.ru", ValidatedField = "julian1990@mail.ru" }); - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = "lol"; - } - }); + using (domain) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = "lol"; + } + }); + } } [Test] public void RangeConstraintTest4() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model4.RangeConstraintTestEntity() { ValidatedIfChangedField = 6, ValidatedField = 6 }); - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = 12; - } - }); + using (domain) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = 12; + } + }); + } } [Test] public void RegExConstraintTest4() { - PrepareDomain(() => + var domain = PrepareDomain(() => new model4.RegExConstraintTestEntity() { ValidatedIfChangedField = "abc", ValidatedField = "abc" }); - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.ValidatedIfChangedField = "***"; - } - }); + using (domain) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.ValidatedIfChangedField = "***"; + } + }); + } } #endregion @@ -2043,173 +2120,182 @@ public void RegExConstraintTest4() [Test] public void StructureTest1() { - PrepareDomain(() => new model1.StructureTestEntity() { + var domain = PrepareDomain(() => new model1.StructureTestEntity() { StructureField = new model1.TestStructure() { ValidatedField = "valid", ValidatedIfChangedField = "valid" } }); - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.StructureField.ValidatedIfChangedField = "lol"; - Assert.Throws(() => { session.Validate(); }); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.StructureField.ValidatedIfChangedField = "lol"; - Assert.Throws(() => { - entityToChange.Validate(); - }); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.StructureField.ValidatedIfChangedField = "lol"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (domain) { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.StructureField.ValidatedIfChangedField = "lol"; + _ = Assert.Throws(() => { session.Validate(); }); + } - Assert.Throws(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); entityToChange.StructureField.ValidatedIfChangedField = "lol"; - transaction.Complete(); + _ = Assert.Throws(() => { + entityToChange.Validate(); + }); } - }); - Assert.Throws(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); - entityToChange.StructureField.ValidatedField = "lol"; - transaction.Complete(); + entityToChange.StructureField.ValidatedIfChangedField = "lol"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); } - }); + + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.StructureField.ValidatedIfChangedField = "lol"; + transaction.Complete(); + } + }); + + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.StructureField.ValidatedField = "lol"; + transaction.Complete(); + } + }); + } } [Test] public void StructureTest2() { - PrepareDomain(() => new model2.StructureTestEntity() { + var domain = PrepareDomain(() => new model2.StructureTestEntity() { StructureField = new model2.TestStructure() { ValidatedField = "valid", ValidatedIfChangedField = "valid" } }); - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.StructureField.ValidatedIfChangedField = "lol"; - Assert.Throws(() => { - session.Validate(); - }); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.StructureField.ValidatedIfChangedField = "lol"; - Assert.Throws(() => { - entityToChange.Validate(); - }); - } - - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.StructureField.ValidatedIfChangedField = "lol"; - var errors = session.ValidateAndGetErrors(); - Assert.That(errors.Count, Is.EqualTo(1)); - } + using (domain) { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.StructureField.ValidatedIfChangedField = "lol"; + _ = Assert.Throws(() => { + session.Validate(); + }); + } - Assert.DoesNotThrow(() => { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); entityToChange.StructureField.ValidatedIfChangedField = "lol"; - transaction.Complete(); + _ = Assert.Throws(() => { + entityToChange.Validate(); + }); } - }); - Assert.DoesNotThrow(() => { using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { + using (var transaction = session.OpenTransaction()) { var entityToChange = session.Query.All().Single(); - entityToChange.StructureField.ValidatedField = "lol"; - transaction.Complete(); + entityToChange.StructureField.ValidatedIfChangedField = "lol"; + var errors = session.ValidateAndGetErrors(); + Assert.That(errors.Count, Is.EqualTo(1)); } - }); + + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.StructureField.ValidatedIfChangedField = "lol"; + transaction.Complete(); + } + }); + + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.StructureField.ValidatedField = "lol"; + transaction.Complete(); + } + }); + } } [Test] public void StructureTest3() { - PrepareDomain(() => new model3.StructureTestEntity() { + var domain = PrepareDomain(() => new model3.StructureTestEntity() { StructureField = new model3.TestStructure() { ValidatedField = "valid", ValidatedIfChangedField = "valid" } }); - - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.StructureField.ValidatedIfChangedField = "***"; - } - }); + using (domain) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.StructureField.ValidatedIfChangedField = "***"; + } + }); + } } [Test] public void StructureTest4() { - PrepareDomain(() => new model4.StructureTestEntity() { + var domain = PrepareDomain(() => new model4.StructureTestEntity() { StructureField = new model4.TestStructure() { ValidatedField = "valid", ValidatedIfChangedField = "valid" } }); - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.StructureField.ValidatedIfChangedField = "***"; - } - }); + using (domain) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.StructureField.ValidatedIfChangedField = "***"; + } + }); + } } [Test] public void UnchangedStructureTest() { - PrepareDomain(() => new model4.StructureTestEntity() { + var domain = PrepareDomain(() => new model4.StructureTestEntity() { StructureField = new model4.TestStructure() { ValidatedField = "valid", ValidatedIfChangedField = "valid" } }); - Assert.DoesNotThrow(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entityToChange = session.Query.All().Single(); - entityToChange.StructureField.ValidatedIfChangedField = entityToChange.StructureField.ValidatedIfChangedField; - transaction.Complete(); - } - }); + using (domain) { + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entityToChange = session.Query.All().Single(); + entityToChange.StructureField.ValidatedIfChangedField = entityToChange.StructureField.ValidatedIfChangedField; + transaction.Complete(); + } + }); + } } [Test] public void IncludedStructureTest() { - PrepareDomain(() => new model1.IncludedStructure() { + var domain = PrepareDomain(() => new model1.IncludedStructure() { StructureField = new model1.Structure1() { ValidatedIfChangedField = "valid", EnclosedStructureField = new model1.Structure2() { @@ -2218,56 +2304,59 @@ public void IncludedStructureTest() } }); - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().Single(); - entity.StructureField.ValidatedIfChangedField = ""; - session.Validate(); - } - }); - - Assert.Throws(() => { - using (var session = domain.OpenSession()) - using (var transaction = session.OpenTransaction()) { - var entity = session.Query.All().Single(); - entity.StructureField.EnclosedStructureField.ValidatedIfChangedField2 = ""; - session.Validate(); - } - }); + using (domain) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().Single(); + entity.StructureField.ValidatedIfChangedField = ""; + session.Validate(); + } + }); - Assert.DoesNotThrow(() => { - using (var session = domain.OpenSession()) { + _ = Assert.Throws(() => { + using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var entity = session.Query.All().Single(); - entity.StructureField.ValidatedIfChangedField = entity.StructureField.ValidatedIfChangedField; - entity.StructureField.EnclosedStructureField.ValidatedIfChangedField2 = entity.StructureField.EnclosedStructureField.ValidatedIfChangedField2; - transaction.Complete(); + entity.StructureField.EnclosedStructureField.ValidatedIfChangedField2 = ""; + session.Validate(); } - } - }); + }); + + Assert.DoesNotThrow(() => { + using (var session = domain.OpenSession()) { + using (var transaction = session.OpenTransaction()) { + var entity = session.Query.All().Single(); + entity.StructureField.ValidatedIfChangedField = entity.StructureField.ValidatedIfChangedField; + entity.StructureField.EnclosedStructureField.ValidatedIfChangedField2 = entity.StructureField.EnclosedStructureField.ValidatedIfChangedField2; + transaction.Complete(); + } + } + }); + } } #endregion - private void PrepareDomain(Func entity) where T : Entity + private Domain PrepareDomain(Func entity) where T : Entity { - BuildDomain(typeof (T)); - PoppualateData(entity); + var domain = BuildDomain(typeof (T)); + PopualateData(domain, entity); + return domain; } - private void PoppualateData(Func entity) + private void PopualateData(Domain domain, Func entityFactory) { using (var session = domain.OpenSession()) using (var transaction = session.OpenTransaction()) { - entity.Invoke(); + _ = entityFactory(); transaction.Complete(); } } - private void BuildDomain(Type type) + private Domain BuildDomain(Type type) { var config = BuildConfiguration(type); - domain = Domain.Build(config); + return Domain.Build(config); } private DomainConfiguration BuildConfiguration(Type type) diff --git a/Orm/Xtensive.Orm.Tests/Storage/ValidationConstraintsOnGenericTypeTest.cs b/Orm/Xtensive.Orm.Tests/Storage/ValidationConstraintsOnGenericTypeTest.cs index 87ad888cc9..bd13ae835f 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/ValidationConstraintsOnGenericTypeTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/ValidationConstraintsOnGenericTypeTest.cs @@ -26,7 +26,6 @@ public sealed class GenericEntity : EntityBase } [HierarchyRoot(InheritanceSchema = InheritanceSchema.ConcreteTable)] - [Serializable] public abstract class EntityBase : Entity { [Field, Key] diff --git a/Orm/Xtensive.Orm.Tests/Storage/ValidationContextTest.cs b/Orm/Xtensive.Orm.Tests/Storage/ValidationContextTest.cs index b155f057b8..beabc71ca5 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/ValidationContextTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/ValidationContextTest.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Storage.ValidationContextTestModel { - [Serializable] [HierarchyRoot] public class Validatable : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/ValidationReferentialTest.cs b/Orm/Xtensive.Orm.Tests/Storage/ValidationReferentialTest.cs index d9a46eca27..b08d5beffe 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/ValidationReferentialTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/ValidationReferentialTest.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Storage.ValidationReferentialTestModel { - [Serializable] [HierarchyRoot] public class Company : Entity { @@ -25,7 +24,6 @@ public class Company : Entity } - [Serializable] [HierarchyRoot] public class Contact : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Storage/ValidationTest.cs b/Orm/Xtensive.Orm.Tests/Storage/ValidationTest.cs index 606adb55f5..c1978082b6 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/ValidationTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/ValidationTest.cs @@ -19,7 +19,6 @@ public class ValidationTest : AutoBuildTest { private static AsyncLocal validationCallsCountAsync = new AsyncLocal(); - [Serializable] [HierarchyRoot] public class Referrer : Entity { @@ -43,7 +42,6 @@ public Referrer() } } - [Serializable] [HierarchyRoot] public class Reference : Entity { @@ -63,7 +61,6 @@ public Reference() } } - [Serializable] [HierarchyRoot] public class Mouse : Entity { @@ -96,7 +93,6 @@ protected override void OnValidate() } } - [Serializable] public class Led : Structure { [Field] diff --git a/Orm/Xtensive.Orm.Tests/Storage/VersionBehaviorTest.cs b/Orm/Xtensive.Orm.Tests/Storage/VersionBehaviorTest.cs index 2391579906..4a2baec91e 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/VersionBehaviorTest.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/VersionBehaviorTest.cs @@ -202,7 +202,8 @@ public void DefaultTest() config.Types.Register(typeof (Base)); config.Types.Register(typeof (Default)); config.Types.Register(typeof (DefaultInheritor)); - var domain = Domain.Build(config); + + using var domain = Domain.Build(config); var defaultTypeInfo = domain.Model.Types[typeof(Default)]; var defaultInheritorTypeInfo = domain.Model.Types[typeof(DefaultInheritor)]; Assert.That(defaultTypeInfo.GetVersionColumns().Count(), Is.EqualTo(3)); @@ -270,7 +271,8 @@ public void ManualTest() config.Types.Register(typeof (AnotherManual)); config.Types.Register(typeof (ManualInheritor)); config.Types.Register(typeof (AnotherManualInheritor)); - var domain = Domain.Build(config); + + using var domain = Domain.Build(config); var manualTypeInfo = domain.Model.Types[typeof(Manual)]; var anotherManualTypeInfo = domain.Model.Types[typeof(AnotherManual)]; var manualInheritorTypeInfo = domain.Model.Types[typeof(ManualInheritor)]; @@ -340,7 +342,8 @@ public void AutoTest() config.Types.Register(typeof (Base)); config.Types.Register(typeof (DateTimeVersionAuto)); config.Types.Register(typeof (DateTimeAutoInheritor)); - var domain = Domain.Build(config); + + using var domain = Domain.Build(config); var autoTypeInfo = domain.Model.Types[typeof(DateTimeVersionAuto)]; var autoInheritorTypeInfo = domain.Model.Types[typeof(DateTimeAutoInheritor)]; Assert.That(autoTypeInfo.GetVersionColumns().Count, Is.EqualTo(1)); @@ -416,7 +419,8 @@ public void AutoTestNoDateTime() config.Types.Register(typeof(Base)); config.Types.Register(typeof(LongVersionAuto)); config.Types.Register(typeof(LongAutoInheritor)); - var domain = Domain.Build(config); + + using var domain = Domain.Build(config); var autoTypeInfo = domain.Model.Types[typeof(LongVersionAuto)]; var autoInheritorTypeInfo = domain.Model.Types[typeof(LongAutoInheritor)]; Assert.That(autoTypeInfo.GetVersionColumns().Count, Is.EqualTo(1)); @@ -493,7 +497,8 @@ public void SkipTest() config.Types.Register(typeof (Version)); config.Types.Register(typeof (HasVersion)); config.Types.Register(typeof (HasSkipVersion)); - var domain = Domain.Build(config); + + using var domain = Domain.Build(config); var skipTypeInfo = domain.Model.Types[typeof(Skip)]; var hasVersionTypeInfo = domain.Model.Types[typeof(HasVersion)]; var hasSkipVersionTypeInfo = domain.Model.Types[typeof(HasSkipVersion)]; @@ -574,7 +579,7 @@ public void HasManualVersionTest() config.Types.Register(typeof(Base)); config.Types.Register(typeof(VersionBehavior.Model.Version)); config.Types.Register(typeof(HasManualVersion)); - Assert.Throws(() => Domain.Build(config)); + _ = Assert.Throws(() => Domain.Build(config).Dispose()); } [Test] @@ -584,7 +589,7 @@ public void HasAutoVersionTest() config.Types.Register(typeof(Base)); config.Types.Register(typeof(VersionBehavior.Model.Version)); config.Types.Register(typeof(HasAutoVersion)); - Assert.Throws(() => Domain.Build(config)); + _ = Assert.Throws(() => Domain.Build(config).Dispose()); } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Storage/VersionRootTests.cs b/Orm/Xtensive.Orm.Tests/Storage/VersionRootTests.cs index 7eb6015427..c377e548b6 100644 --- a/Orm/Xtensive.Orm.Tests/Storage/VersionRootTests.cs +++ b/Orm/Xtensive.Orm.Tests/Storage/VersionRootTests.cs @@ -12,12 +12,12 @@ using Xtensive.Orm.Configuration; using System.Linq; using Xtensive.Collections; +using Xtensive.Orm.Tests.Storage.VersionRootModel; #region Model namespace Xtensive.Orm.Tests.Storage.VersionRootModel { - [Serializable] [HierarchyRoot] public class Order : Entity { @@ -31,14 +31,12 @@ public class Order : Entity public int Number { get; set; } } - [Serializable] public class AdvancedOrder : Order { [Field] public string CustomerName { get; set; } } - [Serializable] [HierarchyRoot] public class OrderItem : Entity, IHasVersionRoots @@ -64,14 +62,12 @@ public IEnumerable GetVersionRoots() } } - [Serializable] public class AdvancedOrderItem : OrderItem { [Field] public string SupplierName { get; set; } } - [Serializable] [HierarchyRoot] public class Owner1 : Entity { @@ -82,7 +78,6 @@ public class Owner1 : Entity public long Version { get; private set; } } - [Serializable] [HierarchyRoot] public class Owner2 : Entity { @@ -96,7 +91,6 @@ public class Owner2 : Entity internal ushort Version2 { get; set; } } - [Serializable] [HierarchyRoot] public class Item : Entity, IHasVersionRoots @@ -118,8 +112,6 @@ public IEnumerable GetVersionRoots() namespace Xtensive.Orm.Tests.Storage { - using VersionRootModel; - [TestFixture] public class VersionRootTests : AutoBuildTest @@ -239,25 +231,5 @@ public void UpdateVersionWithManyRootsTest() } } } - - [Test] - public void SerializeVersionInfoTest() - { - VersionInfo itemVersion; - - using (var session = Domain.OpenSession()) { - using (var transactionScope = session.OpenTransaction()) { - var owner1 = new Owner1(); - var owner2 = new Owner2(); - var item = new Item {Value = "Value"}; - itemVersion = item.VersionInfo; - transactionScope.Complete(); - } - } - Assert.That(itemVersion.IsVoid, Is.False); - var clone = Cloner.Clone(itemVersion); - Assert.That(clone.IsVoid, Is.False); - Assert.That(itemVersion==clone, Is.True); - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/ChangeFulltextCatalogTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/ChangeFulltextCatalogTest.cs index 90d3ed06d3..bf89fd740b 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/ChangeFulltextCatalogTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/ChangeFulltextCatalogTest.cs @@ -74,7 +74,7 @@ public void Test02() Domain.Build(configuration).Dispose(); configuration = BuildConfiguration(DomainUpgradeMode.Validate, true); - var exception = Assert.Throws(() => Domain.Build(configuration)); + var exception = Assert.Throws(() => Domain.Build(configuration).Dispose()); Assert.That(exception.ComparisonResult.SchemaComparisonStatus, Is.EqualTo(SchemaComparisonStatus.TargetIsSuperset)); Assert.That(exception.ComparisonResult.Difference.HasChanges, Is.True); } @@ -86,7 +86,7 @@ public void AsyncTest02() Domain.Build(configuration).Dispose(); configuration = BuildConfiguration(DomainUpgradeMode.Validate, true); - var exception = Assert.ThrowsAsync(async () => await Domain.BuildAsync(configuration)); + var exception = Assert.ThrowsAsync(async () => (await Domain.BuildAsync(configuration)).Dispose()); Assert.That(exception.ComparisonResult.SchemaComparisonStatus, Is.EqualTo(SchemaComparisonStatus.TargetIsSuperset)); Assert.That(exception.ComparisonResult.Difference.HasChanges, Is.True); } @@ -98,7 +98,7 @@ public void Test03() Domain.Build(configuration).Dispose(); configuration = BuildConfiguration(DomainUpgradeMode.Validate, false); - var exception = Assert.Throws(() => Domain.Build(configuration)); + var exception = Assert.Throws(() => Domain.Build(configuration).Dispose()); Assert.That(exception.ComparisonResult.SchemaComparisonStatus, Is.EqualTo(SchemaComparisonStatus.TargetIsSuperset)); Assert.That(exception.ComparisonResult.Difference.HasChanges, Is.True); } @@ -110,7 +110,7 @@ public void AsyncTest03() Domain.Build(configuration).Dispose(); configuration = BuildConfiguration(DomainUpgradeMode.Validate, false); - var exception = Assert.ThrowsAsync(async () => await Domain.BuildAsync(configuration)); + var exception = Assert.ThrowsAsync(async () => (await Domain.BuildAsync(configuration)).Dispose()); Assert.That(exception.ComparisonResult.SchemaComparisonStatus, Is.EqualTo(SchemaComparisonStatus.TargetIsSuperset)); Assert.That(exception.ComparisonResult.Difference.HasChanges, Is.True); } @@ -270,7 +270,7 @@ public void Test09() Domain.Build(configuration).Dispose(); configuration = BuildConfiguration(DomainUpgradeMode.Validate, false); - var exception = Assert.Throws(() => Domain.Build(configuration)); + var exception = Assert.Throws(() => Domain.Build(configuration).Dispose()); Assert.That(exception.ComparisonResult.SchemaComparisonStatus, Is.EqualTo(SchemaComparisonStatus.TargetIsSuperset)); Assert.That(exception.ComparisonResult.Difference.HasChanges, Is.True); } @@ -282,7 +282,7 @@ public void AsyncTest09() Domain.Build(configuration).Dispose(); configuration = BuildConfiguration(DomainUpgradeMode.Validate, false); - var exception = Assert.ThrowsAsync(async () => await Domain.BuildAsync(configuration)); + var exception = Assert.ThrowsAsync(async () => (await Domain.BuildAsync(configuration)).Dispose()); Assert.That(exception.ComparisonResult.SchemaComparisonStatus, Is.EqualTo(SchemaComparisonStatus.TargetIsSuperset)); Assert.That(exception.ComparisonResult.Difference.HasChanges, Is.True); } @@ -294,7 +294,7 @@ public void Test10() Domain.Build(configuration).Dispose(); configuration = BuildConfiguration(DomainUpgradeMode.Validate, true); - var exception = Assert.Throws(() => Domain.Build(configuration)); + var exception = Assert.Throws(() => Domain.Build(configuration).Dispose()); Assert.That(exception.ComparisonResult.SchemaComparisonStatus, Is.EqualTo(SchemaComparisonStatus.TargetIsSuperset)); Assert.That(exception.ComparisonResult.Difference.HasChanges, Is.True); } @@ -306,7 +306,7 @@ public void AsyncTest10() Domain.Build(configuration).Dispose(); configuration = BuildConfiguration(DomainUpgradeMode.Validate, true); - var exception = Assert.ThrowsAsync(async () => await Domain.BuildAsync(configuration)); + var exception = Assert.ThrowsAsync(async () => (await Domain.BuildAsync(configuration)).Dispose()); Assert.That(exception.ComparisonResult.SchemaComparisonStatus, Is.EqualTo(SchemaComparisonStatus.TargetIsSuperset)); Assert.That(exception.ComparisonResult.Difference.HasChanges, Is.True); } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/ColumnTypeTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/ColumnTypeTest.cs index f597c876b2..19280b3f46 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/ColumnTypeTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/ColumnTypeTest.cs @@ -558,9 +558,7 @@ private async Task ChangeFieldTypeAsyncTest(string fieldName, private void AddFieldTest(Type newColumnType, object defaultValue = null) { SetUp(); - if (domain != null) { - domain.DisposeSafely(); - } + domain.DisposeSafely(); var configuration = DomainConfigurationFactory.Create(); configuration.UpgradeMode = DomainUpgradeMode.Perform; @@ -577,9 +575,8 @@ private void AddFieldTest(Type newColumnType, object defaultValue = null) private async Task AddFieldAsyncTest(Type newColumnType, object defaultValue = null) { SetUp(); - if (domain != null) { - domain.DisposeSafely(); - } + domain.DisposeSafely(); + var configuration = DomainConfigurationFactory.Create(); configuration.UpgradeMode = DomainUpgradeMode.Perform; configuration.Types.Register(typeof(X)); @@ -595,7 +592,6 @@ private async Task AddFieldAsyncTest(Type newColumnType, object defaultValue = n #endregion } - [Serializable] [HierarchyRoot] public class X : Entity { @@ -725,7 +721,6 @@ public void OnDefinitionsBuilt(BuildingContext context, DomainModelDef model) } } - [Serializable] public class TestUpgrader : UpgradeHandler { private static bool isEnabled = false; diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/ConflictsByTable/ComplexTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/ConflictsByTable/ComplexTest.cs index 5bd8482387..30c5556f5e 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/ConflictsByTable/ComplexTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/ConflictsByTable/ComplexTest.cs @@ -138,7 +138,7 @@ public void Case1PerformSafelyTest(InheritanceSchema inheritanceSchema) RegisterTypes(domainConfig, inheritanceSchema, casePrefix); domainConfig.UpgradeMode = DomainUpgradeMode.PerformSafely; - var exception = Assert.Throws(() => Domain.Build(domainConfig)); + var exception = Assert.Throws(() => Domain.Build(domainConfig).Dispose()); switch (inheritanceSchema) { case InheritanceSchema.ClassTable: { var unsafeActions = exception.ComparisonResult.UnsafeActions; @@ -258,7 +258,7 @@ public void Case2PerformSafelyTest(InheritanceSchema inheritanceSchema) RegisterTypes(domainConfig, inheritanceSchema, casePrefix); domainConfig.UpgradeMode = DomainUpgradeMode.PerformSafely; - var exception = Assert.Throws(() => Domain.Build(domainConfig)); + var exception = Assert.Throws(() => Domain.Build(domainConfig).Dispose()); switch (inheritanceSchema) { case InheritanceSchema.ClassTable: { var unsafeActions = exception.ComparisonResult.UnsafeActions; @@ -391,7 +391,7 @@ public void Case3PerformSafelyTest(InheritanceSchema inheritanceSchema) RegisterTypes(domainConfig, inheritanceSchema, casePrefix); domainConfig.UpgradeMode = DomainUpgradeMode.PerformSafely; - var exception = Assert.Throws(() => Domain.Build(domainConfig)); + var exception = Assert.Throws(() => Domain.Build(domainConfig).Dispose()); switch (inheritanceSchema) { case InheritanceSchema.ClassTable: { var unsafeActions = exception.ComparisonResult.UnsafeActions; @@ -541,7 +541,7 @@ public void Case4PerformSafelyTest(InheritanceSchema inheritanceSchema) RegisterTypes(domainConfig, inheritanceSchema, casePrefix); domainConfig.UpgradeMode = DomainUpgradeMode.PerformSafely; - var exception = Assert.Throws(() => Domain.Build(domainConfig)); + var exception = Assert.Throws(() => Domain.Build(domainConfig).Dispose()); switch (inheritanceSchema) { case InheritanceSchema.ClassTable: { var unsafeActions = exception.ComparisonResult.UnsafeActions; @@ -708,7 +708,7 @@ public void Case5PerformSafelyTest(InheritanceSchema inheritanceSchema) RegisterTypes(domainConfig, inheritanceSchema, casePrefix); domainConfig.UpgradeMode = DomainUpgradeMode.PerformSafely; - var exception = Assert.Throws(() => Domain.Build(domainConfig)); + var exception = Assert.Throws(() => Domain.Build(domainConfig).Dispose()); switch (inheritanceSchema) { case InheritanceSchema.ClassTable: { var unsafeActions = exception.ComparisonResult.UnsafeActions; @@ -887,7 +887,7 @@ public void Case6PerformSafelyTest(InheritanceSchema inheritanceSchema) RegisterTypes(domainConfig, inheritanceSchema, casePrefix); domainConfig.UpgradeMode = DomainUpgradeMode.PerformSafely; - var exception = Assert.Throws(() => Domain.Build(domainConfig)); + var exception = Assert.Throws(() => Domain.Build(domainConfig).Dispose()); switch (inheritanceSchema) { case InheritanceSchema.ClassTable: { var unsafeActions = exception.ComparisonResult.UnsafeActions; @@ -1078,7 +1078,7 @@ public void Case7PerformSafelyTest(InheritanceSchema inheritanceSchema) RegisterTypes(domainConfig, inheritanceSchema, casePrefix); domainConfig.UpgradeMode = DomainUpgradeMode.PerformSafely; - var exception = Assert.Throws(() => Domain.Build(domainConfig)); + var exception = Assert.Throws(() => Domain.Build(domainConfig).Dispose()); switch (inheritanceSchema) { case InheritanceSchema.ClassTable: { var unsafeActions = exception.ComparisonResult.UnsafeActions; @@ -1224,7 +1224,7 @@ public void Case8PerformSafelyTest(InheritanceSchema inheritanceSchema) RegisterTypes(domainConfig, inheritanceSchema, casePrefix); domainConfig.UpgradeMode = DomainUpgradeMode.PerformSafely; - var exception = Assert.Throws(() => Domain.Build(domainConfig)); + var exception = Assert.Throws(() => Domain.Build(domainConfig).Dispose()); switch (inheritanceSchema) { case InheritanceSchema.ClassTable: { var unsafeActions = exception.ComparisonResult.UnsafeActions; diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/DataUpgrade/Model1.cs b/Orm/Xtensive.Orm.Tests/Upgrade/DataUpgrade/Model1.cs index f7809e3a71..edd0eef5ba 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/DataUpgrade/Model1.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/DataUpgrade/Model1.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.Upgrade.DataUpgrade.Model.Version1 { - [Serializable] [HierarchyRoot] public class A : Entity { @@ -16,12 +15,10 @@ public class A : Entity public int Id { get; private set; } } - [Serializable] public class B : A { } - [Serializable] public class C : B { [Field] @@ -31,7 +28,6 @@ public class C : B public B RefB { get; set; } } - [Serializable] public class D : A { [Field] diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/DataUpgrade/Model2.cs b/Orm/Xtensive.Orm.Tests/Upgrade/DataUpgrade/Model2.cs index d23219fd0d..4b8f4c284c 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/DataUpgrade/Model2.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/DataUpgrade/Model2.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.Upgrade.DataUpgrade.Model.Version2 { - [Serializable] [HierarchyRoot] public class A : Entity { @@ -16,14 +15,12 @@ public class A : Entity public int Id { get; private set; } } - [Serializable] public class C : A { [Field] public A RefA { get; set; } } - [Serializable] public class D : A { [Field] diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/DataUpgrade/Upgrader.cs b/Orm/Xtensive.Orm.Tests/Upgrade/DataUpgrade/Upgrader.cs index b40214ac78..674b53af53 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/DataUpgrade/Upgrader.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/DataUpgrade/Upgrader.cs @@ -17,7 +17,6 @@ namespace Xtensive.Orm.Tests.Upgrade.DataUpgrade { - [Serializable] public class Upgrader : UpgradeHandler { private static bool isEnabled = false; diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/DateTimeDataConversions.cs b/Orm/Xtensive.Orm.Tests/Upgrade/DateTimeDataConversions.cs index 0841f8533c..9561715844 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/DateTimeDataConversions.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/DateTimeDataConversions.cs @@ -269,7 +269,7 @@ private void UpgradeAndExpectException() where TExpectedException : Exception { var configuration = BuildConfiguration(DomainUpgradeMode.PerformSafely, typeof(TEntity), GetUpgradeHandler()); - _ = Assert.Throws(() => Domain.Build(configuration)); + _ = Assert.Throws(() => Domain.Build(configuration).Dispose()); } private DomainConfiguration BuildConfiguration(DomainUpgradeMode upgradeMode, Type entityType, Type upgraderType = null) diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/DisableAutoResolveNamespaceConflictsTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/DisableAutoResolveNamespaceConflictsTest.cs index ac33a96108..a6888e8729 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/DisableAutoResolveNamespaceConflictsTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/DisableAutoResolveNamespaceConflictsTest.cs @@ -5,9 +5,6 @@ // Created: 2014.05.29 using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading.Tasks; using NUnit.Framework; using Xtensive.Orm.Configuration; @@ -76,7 +73,7 @@ public void SetUp() var firstModelConfiguration = DomainConfigurationFactory.Create(); firstModelConfiguration.Types.Register(typeof(model1.Foo)); firstModelConfiguration.UpgradeMode = DomainUpgradeMode.Recreate; - BuildDomain(firstModelConfiguration).Dispose(); + using var domain = BuildDomain(firstModelConfiguration); } [Test] @@ -85,7 +82,7 @@ public void UpgradeWhenAutoResolveIsEnabledTest() var secondModelConfiguration = DomainConfigurationFactory.Create(); secondModelConfiguration.Types.Register(typeof(model2.Foo)); secondModelConfiguration.UpgradeMode = DomainUpgradeMode.PerformSafely; - Assert.DoesNotThrow(()=> BuildDomain(secondModelConfiguration)); + Assert.DoesNotThrow(() => BuildDomain(secondModelConfiguration).Dispose()); } [Test] @@ -94,7 +91,7 @@ public void UpgradeWhenAutoResolveIsEnabledAsyncTest() var secondModelConfiguration = DomainConfigurationFactory.Create(); secondModelConfiguration.Types.Register(typeof(model2.Foo)); secondModelConfiguration.UpgradeMode = DomainUpgradeMode.PerformSafely; - Assert.DoesNotThrowAsync(async () => await BuildDomainAsync(secondModelConfiguration)); + Assert.DoesNotThrowAsync(async () => (await BuildDomainAsync(secondModelConfiguration)).Dispose()); } [Test] @@ -105,7 +102,7 @@ public void UpgradeWhenAutoResolveIsDisabledTest() secondModelConfiguration.Types.Register(typeof(model3.Upgrader)); secondModelConfiguration.UpgradeMode = DomainUpgradeMode.PerformSafely; - _ = Assert.Throws(() => BuildDomain(secondModelConfiguration)); + _ = Assert.Throws(() => BuildDomain(secondModelConfiguration).Dispose()); } [Test] @@ -116,7 +113,7 @@ public void UpgradeWhenAutoResolveIsDisabledAsyncTest() secondModelConfiguration.Types.Register(typeof(model3.Upgrader)); secondModelConfiguration.UpgradeMode = DomainUpgradeMode.PerformSafely; - _ = Assert.ThrowsAsync(async () => await BuildDomainAsync(secondModelConfiguration)); + _ = Assert.ThrowsAsync(async () => (await BuildDomainAsync(secondModelConfiguration)).Dispose()); } private Domain BuildDomain(DomainConfiguration configuration) => Domain.Build(configuration); diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/DomainUpgradeSimpleTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/DomainUpgradeSimpleTest.cs index 0df924a398..16b9fdba32 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/DomainUpgradeSimpleTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/DomainUpgradeSimpleTest.cs @@ -11,6 +11,7 @@ using NUnit.Framework; using Xtensive.Core; +using Xtensive.Orm.Configuration; using Xtensive.Orm.Providers; using Xtensive.Orm.Tests.Upgrade.Model.SimpleVersion1; using SimpleVersion1 = Xtensive.Orm.Tests.Upgrade.Model.SimpleVersion1; @@ -20,56 +21,58 @@ namespace Xtensive.Orm.Tests.Upgrade [TestFixture, Category("Upgrade")] public class DomainUpgradeSimpleTest { - private Domain domain; - - [SetUp] - public void SetUp() + [Test] + public void UpgradeTest() { - BuildDomain("SimpleVersion1", DomainUpgradeMode.Recreate); - FillData(); - } + var domain = BuildDomain("SimpleVersion1", DomainUpgradeMode.Recreate); + using (domain) + FillData(domain); - [Test] - public void UpgradeTest() => - BuildDomain("SimpleVersion2", DomainUpgradeMode.PerformSafely); + BuildDomain("SimpleVersion2", DomainUpgradeMode.PerformSafely).Dispose(); + } [Test] - public async Task UpgradeAsyncTest() => - await BuildDomainAsync("SimpleVersion2", DomainUpgradeMode.PerformSafely); + public async Task UpgradeAsyncTest() + { + var domain = BuildDomain("SimpleVersion1", DomainUpgradeMode.Recreate); + using (domain) + FillData(domain); + (await BuildDomainAsync("SimpleVersion2", DomainUpgradeMode.PerformSafely)).Dispose(); + } - private void BuildDomain(string version, DomainUpgradeMode upgradeMode) + private Domain BuildDomain(string version, DomainUpgradeMode upgradeMode) { - if (domain != null) { - domain.DisposeSafely(); - } + var configuration = BuildConfiguration(version, upgradeMode); - var configuration = DomainConfigurationFactory.Create(); - configuration.UpgradeMode = upgradeMode; - configuration.Types.RegisterCaching(Assembly.GetExecutingAssembly(), - "Xtensive.Orm.Tests.Upgrade.Model." + version); - configuration.Types.Register(typeof(SimpleUpgrader)); + Domain domain; using (SimpleUpgrader.Enable(version)) { domain = Domain.Build(configuration); } + return domain; } - private async Task BuildDomainAsync(string version, DomainUpgradeMode upgradeMode) + private async Task BuildDomainAsync(string version, DomainUpgradeMode upgradeMode) { - if (domain != null) { - domain.DisposeSafely(); + var configuration = BuildConfiguration(version, upgradeMode); + + Domain domain; + using (SimpleUpgrader.Enable(version)) { + domain = await Domain.BuildAsync(configuration); } + return domain; + } + private static DomainConfiguration BuildConfiguration(string version, DomainUpgradeMode upgradeMode) + { var configuration = DomainConfigurationFactory.Create(); configuration.UpgradeMode = upgradeMode; configuration.Types.RegisterCaching(Assembly.GetExecutingAssembly(), "Xtensive.Orm.Tests.Upgrade.Model." + version); configuration.Types.Register(typeof(SimpleUpgrader)); - using (SimpleUpgrader.Enable(version)) { - domain = await Domain.BuildAsync(configuration); - } + return configuration; } - private void FillData() + private static void FillData(Domain domain) { using (var session = domain.OpenSession()) using (var transactionScope = session.OpenTransaction()) { @@ -125,7 +128,7 @@ private void FillData() }; // Orders - new Order { + _ = new Order { OrderNumber = "1", Customer = helen, Employee = michael, @@ -133,7 +136,7 @@ private void FillData() OrderDate = new DateTime(1996, 7, 4), ProductName = "Maxilaku" }; - new Order { + _ = new Order { OrderNumber = "2", Customer = helen, Employee = nancy, @@ -141,7 +144,7 @@ private void FillData() OrderDate = new DateTime(1996, 7, 4), ProductName = "Filo Mix" }; - new Order { + _ = new Order { OrderNumber = "3", Customer = philip, Employee = michael, @@ -149,7 +152,7 @@ private void FillData() OrderDate = new DateTime(1996, 7, 4), ProductName = "Tourtiere" }; - new Order { + _ = new Order { OrderNumber = "4", Customer = philip, Employee = nancy, diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/DomainUpgradeTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/DomainUpgradeTest.cs index f3c0abce58..c49fa05136 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/DomainUpgradeTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/DomainUpgradeTest.cs @@ -140,18 +140,18 @@ public void UpgradeModeTest() var syncedTypeSet = ThreeTypesSet; var missingTypeSet = TwoTypesSet; - BuildDomain(1, DomainUpgradeMode.Recreate, missingTypeSet).DisposeSafely(); + BuildDomain(1, DomainUpgradeMode.Recreate, missingTypeSet).Dispose(); - BuildDomain(1, DomainUpgradeMode.PerformSafely, syncedTypeSet).DisposeSafely(); + BuildDomain(1, DomainUpgradeMode.PerformSafely, syncedTypeSet).Dispose(); AssertEx.Throws(() => BuildDomain(1, DomainUpgradeMode.PerformSafely, missingTypeSet)); - BuildDomain(1, DomainUpgradeMode.Validate, syncedTypeSet).DisposeSafely(); + BuildDomain(1, DomainUpgradeMode.Validate, syncedTypeSet).Dispose(); AssertEx.Throws(() => - BuildDomain(1, DomainUpgradeMode.Validate, missingTypeSet)); + BuildDomain(1, DomainUpgradeMode.Validate, missingTypeSet).Dispose()); AssertEx.Throws(() => - BuildDomain(1, DomainUpgradeMode.Validate, OrdersModelTypeSet)); + BuildDomain(1, DomainUpgradeMode.Validate, OrdersModelTypeSet).Dispose()); } [Test] @@ -160,18 +160,18 @@ public async Task UpgradeModeAsyncTest() var syncedTypeSet = ThreeTypesSet; var missingTypeSet = TwoTypesSet; - (await BuildDomainAsync(1, DomainUpgradeMode.Recreate, missingTypeSet).ConfigureAwait(false)).DisposeSafely(); + (await BuildDomainAsync(1, DomainUpgradeMode.Recreate, missingTypeSet).ConfigureAwait(false)).Dispose(); - (await BuildDomainAsync(1, DomainUpgradeMode.PerformSafely, syncedTypeSet).ConfigureAwait(false)).DisposeSafely(); + (await BuildDomainAsync(1, DomainUpgradeMode.PerformSafely, syncedTypeSet).ConfigureAwait(false)).Dispose(); _ = Assert.ThrowsAsync(async () => await BuildDomainAsync(1, DomainUpgradeMode.PerformSafely, missingTypeSet)); - (await BuildDomainAsync(1, DomainUpgradeMode.Validate, syncedTypeSet).ConfigureAwait(false)).DisposeSafely(); + (await BuildDomainAsync(1, DomainUpgradeMode.Validate, syncedTypeSet).ConfigureAwait(false)).Dispose(); _ = Assert.ThrowsAsync(async () => - await BuildDomainAsync(1, DomainUpgradeMode.Validate, missingTypeSet)); + (await BuildDomainAsync(1, DomainUpgradeMode.Validate, missingTypeSet)).Dispose()); _ = Assert.ThrowsAsync(async () => - await BuildDomainAsync(1, DomainUpgradeMode.Validate, OrdersModelTypeSet)); + (await BuildDomainAsync(1, DomainUpgradeMode.Validate, OrdersModelTypeSet)).Dispose()); } [Test] @@ -407,11 +407,13 @@ public void UpgradeToVersion2Test() { Require.ProviderIsNot(StorageProvider.Firebird); - var domain = BuildDomain(1, DomainUpgradeMode.Recreate); - FillData(domain); + using (var domain = BuildDomain(1, DomainUpgradeMode.Recreate)) { + FillData(domain); + } - domain = BuildDomain(2, DomainUpgradeMode.Perform); - TestComplexModelUpgradedData(domain); + using (var domain = BuildDomain(2, DomainUpgradeMode.Perform)) { + TestComplexModelUpgradedData(domain); + } } [Test] @@ -420,11 +422,13 @@ public async Task UpgradeToVersion2AsyncTest() { Require.ProviderIsNot(StorageProvider.Firebird); - var domain = await BuildDomainAsync(1, DomainUpgradeMode.Recreate).ConfigureAwait(false); - FillData(domain); + await using (var domain = await BuildDomainAsync(1, DomainUpgradeMode.Recreate).ConfigureAwait(false)) { + FillData(domain); + } - domain = await BuildDomainAsync(2, DomainUpgradeMode.Perform).ConfigureAwait(false); - TestComplexModelUpgradedData(domain); + await using (var domain = await BuildDomainAsync(2, DomainUpgradeMode.Perform).ConfigureAwait(false)) { + TestComplexModelUpgradedData(domain); + } } private void TestComplexModelUpgradedData(Domain domain) diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/EntitySetUpgrade/ModelVersion1.cs b/Orm/Xtensive.Orm.Tests/Upgrade/EntitySetUpgrade/ModelVersion1.cs index 09acea8a8c..05622b2db9 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/EntitySetUpgrade/ModelVersion1.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/EntitySetUpgrade/ModelVersion1.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.Upgrade.EntitySetUpgradeTest.Model.Version1 { - [Serializable] [HierarchyRoot] public class Person : Entity { @@ -20,7 +19,6 @@ public class Person : Entity public EntitySet
Addresses { get; private set; } } - [Serializable] [HierarchyRoot] public class Address : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/EntitySetUpgrade/ModelVersion2.cs b/Orm/Xtensive.Orm.Tests/Upgrade/EntitySetUpgrade/ModelVersion2.cs index 1f7778977b..4aa703c5f4 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/EntitySetUpgrade/ModelVersion2.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/EntitySetUpgrade/ModelVersion2.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Upgrade.EntitySetUpgradeTest.Model.Version2 { - [Serializable] [HierarchyRoot] public class Person : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/EntitySetUpgrade/Upgrader.cs b/Orm/Xtensive.Orm.Tests/Upgrade/EntitySetUpgrade/Upgrader.cs index b40ed0b66e..7f51a498f6 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/EntitySetUpgrade/Upgrader.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/EntitySetUpgrade/Upgrader.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Tests.Upgrade.EntitySetUpgradeTest { - [Serializable] public class Upgrader : UpgradeHandler { private static bool isEnabled = false; diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/IgnoreHintsTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/IgnoreHintsTest.cs index 4af283b8fd..07ba351265 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/IgnoreHintsTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/IgnoreHintsTest.cs @@ -179,7 +179,6 @@ public void OnDefinitionsBuilt(BuildingContext context, DomainModelDef model) namespace Xtensive.Orm.Tests.Upgrade.IgnoreHints.Model { - [Serializable] [HierarchyRoot] public class A : Entity { @@ -193,7 +192,6 @@ public class A : Entity public string Y { get; set; } } - [Serializable] [HierarchyRoot] public class B : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/LegacyUpgrade/GeneratorUpgrade/SimpleSchemaTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/LegacyUpgrade/GeneratorUpgrade/SimpleSchemaTest.cs index b98d695668..40c82056b9 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/LegacyUpgrade/GeneratorUpgrade/SimpleSchemaTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/LegacyUpgrade/GeneratorUpgrade/SimpleSchemaTest.cs @@ -193,7 +193,7 @@ public void GeneratorSeedIncreasedTest2() var upgradeConfiguration = BuildDomainConfiguration(DomainUpgradeMode.PerformSafely, refModelTypes); InitializeGenerators(upgradeConfiguration, 128, 0); - _ = Assert.Throws(() => Domain.Build(upgradeConfiguration)); + _ = Assert.Throws(() => Domain.Build(upgradeConfiguration).Dispose()); } [Test] @@ -232,7 +232,7 @@ public void GeneratorCacheSizeIncreasedTest2() var upgradeConfiguration = BuildDomainConfiguration(DomainUpgradeMode.PerformSafely, refModelTypes); InitializeGenerators(upgradeConfiguration, 0, 128); - _ = Assert.Throws(() => Domain.Build(upgradeConfiguration)); + _ = Assert.Throws(() => Domain.Build(upgradeConfiguration).Dispose()); } [Test] @@ -271,7 +271,7 @@ public void GeneratorSeedDecreasedTest2() var upgradeConfiguration = BuildDomainConfiguration(DomainUpgradeMode.PerformSafely, refModelTypes); InitializeGenerators(upgradeConfiguration); - _ = Assert.Throws(() => Domain.Build(upgradeConfiguration)); + _ = Assert.Throws(() => Domain.Build(upgradeConfiguration).Dispose()); } [Test] @@ -310,7 +310,7 @@ public void GeneratorCacheSizeDecreasedTest2() var upgradeConfiguration = BuildDomainConfiguration(DomainUpgradeMode.PerformSafely, refModelTypes); InitializeGenerators(upgradeConfiguration); - _ = Assert.Throws(() => Domain.Build(upgradeConfiguration)); + _ = Assert.Throws(() => Domain.Build(upgradeConfiguration).Dispose()); } private void DropExistingSequences() diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/LegacyUpgrade/LegacyUpgradeTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/LegacyUpgrade/LegacyUpgradeTest.cs index 575000b739..3680079df8 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/LegacyUpgrade/LegacyUpgradeTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/LegacyUpgrade/LegacyUpgradeTest.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests.Upgrade.LegacyUpgradeTest.Model { - [Serializable] [HierarchyRoot] public class A : Entity { @@ -22,7 +21,6 @@ public class A : Entity public string Name { get; set; } } - [Serializable] public class B : A { [Field] @@ -32,7 +30,6 @@ public class B : A public C C { get; set; } } - [Serializable] [HierarchyRoot] public class C : Entity { @@ -197,9 +194,9 @@ public void BuildWithInvalidDbTest() config.UpgradeMode = DomainUpgradeMode.LegacyValidate; CreateDb(CreateInvalidDbScript1); - AssertEx.Throws(() => Domain.Build(config)); + AssertEx.Throws(() => Domain.Build(config).Dispose()); CreateDb(CreateInvalidDbScript2); - AssertEx.Throws(() => Domain.Build(config)); + AssertEx.Throws(() => Domain.Build(config).Dispose()); } [Test] diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/ModelConversion/ConvertDomainModelTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/ModelConversion/ConvertDomainModelTest.cs index b4ff83d3c1..42772e2306 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/ModelConversion/ConvertDomainModelTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/ModelConversion/ConvertDomainModelTest.cs @@ -42,8 +42,6 @@ private Domain BuildDomain() configuration.ForeignKeyMode = ForeignKeyMode.Reference; configuration.Types.RegisterCaching(Assembly.GetExecutingAssembly(), typeof (A).Namespace); configuration.Types.Register(typeof (Handler)); - - Domain.DisposeSafely(); return Domain.Build(configuration); } @@ -59,6 +57,7 @@ public virtual void TearDown() { if (Domain != null) { Domain.Dispose(); + Domain = null; } } @@ -124,7 +123,6 @@ public void GeneratorsTest() namespace Xtensive.Orm.Tests.Upgrade.ConvertDomainModel.Model { - [Serializable] [HierarchyRoot(InheritanceSchema = InheritanceSchema.ClassTable)] [Index("Col1", "Col2", Unique = true, IncludedFields = new[] { "Col3" })] public class A : Entity @@ -142,7 +140,6 @@ public class A : Entity public string Col3 { get; private set; } } - [Serializable] [HierarchyRoot(InheritanceSchema = InheritanceSchema.ClassTable)] [Index("ColA", Name = "A_IX")] public class B : Entity @@ -157,7 +154,6 @@ public class B : Entity public A ColA { get; private set; } } - [Serializable] [HierarchyRoot(InheritanceSchema = InheritanceSchema.ClassTable)] public class C : Entity { @@ -168,7 +164,6 @@ public class C : Entity public TimeSpan Col1 { get; private set; } } - [Serializable] [HierarchyRoot(InheritanceSchema = InheritanceSchema.ClassTable)] public class D : Entity { @@ -179,7 +174,6 @@ public class D : Entity public EntitySet ColE { get; private set; } } - [Serializable] [HierarchyRoot(InheritanceSchema = InheritanceSchema.ClassTable)] public class E : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/ModelConversion/ForeignKeysTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/ModelConversion/ForeignKeysTest.cs index 5e117f1348..4e29302cb3 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/ModelConversion/ForeignKeysTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/ModelConversion/ForeignKeysTest.cs @@ -43,7 +43,6 @@ protected override DomainConfiguration BuildConfiguration() } } - [Serializable] public class TargetSchemaVerifier : UpgradeHandler { private static bool isEnabled = false; diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/Models/ModelVersion1.cs b/Orm/Xtensive.Orm.Tests/Upgrade/Models/ModelVersion1.cs index 7346ee75b4..1733ee849d 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/Models/ModelVersion1.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/Models/ModelVersion1.cs @@ -10,7 +10,6 @@ namespace Xtensive.Orm.Tests.Upgrade.Models.Version1 { #region Address, Person, BusinessContact, Employee - [Serializable] public class Address : Structure { [Field(Length = 15)] @@ -20,7 +19,6 @@ public class Address : Structure public string Country { get; set; } } - [Serializable] [HierarchyRoot] public class Person : Entity { @@ -37,7 +35,6 @@ public class Person : Entity public string PassportNumber { get; set; } } - [Serializable] [Index("CompanyName")] public class BusinessContact : Person { @@ -48,7 +45,6 @@ public class BusinessContact : Person public string ContactName { get; set; } } - [Serializable] [Index("FirstName")] [Index("HireDate", "LastName")] public class Employee : Person @@ -74,7 +70,6 @@ public class Employee : Person public string FullName { get { return FirstName + " " + LastName; } } } - [Serializable] [Index("OrderDate")] [Index("Freight")] [HierarchyRoot] @@ -118,7 +113,6 @@ public override string ToString() #region GenericTypes - [Serializable] [HierarchyRoot] public class Sync : Entity where T : Entity @@ -134,7 +128,6 @@ public class Sync : Entity #region Category, Product - [Serializable] [HierarchyRoot] public class Category : Entity { @@ -148,7 +141,6 @@ public class Category : Entity public EntitySet Products { get; private set; } } - [Serializable] [HierarchyRoot] public class Product : Entity { @@ -169,7 +161,6 @@ public class Product : Entity #region Boy, Girl - [Serializable] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] public class Boy : Entity @@ -186,7 +177,6 @@ public Boy(string name) } } - [Serializable] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] public class Girl : Entity @@ -207,7 +197,6 @@ public Girl(string name) #region Crazy association/structure nesting - [Serializable] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] public class Entity1 : Entity @@ -221,7 +210,6 @@ public Entity1(int id) } } - [Serializable] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] public class Entity2 : Entity @@ -238,7 +226,6 @@ public Entity2(int id, Entity1 e1) } } - [Serializable] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] public class Entity3 : Entity @@ -255,7 +242,6 @@ public Entity3(int id, Entity2 e2) } } - [Serializable] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] public class Entity4 : Entity @@ -271,15 +257,13 @@ public Entity4(int id, Entity3 e3) { } } - - [Serializable] + public class Structure1 : Structure { [Field] public Entity1 E1 { get; set; } } - [Serializable] public class Structure2 : Structure { [Field] @@ -289,7 +273,6 @@ public class Structure2 : Structure public Entity2 E2 { get; set; } } - [Serializable] public class Structure3 : Structure { [Field] @@ -299,7 +282,6 @@ public class Structure3 : Structure public Entity3 E3 { get; set; } } - [Serializable] public class Structure4 : Structure { [Field] @@ -308,8 +290,7 @@ public class Structure4 : Structure [Field] public Entity4 E4 { get; set; } } - - [Serializable] + [HierarchyRoot] public class StructureContainer1 : Entity { @@ -320,7 +301,6 @@ public class StructureContainer1 : Entity public Structure1 S1 { get; set; } } - [Serializable] [HierarchyRoot] public class StructureContainer2 : Entity { @@ -331,7 +311,6 @@ public class StructureContainer2 : Entity public Structure2 S2 { get; set; } } - [Serializable] [HierarchyRoot] public class StructureContainer3 : Entity { @@ -342,7 +321,6 @@ public class StructureContainer3 : Entity public Structure3 S3 { get; set; } } - [Serializable] [HierarchyRoot] public class StructureContainer4 : Entity { @@ -357,7 +335,6 @@ public class StructureContainer4 : Entity #region Complex field copy - [Serializable] public class MyStructure : Structure { [Field] @@ -367,7 +344,6 @@ public class MyStructure : Structure public int B { get; set; } } - [Serializable] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] public class MyStructureOwner : Entity @@ -387,7 +363,6 @@ public MyStructureOwner(int id) } } - [Serializable] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] public class ReferencedEntity : Entity diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/Models/ModelVersion2.cs b/Orm/Xtensive.Orm.Tests/Upgrade/Models/ModelVersion2.cs index 6bf3e9e043..d7b16e2013 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/Models/ModelVersion2.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/Models/ModelVersion2.cs @@ -33,7 +33,6 @@ namespace Xtensive.Orm.Tests.Upgrade.Models.Version2 #region Address, BusinessContact, Person, Employee, Order - [Serializable] public class Address : Structure { [Field(Length = 15)] @@ -43,7 +42,6 @@ public class Address : Structure public string Country { get; set; } } - [Serializable] [Index("FirstName")] [HierarchyRoot] public class BusinessContact : Entity @@ -67,7 +65,6 @@ public class BusinessContact : Entity public string FirstName { get; set; } } - [Serializable] [Index("CompanyName")] public class Person : BusinessContact { @@ -78,7 +75,6 @@ public class Person : BusinessContact public string ContactName { get; set; } } - [Serializable] [Index("HireDate")] public class Employee : BusinessContact { @@ -97,7 +93,6 @@ public class Employee : BusinessContact public string FullName { get { return FirstName + " " + LastName; } } } - [Serializable] [Index("OrderDate")] [Index("Freight")] [HierarchyRoot] @@ -138,7 +133,6 @@ public override string ToString() #region GenericTypes - [Serializable] [HierarchyRoot] public class NewSync : Entity where T : Entity @@ -154,7 +148,6 @@ public class NewSync : Entity #region ProductGroup, Product - [Serializable] [HierarchyRoot] public class ProductGroup : Entity { @@ -168,7 +161,6 @@ public class ProductGroup : Entity public EntitySet Products { get; private set; } } - [Serializable] [HierarchyRoot] public class Product : Entity { @@ -189,7 +181,6 @@ public class Product : Entity #region Boy, Girl - [Serializable] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] public class Boy : Entity @@ -206,7 +197,6 @@ public Boy(string name) } } - [Serializable] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] public class Girl : Entity @@ -227,7 +217,6 @@ public Girl(string name) #region Crazy association nesting - [Serializable] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] public class Entity1 : Entity @@ -241,7 +230,6 @@ public Entity1(int id) } } - [Serializable] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] public class Entity2 : Entity @@ -258,7 +246,6 @@ public Entity2(int id, Entity1 e1) } } - [Serializable] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] public class Entity3 : Entity @@ -275,7 +262,6 @@ public Entity3(int id, Entity2 e2) } } - [Serializable] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] public class Entity4 : Entity @@ -291,15 +277,13 @@ public Entity4(int id, Entity3 e3) { } } - - [Serializable] + public class Structure1 : Structure { [Field] public Entity1 MyE1 { get; set; } } - [Serializable] public class Structure2 : Structure { [Field] @@ -309,7 +293,6 @@ public class Structure2 : Structure public Entity2 MyE2 { get; set; } } - [Serializable] public class Structure3 : Structure { [Field] @@ -319,7 +302,6 @@ public class Structure3 : Structure public Entity3 MyE3 { get; set; } } - [Serializable] public class Structure4 : Structure { [Field] @@ -328,8 +310,7 @@ public class Structure4 : Structure [Field] public Entity4 MyE4 { get; set; } } - - [Serializable] + [HierarchyRoot] public class StructureContainer1 : Entity { @@ -340,7 +321,6 @@ public class StructureContainer1 : Entity public Structure1 S1 { get; set; } } - [Serializable] [HierarchyRoot] public class StructureContainer2 : Entity { @@ -351,7 +331,6 @@ public class StructureContainer2 : Entity public Structure2 S2 { get; set; } } - [Serializable] [HierarchyRoot] public class StructureContainer3 : Entity { @@ -362,7 +341,6 @@ public class StructureContainer3 : Entity public Structure3 S3 { get; set; } } - [Serializable] [HierarchyRoot] public class StructureContainer4 : Entity { @@ -377,7 +355,6 @@ public class StructureContainer4 : Entity #region Complex field copy - [Serializable] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] public class MyStructureOwner : Entity @@ -394,7 +371,6 @@ public MyStructureOwner(int id) } } - [Serializable] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] public class ReferencedEntity : Entity diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/Models/ModelVersion3.cs b/Orm/Xtensive.Orm.Tests/Upgrade/Models/ModelVersion3.cs index c2e2ffdaf7..a1d1366f4d 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/Models/ModelVersion3.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/Models/ModelVersion3.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Upgrade.Models.Version3 // Order.Customer field type changed to Contact // Employee removed - [Serializable] public class Address : Structure { [Field(Length = 15)] @@ -22,7 +21,6 @@ public class Address : Structure public string Country { get; set; } } - [Serializable] [HierarchyRoot] public class Person : Entity { @@ -36,7 +34,6 @@ public class Person : Entity public string Phone { get; set; } } - [Serializable] [Index("CompanyName")] [HierarchyRoot] public class Contact : Entity @@ -51,7 +48,6 @@ public class Contact : Entity public string ContactName { get; set; } } - [Serializable] [Index("OrderDate")] [Index("Freight")] [Index("ProductName")] diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/Models/Upgrader.cs b/Orm/Xtensive.Orm.Tests/Upgrade/Models/Upgrader.cs index d3c734e2fc..7fdcb93355 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/Models/Upgrader.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/Models/Upgrader.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Tests.Upgrade.Models { - [Serializable] public class Upgrader : UpgradeHandler { [Flags] diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/Model.cs b/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/Model.cs index 442542e8da..44ac17f6a3 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/Model.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/NewSkip/Model.cs @@ -243,7 +243,6 @@ public XRef(Guid key) { } } - [Serializable] [HierarchyRoot] public class X : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/Recycled/ModelVersion1.cs b/Orm/Xtensive.Orm.Tests/Upgrade/Recycled/ModelVersion1.cs index 40ff1eff73..0c04ca8fe3 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/Recycled/ModelVersion1.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/Recycled/ModelVersion1.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.Upgrade.Recycled.Model.Version1 { - [Serializable] [HierarchyRoot] public class Customer : Entity { @@ -25,7 +24,6 @@ public class Customer : Entity public string Name{ get; set;} } - [Serializable] [HierarchyRoot] public class Employee : Entity { @@ -39,7 +37,6 @@ public class Employee : Entity public string Name { get; set; } } - [Serializable] [HierarchyRoot] public class Order : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/Recycled/ModelVersion2.cs b/Orm/Xtensive.Orm.Tests/Upgrade/Recycled/ModelVersion2.cs index c8ad87ec9a..ed9832ca25 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/Recycled/ModelVersion2.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/Recycled/ModelVersion2.cs @@ -9,7 +9,6 @@ namespace Xtensive.Orm.Tests.Upgrade.Recycled.Model.Version2 { - [Serializable] [HierarchyRoot] public class Person : Entity { @@ -32,7 +31,6 @@ public Person(int id) } } - [Serializable] public class Customer : Person { [Field(Length = 256)] @@ -54,7 +52,6 @@ public Customer(int id) } } - [Serializable] public class Employee : Person { [Field(Length = 30)] @@ -73,7 +70,6 @@ public Employee(int id) } } - [Serializable] [HierarchyRoot] public class Order : Entity { @@ -104,7 +100,6 @@ public override string ToString() } } - [Serializable] [Recycled("Xtensive.Orm.Tests.Upgrade.Recycled.Model.Version1.Customer")] [HierarchyRoot] public class RcCustomer : Entity @@ -122,7 +117,6 @@ public class RcCustomer : Entity public string Name{ get; set;} } - [Serializable] [Recycled("Xtensive.Orm.Tests.Upgrade.Recycled.Model.Version1.Employee")] [HierarchyRoot] public class RcEmployee : Entity diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/Recycled/Upgrader.cs b/Orm/Xtensive.Orm.Tests/Upgrade/Recycled/Upgrader.cs index 91a3be54ec..e161e74fa5 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/Recycled/Upgrader.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/Recycled/Upgrader.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Upgrade.Recycled { - [Serializable] public class Upgrader : UpgradeHandler { private static bool isEnabled = false; diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/Sample3/ModelVersion1.cs b/Orm/Xtensive.Orm.Tests/Upgrade/Sample3/ModelVersion1.cs index 211931355e..255e2a0630 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/Sample3/ModelVersion1.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/Sample3/ModelVersion1.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.Upgrade.Sample3.Model.Version1 { - [Serializable] [HierarchyRoot] public abstract class Person : Entity { @@ -27,7 +26,6 @@ public abstract class Person : Entity public string ContactPhone { get; set; } } - [Serializable] public class Employee : Person { [Field] @@ -42,7 +40,6 @@ public override string ToString() } } - [Serializable] [HierarchyRoot] public class Order : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/Sample3/ModelVersion2.cs b/Orm/Xtensive.Orm.Tests/Upgrade/Sample3/ModelVersion2.cs index b196d4bfdb..258759254b 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/Sample3/ModelVersion2.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/Sample3/ModelVersion2.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Upgrade.Sample3.Model.Version2 { - [Serializable] [HierarchyRoot] public abstract class Person : Entity { @@ -32,7 +31,6 @@ public abstract class Person : Entity public string ContactPhone { get; set; } } - [Serializable] public class Employee : Person { [Field, Obsolete, Recycled("Department")] @@ -45,7 +43,6 @@ public class Employee : Person public string DepartmentName { get; set; } } - [Serializable] [HierarchyRoot] public class Order : Entity { @@ -75,7 +72,6 @@ public override string ToString() } - [Serializable] [HierarchyRoot] public class OrderItem : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/Sample3/Upgrader.cs b/Orm/Xtensive.Orm.Tests/Upgrade/Sample3/Upgrader.cs index ab7f92693d..ec337be357 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/Sample3/Upgrader.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/Sample3/Upgrader.cs @@ -16,7 +16,6 @@ namespace Xtensive.Orm.Tests.Upgrade.Sample3 { - [Serializable] public class Upgrader : UpgradeHandler { private static bool isEnabled = false; diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SimpleModelVersion1.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SimpleModelVersion1.cs index 562166f5c1..9bf997b059 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SimpleModelVersion1.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SimpleModelVersion1.cs @@ -9,7 +9,6 @@ namespace Xtensive.Orm.Tests.Upgrade.Model.SimpleVersion1 { - [Serializable] public class Address : Structure { [Field(Length = 15)] @@ -19,7 +18,6 @@ public class Address : Structure public string Country { get; set; } } - [Serializable] [HierarchyRoot] public class Person : Entity { @@ -36,7 +34,6 @@ public class Person : Entity public string PassportNumber { get; set; } } - [Serializable] [Index("CompanyName")] public class BusinessContact : Person { @@ -47,7 +44,6 @@ public class BusinessContact : Person public string ContactName { get; set; } } - [Serializable] [Index("FirstName")] [Index("HireDate", "LastName")] public class Employee : Person @@ -76,7 +72,6 @@ public class Employee : Person public string FullName { get { return FirstName + " " + LastName; } } } - [Serializable] [Index("OrderDate")] [Index("Freight")] [HierarchyRoot] diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SimpleModelVersion2.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SimpleModelVersion2.cs index 76e8c7971c..28b47c717a 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SimpleModelVersion2.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SimpleModelVersion2.cs @@ -17,7 +17,6 @@ namespace Xtensive.Orm.Tests.Upgrade.Model.SimpleVersion2 // Type of field Order.Number changed to int // Type of field BusinessContact.PassportNumber (old Person.PassportNumber) changed to int - [Serializable] public class Address : Structure { [Field(Length = 15)] @@ -27,7 +26,6 @@ public class Address : Structure public string Country { get; set; } } - [Serializable] [Index("FirstName")] [HierarchyRoot] public class BusinessContact : Entity @@ -51,7 +49,6 @@ public class BusinessContact : Entity public string FirstName { get; set; } } - [Serializable] [Index("CompanyName")] public class Person : BusinessContact { @@ -62,7 +59,6 @@ public class Person : BusinessContact public string ContactName { get; set; } } - [Serializable] [Index("HireDate")] public class Employee : BusinessContact { @@ -84,7 +80,6 @@ public class Employee : BusinessContact public string FullName { get { return FirstName + " " + LastName; } } } - [Serializable] [Index("OrderDate")] [Index("Freight")] [HierarchyRoot] diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/SimpleUpgrader.cs b/Orm/Xtensive.Orm.Tests/Upgrade/SimpleUpgrader.cs index 9cd472ab48..190ca13e56 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/SimpleUpgrader.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/SimpleUpgrader.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Tests.Upgrade { - [Serializable] public class SimpleUpgrader : UpgradeHandler { private static bool isEnabled = false; diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/TwoUpgradeHandlersTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/TwoUpgradeHandlersTest.cs index f4a8265b8c..e4760d3c37 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/TwoUpgradeHandlersTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/TwoUpgradeHandlersTest.cs @@ -31,7 +31,7 @@ public void MainTest() var configuration = DomainConfigurationFactory.Create(); configuration.Types.Register(typeof(UpgradeHandler1)); configuration.Types.Register(typeof(UpgradeHandler2)); - _ = Assert.Throws(() => Domain.Build(configuration)); + _ = Assert.Throws(() => Domain.Build(configuration).Dispose()); } [Test] @@ -40,7 +40,7 @@ public void MainAsyncTest() var configuration = DomainConfigurationFactory.Create(); configuration.Types.Register(typeof(UpgradeHandler1)); configuration.Types.Register(typeof(UpgradeHandler2)); - _ = Assert.ThrowsAsync(async () => await Domain.BuildAsync(configuration)); + _ = Assert.ThrowsAsync(async () => (await Domain.BuildAsync(configuration)).Dispose()); } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/TypeIdUpgrade/Many2SingleClassTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/TypeIdUpgrade/Many2SingleClassTest.cs index edeacbcf27..cb2192183b 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/TypeIdUpgrade/Many2SingleClassTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/TypeIdUpgrade/Many2SingleClassTest.cs @@ -22,6 +22,7 @@ public void CombinedTest() configuration.Types.Register(typeof(Model.Employee)); var domain = Domain.Build(configuration); + using (domain) using (var session = domain.OpenSession()) using (var t = session.OpenTransaction()) { _ = new Model.Person() { @@ -46,6 +47,7 @@ public void CombinedTest() using (Upgrader.Enable()) domain = Domain.Build(configuration); + using (domain) using (var session = domain.OpenSession()) using (var t = session.OpenTransaction()) { var count = session.Query.All().Count(); diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/TypeIdUpgrade/Model.cs b/Orm/Xtensive.Orm.Tests/Upgrade/TypeIdUpgrade/Model.cs index e191a5cc29..467877d589 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/TypeIdUpgrade/Model.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/TypeIdUpgrade/Model.cs @@ -9,7 +9,6 @@ namespace Xtensive.Orm.Tests.Upgrade.TypeIdUpgrade.Model { - [Serializable] [HierarchyRoot] public class Person : Entity { @@ -23,7 +22,6 @@ public class Person : Entity public string LastName { get; set; } } - [Serializable] public class Employee : Person { [Field] diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/TypeIdUpgrade/Single2ManyClassesTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/TypeIdUpgrade/Single2ManyClassesTest.cs index adbfe937ca..df2dfcd08e 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/TypeIdUpgrade/Single2ManyClassesTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/TypeIdUpgrade/Single2ManyClassesTest.cs @@ -20,6 +20,7 @@ public void CombinedTest() configuration.Types.Register(typeof(Model.Person)); var domain = Domain.Build(configuration); + using (domain) using (var session = domain.OpenSession()) using (var t = session.OpenTransaction()) { var person = new Model.Person() { @@ -34,6 +35,7 @@ public void CombinedTest() configuration.Types.Register(typeof(Model.Employee)); domain = Domain.Build(configuration); + using (domain) using (var session = domain.OpenSession()) using (var t = session.OpenTransaction()) { var person = new Model.Person() { diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/TypeIdUpgrade/VersionUpgradeTest.cs b/Orm/Xtensive.Orm.Tests/Upgrade/TypeIdUpgrade/VersionUpgradeTest.cs index e658e36ccd..e17dfb7a48 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/TypeIdUpgrade/VersionUpgradeTest.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/TypeIdUpgrade/VersionUpgradeTest.cs @@ -29,38 +29,40 @@ public void NoChangesTest() configuration.Types.Register(typeof(Model.Employee)); var domain = Domain.Build(configuration); - using (var session = domain.OpenSession()) - using (var t = session.OpenTransaction()) { - new Model.Person() { - FirstName = "Alex", - LastName = "Kochetov" - }; - new Model.Person() { - FirstName = "Alex", - LastName = "Gamzov" - }; - new Model.Employee() { - FirstName = "Dmitri", - LastName = "Maximov" - }; - t.Complete(); - } - - using (var session = domain.OpenSession(SessionType.System)) - using (var t = session.OpenTransaction()) { - var handler = (SqlSessionHandler) session.Handler; - var connection = handler.Connection; - var command = connection.CreateCommand(string.Format( - "ALTER TABLE [dbo].[Metadata.Assembly] ADD [TypeId] integer NOT NULL DEFAULT({0});" + - "ALTER TABLE [dbo].[Metadata.Extension] ADD [TypeId] integer NOT NULL DEFAULT({1});" + - "ALTER TABLE [dbo].[Metadata.Type] ADD [TypeId] integer NOT NULL DEFAULT({2});" + - "CREATE UNIQUE INDEX [Type.IX_Name] ON [dbo].[Metadata.Type] ([Name]) INCLUDE (TypeId) WITH (FILLFACTOR = 80, PAD_INDEX = ON, DROP_EXISTING = ON)", - domain.Model.Types[typeof(Metadata.Assembly)].TypeId, - domain.Model.Types[typeof(Metadata.Extension)].TypeId, - domain.Model.Types[typeof(Metadata.Type)].TypeId)); - command.Transaction = connection.ActiveTransaction; - command.ExecuteNonQuery(); - t.Complete(); + using (domain) { + using (var session = domain.OpenSession()) + using (var t = session.OpenTransaction()) { + _ = new Model.Person() { + FirstName = "Alex", + LastName = "Kochetov" + }; + _ = new Model.Person() { + FirstName = "Alex", + LastName = "Gamzov" + }; + _ = new Model.Employee() { + FirstName = "Dmitri", + LastName = "Maximov" + }; + t.Complete(); + } + + using (var session = domain.OpenSession(SessionType.System)) + using (var t = session.OpenTransaction()) { + var handler = (SqlSessionHandler) session.Handler; + var connection = handler.Connection; + var command = connection.CreateCommand(string.Format( + "ALTER TABLE [dbo].[Metadata.Assembly] ADD [TypeId] integer NOT NULL DEFAULT({0});" + + "ALTER TABLE [dbo].[Metadata.Extension] ADD [TypeId] integer NOT NULL DEFAULT({1});" + + "ALTER TABLE [dbo].[Metadata.Type] ADD [TypeId] integer NOT NULL DEFAULT({2});" + + "CREATE UNIQUE INDEX [Type.IX_Name] ON [dbo].[Metadata.Type] ([Name]) INCLUDE (TypeId) WITH (FILLFACTOR = 80, PAD_INDEX = ON, DROP_EXISTING = ON)", + domain.Model.Types[typeof(Metadata.Assembly)].TypeId, + domain.Model.Types[typeof(Metadata.Extension)].TypeId, + domain.Model.Types[typeof(Metadata.Type)].TypeId)); + command.Transaction = connection.ActiveTransaction; + _ = command.ExecuteNonQuery(); + t.Complete(); + } } configuration = DomainConfigurationFactory.Create(); @@ -69,15 +71,17 @@ public void NoChangesTest() configuration.Types.Register(typeof(Model.Employee)); domain = Domain.Build(configuration); - using (var session = domain.OpenSession()) - using (var t = session.OpenTransaction()) { - var count = session.Query.All().Count(); - Assert.That(count, Is.EqualTo(3)); - var list = session.Query.All().ToList(); - Assert.That(list.Count, Is.EqualTo(3)); - foreach (var item in list) - Assert.That(item, Is.Not.Null); - t.Complete(); + using (domain) { + using (var session = domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var count = session.Query.All().Count(); + Assert.That(count, Is.EqualTo(3)); + var list = session.Query.All().ToList(); + Assert.That(list.Count, Is.EqualTo(3)); + foreach (var item in list) + Assert.That(item, Is.Not.Null); + t.Complete(); + } } } @@ -89,36 +93,38 @@ public void TypeAddTest() configuration.Types.Register(typeof(Model.Person)); var domain = Domain.Build(configuration); - using (var session = domain.OpenSession()) - using (var t = session.OpenTransaction()) { - new Model.Person() { - FirstName = "Alex", - LastName = "Kochetov" - }; - new Model.Person() { - FirstName = "Alex", - LastName = "Gamzov" - }; - t.Complete(); - } - - using (var session = domain.OpenSession(SessionType.System)) - using (var t = session.OpenTransaction()) { - var handler = (SqlSessionHandler) session.Handler; - var connection = handler.Connection; - var command = connection.CreateCommand(string.Format( - "ALTER TABLE [dbo].[Person] ADD [TypeId] integer NOT NULL DEFAULT({0});" + - "ALTER TABLE [dbo].[Metadata.Assembly] ADD [TypeId] integer NOT NULL DEFAULT({1});" + - "ALTER TABLE [dbo].[Metadata.Extension] ADD [TypeId] integer NOT NULL DEFAULT({2});" + - "ALTER TABLE [dbo].[Metadata.Type] ADD [TypeId] integer NOT NULL DEFAULT({3});" + - "CREATE UNIQUE INDEX [Type.IX_Name] ON [dbo].[Metadata.Type] ([Name]) INCLUDE (TypeId) WITH (FILLFACTOR = 80, PAD_INDEX = ON, DROP_EXISTING = ON)", - domain.Model.Types[typeof(Model.Person)].TypeId, - domain.Model.Types[typeof(Metadata.Assembly)].TypeId, - domain.Model.Types[typeof(Metadata.Extension)].TypeId, - domain.Model.Types[typeof(Metadata.Type)].TypeId)); - command.Transaction = connection.ActiveTransaction; - command.ExecuteNonQuery(); - t.Complete(); + using (domain) { + using (var session = domain.OpenSession()) + using (var t = session.OpenTransaction()) { + _ = new Model.Person() { + FirstName = "Alex", + LastName = "Kochetov" + }; + _ = new Model.Person() { + FirstName = "Alex", + LastName = "Gamzov" + }; + t.Complete(); + } + + using (var session = domain.OpenSession(SessionType.System)) + using (var t = session.OpenTransaction()) { + var handler = (SqlSessionHandler) session.Handler; + var connection = handler.Connection; + var command = connection.CreateCommand(string.Format( + "ALTER TABLE [dbo].[Person] ADD [TypeId] integer NOT NULL DEFAULT({0});" + + "ALTER TABLE [dbo].[Metadata.Assembly] ADD [TypeId] integer NOT NULL DEFAULT({1});" + + "ALTER TABLE [dbo].[Metadata.Extension] ADD [TypeId] integer NOT NULL DEFAULT({2});" + + "ALTER TABLE [dbo].[Metadata.Type] ADD [TypeId] integer NOT NULL DEFAULT({3});" + + "CREATE UNIQUE INDEX [Type.IX_Name] ON [dbo].[Metadata.Type] ([Name]) INCLUDE (TypeId) WITH (FILLFACTOR = 80, PAD_INDEX = ON, DROP_EXISTING = ON)", + domain.Model.Types[typeof(Model.Person)].TypeId, + domain.Model.Types[typeof(Metadata.Assembly)].TypeId, + domain.Model.Types[typeof(Metadata.Extension)].TypeId, + domain.Model.Types[typeof(Metadata.Type)].TypeId)); + command.Transaction = connection.ActiveTransaction; + _ = command.ExecuteNonQuery(); + t.Complete(); + } } configuration = DomainConfigurationFactory.Create(); @@ -127,15 +133,17 @@ public void TypeAddTest() configuration.Types.Register(typeof(Model.Employee)); domain = Domain.Build(configuration); - using (var session = domain.OpenSession()) - using (var t = session.OpenTransaction()) { - var count = session.Query.All().Count(); - Assert.That(count, Is.EqualTo(2)); - var list = session.Query.All().ToList(); - Assert.That(list.Count, Is.EqualTo(2)); - foreach (var item in list) - Assert.That(item, Is.Not.Null); - t.Complete(); + using (domain) { + using (var session = domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var count = session.Query.All().Count(); + Assert.That(count, Is.EqualTo(2)); + var list = session.Query.All().ToList(); + Assert.That(list.Count, Is.EqualTo(2)); + foreach (var item in list) + Assert.That(item, Is.Not.Null); + t.Complete(); + } } } @@ -148,38 +156,40 @@ public void TypeRemovalTest() configuration.Types.Register(typeof(Model.Employee)); var domain = Domain.Build(configuration); - using (var session = domain.OpenSession()) - using (var t = session.OpenTransaction()) { - new Model.Person() { - FirstName = "Alex", - LastName = "Kochetov" - }; - new Model.Person() { - FirstName = "Alex", - LastName = "Gamzov" - }; - new Model.Employee() { - FirstName = "Dmitri", - LastName = "Maximov" - }; - t.Complete(); - } - - using (var session = domain.OpenSession(SessionType.System)) - using (var t = session.OpenTransaction()) { - var handler = (SqlSessionHandler) session.Handler; - var connection = handler.Connection; - var command = connection.CreateCommand(string.Format( - "ALTER TABLE [dbo].[Metadata.Assembly] ADD [TypeId] integer NOT NULL DEFAULT({0});" + - "ALTER TABLE [dbo].[Metadata.Extension] ADD [TypeId] integer NOT NULL DEFAULT({1});" + - "ALTER TABLE [dbo].[Metadata.Type] ADD [TypeId] integer NOT NULL DEFAULT({2});" + - "CREATE UNIQUE INDEX [Type.IX_Name] ON [dbo].[Metadata.Type] ([Name]) INCLUDE (TypeId) WITH (FILLFACTOR = 80, PAD_INDEX = ON, DROP_EXISTING = ON)", - domain.Model.Types[typeof(Metadata.Assembly)].TypeId, - domain.Model.Types[typeof(Metadata.Extension)].TypeId, - domain.Model.Types[typeof(Metadata.Type)].TypeId)); - command.Transaction = connection.ActiveTransaction; - command.ExecuteNonQuery(); - t.Complete(); + using (domain) { + using (var session = domain.OpenSession()) + using (var t = session.OpenTransaction()) { + _ = new Model.Person() { + FirstName = "Alex", + LastName = "Kochetov" + }; + _ = new Model.Person() { + FirstName = "Alex", + LastName = "Gamzov" + }; + _ = new Model.Employee() { + FirstName = "Dmitri", + LastName = "Maximov" + }; + t.Complete(); + } + + using (var session = domain.OpenSession(SessionType.System)) + using (var t = session.OpenTransaction()) { + var handler = (SqlSessionHandler) session.Handler; + var connection = handler.Connection; + var command = connection.CreateCommand(string.Format( + "ALTER TABLE [dbo].[Metadata.Assembly] ADD [TypeId] integer NOT NULL DEFAULT({0});" + + "ALTER TABLE [dbo].[Metadata.Extension] ADD [TypeId] integer NOT NULL DEFAULT({1});" + + "ALTER TABLE [dbo].[Metadata.Type] ADD [TypeId] integer NOT NULL DEFAULT({2});" + + "CREATE UNIQUE INDEX [Type.IX_Name] ON [dbo].[Metadata.Type] ([Name]) INCLUDE (TypeId) WITH (FILLFACTOR = 80, PAD_INDEX = ON, DROP_EXISTING = ON)", + domain.Model.Types[typeof(Metadata.Assembly)].TypeId, + domain.Model.Types[typeof(Metadata.Extension)].TypeId, + domain.Model.Types[typeof(Metadata.Type)].TypeId)); + command.Transaction = connection.ActiveTransaction; + _ = command.ExecuteNonQuery(); + t.Complete(); + } } configuration = DomainConfigurationFactory.Create(); @@ -189,15 +199,17 @@ public void TypeRemovalTest() using (Upgrader.Enable()) domain = Domain.Build(configuration); - using (var session = domain.OpenSession()) - using (var t = session.OpenTransaction()) { - var count = session.Query.All().Count(); - Assert.That(count, Is.EqualTo(2)); - var list = session.Query.All().ToList(); - Assert.That(list.Count, Is.EqualTo(2)); - foreach (var item in list) - Assert.That(item, Is.Not.Null); - t.Complete(); + using (domain) { + using (var session = domain.OpenSession()) + using (var t = session.OpenTransaction()) { + var count = session.Query.All().Count(); + Assert.That(count, Is.EqualTo(2)); + var list = session.Query.All().ToList(); + Assert.That(list.Count, Is.EqualTo(2)); + foreach (var item in list) + Assert.That(item, Is.Not.Null); + t.Complete(); + } } } } diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeAndNamingRules/ModelVersion1.cs b/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeAndNamingRules/ModelVersion1.cs index ca165f974c..a60163816a 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeAndNamingRules/ModelVersion1.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeAndNamingRules/ModelVersion1.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.Upgrade.UpgradeAndNamingRules.Model.Version1 { - [Serializable] [HierarchyRoot] public class Person : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeAndNamingRules/ModelVersion2.cs b/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeAndNamingRules/ModelVersion2.cs index 7b748f3204..47c533ca1c 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeAndNamingRules/ModelVersion2.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeAndNamingRules/ModelVersion2.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.Upgrade.UpgradeAndNamingRules.Model.Version2 { - [Serializable] [HierarchyRoot] public class Person : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeAndNamingRules/Upgrader.cs b/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeAndNamingRules/Upgrader.cs index fba35f6759..f0677be18b 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeAndNamingRules/Upgrader.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeAndNamingRules/Upgrader.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Tests.Upgrade.UpgradeAndNamingRules { - [Serializable] public class Upgrader : UpgradeHandler { private static bool isEnabled = false; diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeToStructure/ModelVersion1.cs b/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeToStructure/ModelVersion1.cs index ae8ea5a4d7..3884dc4d23 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeToStructure/ModelVersion1.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeToStructure/ModelVersion1.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Tests.Upgrade.UpgradeToStructure.Model.Version1 { - [Serializable] [HierarchyRoot] public class Person : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeToStructure/ModelVersion2.cs b/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeToStructure/ModelVersion2.cs index 54207118b2..988b2cda05 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeToStructure/ModelVersion2.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeToStructure/ModelVersion2.cs @@ -8,14 +8,12 @@ namespace Xtensive.Orm.Tests.Upgrade.UpgradeToStructure.Model.Version2 { - [Serializable] public class PersonInfo : Structure { [Field] public string Title { get; set; } } - [Serializable] [HierarchyRoot] public class Person : Entity { diff --git a/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeToStructure/Upgrader.cs b/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeToStructure/Upgrader.cs index 965e849cef..c91806c537 100644 --- a/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeToStructure/Upgrader.cs +++ b/Orm/Xtensive.Orm.Tests/Upgrade/UpgradeToStructure/Upgrader.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Tests.Upgrade.UpgradeToStructure { - [Serializable] public class Upgrader : UpgradeHandler { private static bool isEnabled = false; diff --git a/Orm/Xtensive.Orm.Tests/_Manual/Validation/Person.cs b/Orm/Xtensive.Orm.Tests/_Manual/Validation/Person.cs index 937d29ada9..bb231318b5 100644 --- a/Orm/Xtensive.Orm.Tests/_Manual/Validation/Person.cs +++ b/Orm/Xtensive.Orm.Tests/_Manual/Validation/Person.cs @@ -1,16 +1,14 @@ -// Copyright (C) 2003-2010 Xtensive LLC. +// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Alex Kofman // Created: 2009.10.27 using System; -using Xtensive.Orm.Tests._Manual.Validation; using Xtensive.Orm.Validation; namespace Xtensive.Orm.Tests._Manual.Validation { - [Serializable] [HierarchyRoot] public class Person : Entity { diff --git a/Orm/Xtensive.Orm.Tests/_Manual/Validation/PhoneNumberConstraint.cs b/Orm/Xtensive.Orm.Tests/_Manual/Validation/PhoneNumberConstraint.cs index affab2c779..fc2f68b84d 100644 --- a/Orm/Xtensive.Orm.Tests/_Manual/Validation/PhoneNumberConstraint.cs +++ b/Orm/Xtensive.Orm.Tests/_Manual/Validation/PhoneNumberConstraint.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Tests._Manual.Validation { - [Serializable] public class PhoneNumberConstraint : PropertyValidator { private const string PhoneNumberPattern = "^[2-9]\\d{2}-\\d{3}-\\d{4}$"; diff --git a/Orm/Xtensive.Orm/Arithmetic/Arithmetic.cs b/Orm/Xtensive.Orm/Arithmetic/Arithmetic.cs index dae2b7b2b5..dbcce9a0d4 100644 --- a/Orm/Xtensive.Orm/Arithmetic/Arithmetic.cs +++ b/Orm/Xtensive.Orm/Arithmetic/Arithmetic.cs @@ -6,7 +6,6 @@ using System; using System.Diagnostics; -using System.Runtime.Serialization; using System.Threading; using Xtensive.Core; @@ -18,10 +17,9 @@ namespace Xtensive.Arithmetic /// Provides delegates allowing to call methods faster. /// /// The type of generic argument. - [Serializable] public sealed class Arithmetic : MethodCacheBase> { - private static Lazy> cached = + private readonly static Lazy> cached = new Lazy>(() => ArithmeticProvider.Default.GetArithmetic()); /// @@ -99,28 +97,6 @@ public static Arithmetic Default { // Constructors - /// - /// Initializes new instance of this type. - /// - /// The info. - /// The context. - public Arithmetic(SerializationInfo info, StreamingContext context) - : base(info, context) - { - Provider = Implementation.Provider; - Zero = Implementation.Zero; - One = Implementation.One; - MaxValue = Implementation.MaxValue; - MinValue = Implementation.MinValue; - IsSigned = Implementation.IsSigned; - Add = Implementation.Add; - Subtract = Implementation.Subtract; - Multiply = Implementation.Multiply; - Divide = Implementation.Divide; - Negation = Implementation.Negation; - ApplyRules = Implementation.ApplyRules; - } - /// /// Initializes new instance of this type. /// diff --git a/Orm/Xtensive.Orm/Arithmetic/ArithmeticBase.cs b/Orm/Xtensive.Orm/Arithmetic/ArithmeticBase.cs index dbe159dfc3..5e7d8e7a0c 100644 --- a/Orm/Xtensive.Orm/Arithmetic/ArithmeticBase.cs +++ b/Orm/Xtensive.Orm/Arithmetic/ArithmeticBase.cs @@ -6,12 +6,6 @@ using System; using System.Collections.Concurrent; -using System.Diagnostics; -using System.Runtime.Serialization; -using Xtensive.Collections; -using Xtensive.Core; - - namespace Xtensive.Arithmetic { @@ -19,29 +13,21 @@ namespace Xtensive.Arithmetic /// Base class for implementations. /// /// Type to provide arithmetic operations for. - [Serializable] - public abstract class ArithmeticBase : IArithmetic, - IDeserializationCallback + public abstract class ArithmeticBase : IArithmetic { - private IArithmeticProvider provider; - - [NonSerialized] - private ConcurrentDictionary<(ArithmeticRules, ArithmeticBase), Arithmetic> cachedArithmetics = - new ConcurrentDictionary<(ArithmeticRules, ArithmeticBase), Arithmetic>(); + private readonly ConcurrentDictionary<(ArithmeticRules, ArithmeticBase), Arithmetic> cachedArithmetics = new(); /// /// Indicates whether overflow is allowed (doesn't lead to an exception) /// on arithmetic operations. /// - [NonSerialized] - protected bool OverflowAllowed; + protected readonly bool OverflowAllowed; /// /// Indicates whether value is threated as zero /// in arithmetic operations. /// - [NonSerialized] - protected bool NullIsZero; + protected readonly bool NullIsZero; /// /// Gets used by this arithmetic. @@ -49,11 +35,7 @@ public abstract class ArithmeticBase : IArithmetic, protected readonly ArithmeticRules Rules; /// - public IArithmeticProvider Provider - { - [DebuggerStepThrough] - get { return provider; } - } + public IArithmeticProvider Provider { get; } /// public abstract T Zero { get; } @@ -117,23 +99,10 @@ public Arithmetic ApplyRules(ArithmeticRules rules) /// Arithmetic rules. public ArithmeticBase(IArithmeticProvider provider, ArithmeticRules rules) { - this.provider = provider ?? throw new ArgumentNullException(nameof(provider)); + Provider = provider ?? throw new ArgumentNullException(nameof(provider)); Rules = rules; - OverflowAllowed = (rules.OverflowBehavior==OverflowBehavior.AllowOverflow); - NullIsZero = (rules.NullBehavior==NullBehavior.ThreatNullAsZero); - } - - /// - /// Performs post-deserialization actions. - /// - /// - public virtual void OnDeserialization(object sender) - { - if (provider==null || provider.GetType()==typeof (ArithmeticProvider)) - provider = ArithmeticProvider.Default; - OverflowAllowed = (Rules.OverflowBehavior==OverflowBehavior.AllowOverflow); - NullIsZero = (Rules.NullBehavior==NullBehavior.ThreatNullAsZero); - cachedArithmetics = new ConcurrentDictionary<(ArithmeticRules, ArithmeticBase), Arithmetic>(); + OverflowAllowed = (rules.OverflowBehavior is OverflowBehavior.AllowOverflow); + NullIsZero = (rules.NullBehavior is NullBehavior.ThreatNullAsZero); } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Arithmetic/ArithmeticProvider.cs b/Orm/Xtensive.Orm/Arithmetic/ArithmeticProvider.cs index a862dff99b..7b4ef040c2 100644 --- a/Orm/Xtensive.Orm/Arithmetic/ArithmeticProvider.cs +++ b/Orm/Xtensive.Orm/Arithmetic/ArithmeticProvider.cs @@ -28,7 +28,6 @@ namespace Xtensive.Arithmetic /// /// /// - [Serializable] public class ArithmeticProvider : AssociateProvider, IArithmeticProvider { diff --git a/Orm/Xtensive.Orm/Arithmetic/ArithmeticRules.cs b/Orm/Xtensive.Orm/Arithmetic/ArithmeticRules.cs index 020f3759ca..956011b880 100644 --- a/Orm/Xtensive.Orm/Arithmetic/ArithmeticRules.cs +++ b/Orm/Xtensive.Orm/Arithmetic/ArithmeticRules.cs @@ -11,7 +11,6 @@ namespace Xtensive.Arithmetic /// /// Describes how to calculate arithmetics. /// - [Serializable] public struct ArithmeticRules : IEquatable { private readonly OverflowBehavior overflowBehavior; diff --git a/Orm/Xtensive.Orm/Arithmetic/ArithmeticStruct.cs b/Orm/Xtensive.Orm/Arithmetic/ArithmeticStruct.cs index c28d00273c..0d7cea03c1 100644 --- a/Orm/Xtensive.Orm/Arithmetic/ArithmeticStruct.cs +++ b/Orm/Xtensive.Orm/Arithmetic/ArithmeticStruct.cs @@ -5,11 +5,7 @@ // Created: 2008.02.12 using System; -using System.Runtime.Serialization; -using System.Security; -using System.Security.Permissions; - -using A=Xtensive.Arithmetic; +using A = Xtensive.Arithmetic; namespace Xtensive.Arithmetic { @@ -18,8 +14,7 @@ namespace Xtensive.Arithmetic /// delegates. /// /// The type of generic argument. - [Serializable] - public struct ArithmeticStruct : ISerializable + public struct ArithmeticStruct { /// /// Gets for @@ -121,33 +116,5 @@ private ArithmeticStruct(Arithmetic arithmetic) ApplyRules = Arithmetic==null ? null : Arithmetic.ApplyRules; } - - /// - /// Deserializes the instance of this class. - /// - /// Serialization info. - /// Streaming context. - private ArithmeticStruct(SerializationInfo info, StreamingContext context) - { - Arithmetic = (Arithmetic)info.GetValue("Arithmetic", typeof (Arithmetic)); - Zero = Arithmetic==null ? default(T) : Arithmetic.Zero; - One = Arithmetic==null ? default(T) : Arithmetic.One; - MinValue = Arithmetic == null ? default(T) : Arithmetic.MinValue; - MaxValue = Arithmetic == null ? default(T) : Arithmetic.MaxValue; - IsSigned = Arithmetic == null ? true : Arithmetic.IsSigned; - Add = Arithmetic==null ? null : Arithmetic.Add; - Subtract = Arithmetic==null ? null : Arithmetic.Subtract; - Multiply = Arithmetic==null ? null : Arithmetic.Multiply; - Divide = Arithmetic==null ? null : Arithmetic.Divide; - Negation = Arithmetic==null ? null : Arithmetic.Negation; - ApplyRules = Arithmetic==null ? null : Arithmetic.ApplyRules; - } - - /// - [SecurityCritical] - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue("Arithmetic", Arithmetic); - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Arithmetic/Internal/NullableArithmetic.cs b/Orm/Xtensive.Orm/Arithmetic/Internal/NullableArithmetic.cs index 030abd0065..728ac669c2 100644 --- a/Orm/Xtensive.Orm/Arithmetic/Internal/NullableArithmetic.cs +++ b/Orm/Xtensive.Orm/Arithmetic/Internal/NullableArithmetic.cs @@ -9,7 +9,6 @@ namespace Xtensive.Arithmetic { - [Serializable] internal class NullableArithmetic : WrappingArithmetic where T : struct diff --git a/Orm/Xtensive.Orm/Arithmetic/Internal/PrimitiveArithmetics.cs b/Orm/Xtensive.Orm/Arithmetic/Internal/PrimitiveArithmetics.cs index e14f4c694f..7d40cd3bc5 100644 --- a/Orm/Xtensive.Orm/Arithmetic/Internal/PrimitiveArithmetics.cs +++ b/Orm/Xtensive.Orm/Arithmetic/Internal/PrimitiveArithmetics.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2008 Xtensive LLC. +// Copyright (C) 2008 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Alexey Gamzov @@ -10,7 +10,6 @@ namespace Xtensive.Arithmetic { - [Serializable] internal sealed class ByteArithmetic : ArithmeticBase { @@ -141,7 +140,6 @@ public ByteArithmetic(IArithmeticProvider provider, ArithmeticRules rule) } } - [Serializable] internal sealed class SByteArithmetic : ArithmeticBase { @@ -272,7 +270,6 @@ public SByteArithmetic(IArithmeticProvider provider, ArithmeticRules rule) } } - [Serializable] internal sealed class CharArithmetic : ArithmeticBase { @@ -403,7 +400,6 @@ public CharArithmetic(IArithmeticProvider provider, ArithmeticRules rule) } } - [Serializable] internal sealed class Int16Arithmetic : ArithmeticBase { @@ -534,7 +530,6 @@ public Int16Arithmetic(IArithmeticProvider provider, ArithmeticRules rule) } } - [Serializable] internal sealed class UInt16Arithmetic : ArithmeticBase { @@ -665,7 +660,6 @@ public UInt16Arithmetic(IArithmeticProvider provider, ArithmeticRules rule) } } - [Serializable] internal sealed class Int32Arithmetic : ArithmeticBase { @@ -796,7 +790,6 @@ public Int32Arithmetic(IArithmeticProvider provider, ArithmeticRules rule) } } - [Serializable] internal sealed class UInt32Arithmetic : ArithmeticBase { @@ -927,7 +920,6 @@ public UInt32Arithmetic(IArithmeticProvider provider, ArithmeticRules rule) } } - [Serializable] internal sealed class Int64Arithmetic : ArithmeticBase { @@ -1058,7 +1050,6 @@ public Int64Arithmetic(IArithmeticProvider provider, ArithmeticRules rule) } } - [Serializable] internal sealed class UInt64Arithmetic : ArithmeticBase { @@ -1189,7 +1180,6 @@ public UInt64Arithmetic(IArithmeticProvider provider, ArithmeticRules rule) } } - [Serializable] internal sealed class DecimalArithmetic : ArithmeticBase { @@ -1320,7 +1310,6 @@ public DecimalArithmetic(IArithmeticProvider provider, ArithmeticRules rule) } } - [Serializable] internal sealed class SingleArithmetic : ArithmeticBase { @@ -1451,7 +1440,6 @@ public SingleArithmetic(IArithmeticProvider provider, ArithmeticRules rule) } } - [Serializable] internal sealed class DoubleArithmetic : ArithmeticBase { diff --git a/Orm/Xtensive.Orm/Arithmetic/Internal/PrimitiveArithmetics.tt b/Orm/Xtensive.Orm/Arithmetic/Internal/PrimitiveArithmetics.tt index 90e9a1a843..de8ec600d1 100644 --- a/Orm/Xtensive.Orm/Arithmetic/Internal/PrimitiveArithmetics.tt +++ b/Orm/Xtensive.Orm/Arithmetic/Internal/PrimitiveArithmetics.tt @@ -32,7 +32,6 @@ foreach (var type in types) { var primitiveName = type.Name; var className = type.Name + "Arithmetic"; #> - [Serializable] internal sealed class <#= className #> : ArithmeticBase<<#= primitiveName #>> { diff --git a/Orm/Xtensive.Orm/Arithmetic/NullBehavior.cs b/Orm/Xtensive.Orm/Arithmetic/NullBehavior.cs index 95bd2f3549..0f9e6c72ca 100644 --- a/Orm/Xtensive.Orm/Arithmetic/NullBehavior.cs +++ b/Orm/Xtensive.Orm/Arithmetic/NullBehavior.cs @@ -11,7 +11,6 @@ namespace Xtensive.Arithmetic /// /// Describes how arithmetics treats in operations. /// - [Serializable] public enum NullBehavior : sbyte { /// diff --git a/Orm/Xtensive.Orm/Arithmetic/OverflowBehavior.cs b/Orm/Xtensive.Orm/Arithmetic/OverflowBehavior.cs index 0b9aa67e3e..273bda50c5 100644 --- a/Orm/Xtensive.Orm/Arithmetic/OverflowBehavior.cs +++ b/Orm/Xtensive.Orm/Arithmetic/OverflowBehavior.cs @@ -11,7 +11,6 @@ namespace Xtensive.Arithmetic /// /// Describes arithmetic overflow behavior. /// - [Serializable] public enum OverflowBehavior : sbyte { /// diff --git a/Orm/Xtensive.Orm/Arithmetic/WrappingArithmetic{T,TBase}.cs b/Orm/Xtensive.Orm/Arithmetic/WrappingArithmetic{T,TBase}.cs index 8988171147..5cc548ebdd 100644 --- a/Orm/Xtensive.Orm/Arithmetic/WrappingArithmetic{T,TBase}.cs +++ b/Orm/Xtensive.Orm/Arithmetic/WrappingArithmetic{T,TBase}.cs @@ -15,7 +15,6 @@ namespace Xtensive.Arithmetic /// /// The type to provide arithmetic operations for. /// Base (wrapped) type. - [Serializable] public abstract class WrappingArithmetic : ArithmeticBase { /// diff --git a/Orm/Xtensive.Orm/Collections/BindingCollection.cs b/Orm/Xtensive.Orm/Collections/BindingCollection.cs index de594dbe0e..66a1239654 100644 --- a/Orm/Xtensive.Orm/Collections/BindingCollection.cs +++ b/Orm/Xtensive.Orm/Collections/BindingCollection.cs @@ -18,7 +18,6 @@ namespace Xtensive.Collections /// Any binding is active while its binding result ( object) /// isn't disposed. /// - [Serializable] [DebuggerDisplay("Count = {Count}")] public class BindingCollection : IReadOnlyCollection> { @@ -65,8 +64,8 @@ public BindingScope(BindingCollection owner, TKey key, TValue prev } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - private readonly Dictionary bindings = new Dictionary(); - private readonly HashSet permanentBindings = new HashSet(); + private readonly Dictionary bindings = new(); + private readonly HashSet permanentBindings = new(); /// /// Gets the number of currently bound items. @@ -112,7 +111,7 @@ public virtual BindingScope Add(TKey key, TValue value) public virtual void PermanentAdd(TKey key, TValue value) { bindings[key] = value; - permanentBindings.Add(key); + _ = permanentBindings.Add(key); } /// diff --git a/Orm/Xtensive.Orm/Collections/ChangeNotifierEventArgs.cs b/Orm/Xtensive.Orm/Collections/ChangeNotifierEventArgs.cs index 43a2f109d1..c751e0b007 100644 --- a/Orm/Xtensive.Orm/Collections/ChangeNotifierEventArgs.cs +++ b/Orm/Xtensive.Orm/Collections/ChangeNotifierEventArgs.cs @@ -12,22 +12,16 @@ namespace Xtensive.Collections /// /// Represents a set of information describing change. /// - [Serializable] - public readonly struct ChangeNotifierEventArgs + /// + /// Initializes a new instance of this type. + /// + /// The info. + public readonly struct ChangeNotifierEventArgs(object changeInfo) { /// /// Gets the object representing some additional change information. /// /// The info. - public object ChangeInfo { get; } - - /// - /// Initializes a new instance of this type. - /// - /// The info. - public ChangeNotifierEventArgs(object changeInfo) - { - ChangeInfo = changeInfo; - } + public object ChangeInfo { get; } = changeInfo; } } diff --git a/Orm/Xtensive.Orm/Collections/ClassifiedCollection.cs b/Orm/Xtensive.Orm/Collections/ClassifiedCollection.cs index 38688ca652..c7c5098b2c 100644 --- a/Orm/Xtensive.Orm/Collections/ClassifiedCollection.cs +++ b/Orm/Xtensive.Orm/Collections/ClassifiedCollection.cs @@ -17,36 +17,29 @@ namespace Xtensive.Collections /// /// The type of the class. /// The type of the item. - [Serializable] [DebuggerDisplay("Count = {Count}, ClassCount = {ClassCount}")] - public class ClassifiedCollection : + public class ClassifiedCollection : IClassifiedCollection { [DebuggerBrowsable(DebuggerBrowsableState.Never)] - private HashSet set = new HashSet(); + private readonly HashSet set = new(); [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - private List list = new List(); - private Dictionary> classified = new Dictionary>(); + private readonly List list = new(); + private readonly Dictionary> classified = new(); #region Properties: Count, ClassCount, IsSet, ... /// - public bool IsSet { get; private set; } + public bool IsSet { get; } /// - public bool IsReadOnly { - get { return false; } - } + public bool IsReadOnly => false; /// - public int Count { - get { return list.Count; } - } + public int Count => list.Count; /// - public int ClassCount { - get { return classified.Keys.Count; } - } + public int ClassCount => classified.Keys.Count; /// public Func Classifier { get; private set; } @@ -62,7 +55,7 @@ public void Add(TItem item) var classes = Classifier.Invoke(item); foreach (var @class in classes) { var classList = classified.GetValueOrDefault(@class); - if (classList==null) { + if (classList is null) { classList = new List(); classified.Add(@class, classList); } @@ -82,13 +75,13 @@ public bool Remove(TItem item) { if (!set.Remove(item)) return false; - list.Remove(item); + _ = list.Remove(item); var classes = Classifier.Invoke(item); foreach (var @class in classes) { var classList = classified[@class]; - classList.Remove(item); + _ = classList.Remove(item); if (classList.Count==0) - classified.Remove(@class); + _ = classified.Remove(@class); } return true; } @@ -102,28 +95,19 @@ public void Clear() } /// - public bool Contains(TItem item) - { - return set.Contains(item); - } + public bool Contains(TItem item) => set.Contains(item); /// public void CopyTo(TItem[] array, int arrayIndex) - { - list.CopyTo(array, arrayIndex); - } + => list.CopyTo(array, arrayIndex); /// public IEnumerable GetItems(TClass @class) - { - return classified.GetValueOrDefault(@class) ?? Enumerable.Empty(); - } + => classified.GetValueOrDefault(@class) + ?? Enumerable.Empty(); /// - public IEnumerable GetClasses() - { - return classified.Keys; - } + public IEnumerable GetClasses() => classified.Keys; public int GetItemCount(TClass @class) { @@ -133,15 +117,9 @@ public int GetItemCount(TClass @class) #region IEnumerable<...> members - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - public IEnumerator GetEnumerator() - { - return list.GetEnumerator(); - } + public IEnumerator GetEnumerator() => list.GetEnumerator(); #endregion diff --git a/Orm/Xtensive.Orm/Collections/CollectionBaseSlim.cs b/Orm/Xtensive.Orm/Collections/CollectionBaseSlim.cs index 46f2e5922a..5e86406fb3 100644 --- a/Orm/Xtensive.Orm/Collections/CollectionBaseSlim.cs +++ b/Orm/Xtensive.Orm/Collections/CollectionBaseSlim.cs @@ -15,7 +15,6 @@ namespace Xtensive.Collections /// /// Lightweight base class for any collection. /// - [Serializable] [DebuggerDisplay("Count = {Count}")] public class CollectionBaseSlim: LockableBase, ICollection, IReadOnlyList diff --git a/Orm/Xtensive.Orm/Collections/Deque.cs b/Orm/Xtensive.Orm/Collections/Deque.cs index f6f27b6557..79e588354d 100644 --- a/Orm/Xtensive.Orm/Collections/Deque.cs +++ b/Orm/Xtensive.Orm/Collections/Deque.cs @@ -7,14 +7,9 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; -using System.Runtime.Serialization; -using System.Security; -using System.Security.Permissions; using Xtensive.Comparison; using Xtensive.Core; - - namespace Xtensive.Collections { /// @@ -45,10 +40,9 @@ namespace Xtensive.Collections /// as a valid value for reference types and allows duplicate elements. /// /// - [Serializable] [DebuggerDisplay("Count = {Count}")] - public class Deque : IDeque, - ISerializable, + [Obsolete] + public class Deque : IDeque, ICloneable { private const int minimalCapacity = 16; @@ -625,37 +619,5 @@ public Deque(IEnumerable source, float growFactor) { this.growFactor = growFactor; } - - #region ISerializable Members - - /// - /// Serializes instance of this type. - /// - /// - /// - [SecurityCritical] - public virtual void GetObjectData(SerializationInfo info, StreamingContext context) - { - T[] arrItems = new T[count]; - InnerCopyTo(arrItems, 0); - info.AddValue("Items", arrItems); - info.AddValue("GrowFactor", growFactor); - } - - /// - /// Deserializes instance of this type. - /// - /// - /// - protected Deque(SerializationInfo info, StreamingContext context) - { - items = (T[])info.GetValue("Items", typeof (T[])); - growFactor = info.GetSingle("GrowFactor"); - count = items.Length; - headPos = count - 1; - tailPos = count - 1; - } - - #endregion } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Collections/DirectionCollection.cs b/Orm/Xtensive.Orm/Collections/DirectionCollection.cs index 61117ee635..2a7b679687 100644 --- a/Orm/Xtensive.Orm/Collections/DirectionCollection.cs +++ b/Orm/Xtensive.Orm/Collections/DirectionCollection.cs @@ -18,30 +18,24 @@ namespace Xtensive.Collections /// Normally used to describe "order by" clauses. /// /// The type of collection item to associate with direction. - [Serializable] [DebuggerDisplay("Count = {Count}")] public sealed class DirectionCollection: FlagCollection { private static readonly Biconverter DirectionToBoolBiconverter = - new Biconverter( - value => value == Direction.None - ? throw Exceptions.InvalidArgument(value, nameof(value)) - : value == Direction.Positive, - value => value ? Direction.Positive : Direction.Negative); + new(value => value == Direction.None + ? throw Exceptions.InvalidArgument(value, nameof(value)) + : value == Direction.Positive, + value => value ? Direction.Positive : Direction.Negative); /// - public override void Add(T key) - { - Add(key, Direction.Positive); - } + public override void Add(T key) => Add(key, Direction.Positive); /// /// Initializes a new instance of this type. /// /// Initial content of collection. public DirectionCollection(IEnumerable> enumerable) - : base(DirectionToBoolBiconverter, - enumerable) + : base(DirectionToBoolBiconverter, enumerable) { } diff --git a/Orm/Xtensive.Orm/Collections/ExtensionCollection.cs b/Orm/Xtensive.Orm/Collections/ExtensionCollection.cs index 05ba6408ef..1597e8a53f 100644 --- a/Orm/Xtensive.Orm/Collections/ExtensionCollection.cs +++ b/Orm/Xtensive.Orm/Collections/ExtensionCollection.cs @@ -19,7 +19,6 @@ namespace Xtensive.Collections /// /// Default implementation (lockable). /// - [Serializable] public class ExtensionCollection: LockableBase, IExtensionCollection, ICloneable @@ -29,27 +28,21 @@ public class ExtensionCollection: LockableBase, /// public long Count { [DebuggerStepThrough] - get { - return extensions!=null ? extensions.Count : 0; - } + get => extensions is not null ? extensions.Count : 0; } /// [DebuggerStepThrough] - public T Get() - where T : class - { - return (T) Get(typeof (T)); - } + public T Get() + where T : class => (T) Get(typeof(T)); /// public object Get(Type extensionType) { ArgumentNullException.ThrowIfNull(extensionType); - if (extensions==null) + if (extensions is null) return null; - object result; - if (extensions.TryGetValue(extensionType, out result)) + if (extensions.TryGetValue(extensionType, out object result)) return result; else return null; @@ -57,11 +50,8 @@ public object Get(Type extensionType) /// [DebuggerStepThrough] - public void Set(T value) - where T : class - { - Set(typeof (T), value); - } + public void Set(T value) + where T : class => Set(typeof(T), value); /// /// Wrong arguments. @@ -76,8 +66,8 @@ public void Set(Type extensionType, object value) throw new ArgumentException(string.Format( Strings.ExTypeXMustImplementY, value.GetType(), extensionType.GetShortName()), nameof(value)); - if (extensions==null) - if (value==null) + if (extensions is null) + if (value is null) return; else extensions = new Dictionary(); @@ -95,11 +85,11 @@ public void Clear() public override void Lock(bool recursive) { base.Lock(recursive); - if (extensions!=null) + if (extensions is not null) foreach (KeyValuePair pair in extensions) { - var lockable = pair.Value as ILockable; - if (lockable!=null) - lockable.Lock(recursive); + if (pair.Value is ILockable locable) { + locable.Lock(recursive); + } } } diff --git a/Orm/Xtensive.Orm/Collections/FlagCollection.cs b/Orm/Xtensive.Orm/Collections/FlagCollection.cs index 4c0948f4de..102128fabd 100644 --- a/Orm/Xtensive.Orm/Collections/FlagCollection.cs +++ b/Orm/Xtensive.Orm/Collections/FlagCollection.cs @@ -10,8 +10,6 @@ using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Diagnostics; -using System.Runtime.Serialization; -using System.Security; using Xtensive.Conversion; using Xtensive.Core; @@ -28,13 +26,11 @@ namespace Xtensive.Collections /// /// Type of the key. /// Type of the flag. - [Serializable] [DebuggerDisplay("Count = {Count}")] public class FlagCollection: LockableBase, IList>, IDictionary, - IEquatable>, - ISerializable + IEquatable> { private const int MaxItemCount = 32; private readonly Biconverter converter; @@ -373,38 +369,5 @@ private FlagCollection() keys = new List(); readOnlyKeys = keys.AsReadOnly(); } - - #region ISerializable members - - /// - /// Deserializes instance of this type. - /// - /// - /// - protected FlagCollection(SerializationInfo info, StreamingContext context) - : base(info.GetBoolean("IsLocked")) - { - converter = (Biconverter) - info.GetValue("AdvancedConverter", typeof(Biconverter)); - keys = (List)info.GetValue("Keys", typeof(List)); - readOnlyKeys = keys.AsReadOnly(); - flags = new BitVector32(info.GetInt32("Flags")); - } - - /// - /// Serializes instance of this type. - /// - /// - /// - [SecurityCritical] - public virtual void GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue("IsLocked", IsLocked); - info.AddValue("AdvancedConverter", converter); - info.AddValue("Keys", keys); - info.AddValue("Flags", flags.Data); - } - - #endregion } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Collections/Graphs/Edge.cs b/Orm/Xtensive.Orm/Collections/Graphs/Edge.cs index 4fa7d59ff4..1791780bfc 100644 --- a/Orm/Xtensive.Orm/Collections/Graphs/Edge.cs +++ b/Orm/Xtensive.Orm/Collections/Graphs/Edge.cs @@ -13,13 +13,12 @@ namespace Xtensive.Collections.Graphs /// /// A connection between two graph s. /// - [Serializable] public class Edge { /// /// Gets edge value. /// - public virtual object UntypedValue { get { return null; } } + public virtual object UntypedValue => null; /// /// Gets or sets edge source. @@ -41,8 +40,8 @@ public class Edge /// public void Attach() { - Source.OutgoingEdges.Add(this); - Target.IncomingEdges.Add(this); + _ = Source.OutgoingEdges.Add(this); + _ = Target.IncomingEdges.Add(this); IsAttached = true; } @@ -51,8 +50,8 @@ public void Attach() /// public void Detach() { - Source.OutgoingEdges.Remove(this); - Target.IncomingEdges.Remove(this); + _ = Source.OutgoingEdges.Remove(this); + _ = Target.IncomingEdges.Remove(this); IsAttached = false; } diff --git a/Orm/Xtensive.Orm/Collections/Graphs/Edge{TValue}.cs b/Orm/Xtensive.Orm/Collections/Graphs/Edge{TValue}.cs index 8016c23ef9..b22c4b6089 100644 --- a/Orm/Xtensive.Orm/Collections/Graphs/Edge{TValue}.cs +++ b/Orm/Xtensive.Orm/Collections/Graphs/Edge{TValue}.cs @@ -13,7 +13,6 @@ namespace Xtensive.Collections.Graphs /// A connection between two graph s with value. /// /// Edge value. - [Serializable] public class Edge : Edge { /// @@ -24,7 +23,7 @@ public class Edge : Edge /// /// Gets node value. /// - public override object UntypedValue { get { return Value; } } + public override object UntypedValue => Value; // Constructors diff --git a/Orm/Xtensive.Orm/Collections/Graphs/Graph.cs b/Orm/Xtensive.Orm/Collections/Graphs/Graph.cs index 69956d8b17..3484ea7544 100644 --- a/Orm/Xtensive.Orm/Collections/Graphs/Graph.cs +++ b/Orm/Xtensive.Orm/Collections/Graphs/Graph.cs @@ -17,7 +17,6 @@ namespace Xtensive.Collections.Graphs /// /// Node type. /// Edge type. - [Serializable] public class Graph where TNode : Node where TEdge : Edge @@ -30,10 +29,7 @@ public class Graph /// /// Gets a sequence of graph edges. /// - public IEnumerable Edges - { - get { return Nodes.SelectMany(node => node.OutgoingEdges.Cast()); } - } + public IEnumerable Edges => Nodes.SelectMany(node => node.OutgoingEdges.Cast()); /// /// Creates a mutable copy of the graph. diff --git a/Orm/Xtensive.Orm/Collections/Graphs/Node.cs b/Orm/Xtensive.Orm/Collections/Graphs/Node.cs index f5fab8e383..abc39d8317 100644 --- a/Orm/Xtensive.Orm/Collections/Graphs/Node.cs +++ b/Orm/Xtensive.Orm/Collections/Graphs/Node.cs @@ -12,7 +12,6 @@ namespace Xtensive.Collections.Graphs /// /// Graph node. /// - [Serializable] public class Node { private HashSet incomingEdges; @@ -21,17 +20,17 @@ public class Node /// /// Gets node value. /// - public virtual object UntypedValue { get { return null; } } + public virtual object UntypedValue => null; /// /// Indicates whether this node has incoming edges. /// - public bool HasIncomingEdges { get { return incomingEdges!=null && incomingEdges.Count!=0; } } - + public bool HasIncomingEdges => incomingEdges is not null && incomingEdges.Count != 0; + /// /// Indicates whether this node has outgoing edges. /// - public bool HasOutgoingEdges { get { return outgoingEdges!=null && outgoingEdges.Count!=0; } } + public bool HasOutgoingEdges => outgoingEdges is not null && outgoingEdges.Count != 0; /// /// Gets incoming edges. @@ -63,12 +62,9 @@ public IEnumerable Edges foreach (var c in outgoingEdges) yield return c; } - } + } /// - public override string ToString() - { - return string.Concat("[", UntypedValue, "]"); - } + public override string ToString() => $"[{UntypedValue}]"; } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Collections/Graphs/Node{TValue}.cs b/Orm/Xtensive.Orm/Collections/Graphs/Node{TValue}.cs index 95dcf1c502..408ef0e5ce 100644 --- a/Orm/Xtensive.Orm/Collections/Graphs/Node{TValue}.cs +++ b/Orm/Xtensive.Orm/Collections/Graphs/Node{TValue}.cs @@ -13,7 +13,6 @@ namespace Xtensive.Collections.Graphs /// Graph node with value. /// /// Node value. - [Serializable] public class Node : Node { /// @@ -24,7 +23,7 @@ public class Node : Node /// /// Gets node value. /// - public override object UntypedValue { get { return Value; } } + public override object UntypedValue => Value; // Constructors diff --git a/Orm/Xtensive.Orm/Collections/Interfaces/IDeque.cs b/Orm/Xtensive.Orm/Collections/Interfaces/IDeque.cs index 324a6f1891..52c6aea355 100644 --- a/Orm/Xtensive.Orm/Collections/Interfaces/IDeque.cs +++ b/Orm/Xtensive.Orm/Collections/Interfaces/IDeque.cs @@ -14,6 +14,7 @@ namespace Xtensive.Collections /// Double-ended queue contract. /// /// The type of queued elements. + [Obsolete] public interface IDeque : IList { /// diff --git a/Orm/Xtensive.Orm/Collections/NativeTypeClassifier.cs b/Orm/Xtensive.Orm/Collections/NativeTypeClassifier.cs index f1828f7217..90a454d321 100644 --- a/Orm/Xtensive.Orm/Collections/NativeTypeClassifier.cs +++ b/Orm/Xtensive.Orm/Collections/NativeTypeClassifier.cs @@ -17,7 +17,6 @@ namespace Xtensive.Collections /// Native type-based classifier. /// /// The type of the item. - [Serializable] public class NativeTypeClassifier : ClassifiedCollection { /// @@ -28,24 +27,16 @@ public class NativeTypeClassifier : ClassifiedCollection /// A sequence of items of the specified class. /// public IEnumerable GetItems() - { - return GetItems(typeof(TClass)).Cast(); - } + => GetItems(typeof(TClass)).Cast(); public int GetItemCount() - { - return GetItemCount(typeof(TClass)); - } + => GetItemCount(typeof(TClass)); private static Func GetClassifier(bool exactType) - { - if (exactType) - return item => new[] {item.GetType()}; - else - return item => item.GetType().GetCompatibles(); - } + => exactType + ? (item => [item.GetType()]) + : (item => item.GetType().GetCompatibles()); - // Constructors /// diff --git a/Orm/Xtensive.Orm/Collections/ReadOnlyHashSet{T}.cs b/Orm/Xtensive.Orm/Collections/ReadOnlyHashSet{T}.cs index c6181ff649..20eb45ecf6 100644 --- a/Orm/Xtensive.Orm/Collections/ReadOnlyHashSet{T}.cs +++ b/Orm/Xtensive.Orm/Collections/ReadOnlyHashSet{T}.cs @@ -14,9 +14,8 @@ namespace Xtensive.Collections /// /// Read-only wrapper over the class instance. /// - [Serializable] [DebuggerDisplay("Count = {Count}")] - internal class ReadOnlyHashSet: System.Collections.Generic.ISet, IReadOnlySet + internal class ReadOnlyHashSet: ISet, IReadOnlySet { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] private readonly HashSet innerSet; diff --git a/Orm/Xtensive.Orm/Collections/SinglyLinkedList.cs b/Orm/Xtensive.Orm/Collections/SinglyLinkedList.cs index 6654ef48cd..e18412e2db 100644 --- a/Orm/Xtensive.Orm/Collections/SinglyLinkedList.cs +++ b/Orm/Xtensive.Orm/Collections/SinglyLinkedList.cs @@ -14,13 +14,12 @@ namespace Xtensive.Collections /// Singly-linked immutable list. /// /// The type of elements. - [Serializable] public sealed class SinglyLinkedList : IEnumerable { /// /// Gets the empty . /// - public static SinglyLinkedList Empty { get; private set; } + public static readonly SinglyLinkedList Empty = new(); private readonly T head; @@ -40,10 +39,10 @@ public T Head /// /// Gets the tail of the current insttance. /// - public SinglyLinkedList Tail { get; private set; } + public SinglyLinkedList Tail { get; } /// - public long Count { get; private set; } + public long Count { get; } /// @@ -126,13 +125,5 @@ private SinglyLinkedList(T head, SinglyLinkedList tail) Tail = tail; Count = Tail.Count + 1; } - - /// - /// Initializes this type. - /// - static SinglyLinkedList() - { - Empty = new SinglyLinkedList(); - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Collections/TopDeque.cs b/Orm/Xtensive.Orm/Collections/TopDeque.cs index 026b42675a..083214e762 100644 --- a/Orm/Xtensive.Orm/Collections/TopDeque.cs +++ b/Orm/Xtensive.Orm/Collections/TopDeque.cs @@ -19,11 +19,10 @@ namespace Xtensive.Collections /// /// Type of the key. /// Type of the value. - [Serializable] [DebuggerDisplay("Count = {Count}")] public class TopDeque : ITopDeque { - private readonly System.Collections.Generic.LinkedList> list; + private readonly LinkedList> list; private readonly Dictionary>> map; /// @@ -37,14 +36,12 @@ public int Count /// There is no specified key. public V this[K key] { get { - LinkedListNode> valueContainer; - if (map.TryGetValue(key, out valueContainer)) + if (map.TryGetValue(key, out var valueContainer)) return valueContainer.Value.Second; throw new KeyNotFoundException(Strings.ExNoObjectWithSpecifiedKey); } set { - LinkedListNode> valueContainer; - if (map.TryGetValue(key, out valueContainer)) + if (map.TryGetValue(key, out var valueContainer)) valueContainer.Value = new Pair(key, value); throw new KeyNotFoundException(Strings.ExNoObjectWithSpecifiedKey); } @@ -53,8 +50,7 @@ public V this[K key] { /// public bool TryGetValue(K key, out V value) { - LinkedListNode> valueContainer; - if (map.TryGetValue(key, out valueContainer)) { + if (map.TryGetValue(key, out var valueContainer)) { value = valueContainer.Value.Second; return true; } @@ -65,8 +61,7 @@ public bool TryGetValue(K key, out V value) /// public bool TryGetValue(K key, bool moveToTop, out V value) { - LinkedListNode> valueContainer; - if (map.TryGetValue(key, out valueContainer)) { + if (map.TryGetValue(key, out var valueContainer)) { if (moveToTop) { list.Remove(valueContainer); list.AddFirst(valueContainer); @@ -81,8 +76,7 @@ public bool TryGetValue(K key, bool moveToTop, out V value) /// public bool TryChangeValue(K key, V value, bool moveToTop, bool replaceIfExists, out V oldValue) { - LinkedListNode> valueContainer; - if (map.TryGetValue(key, out valueContainer)) { + if (map.TryGetValue(key, out var valueContainer)) { oldValue = valueContainer.Value.Second; if (moveToTop) { list.Remove(valueContainer); @@ -107,10 +101,7 @@ public bool TryChangeValue(K key, V value, bool moveToTop, bool replaceIfExists, } /// - public bool Contains(K key) - { - return map.ContainsKey(key); - } + public bool Contains(K key) => map.ContainsKey(key); #region Properties: TopXxx, BottomXxx @@ -168,7 +159,7 @@ public V PopTop() var valueContainer = list.First; list.Remove(valueContainer); var keyValuePair = valueContainer.Value; - map.Remove(keyValuePair.First); + _ = map.Remove(keyValuePair.First); return keyValuePair.Second; } @@ -182,7 +173,7 @@ public V PopBottom() var valueContainer = list.Last; list.Remove(valueContainer); var keyValuePair = valueContainer.Value; - map.Remove(keyValuePair.First); + _ = map.Remove(keyValuePair.First); return keyValuePair.Second; } @@ -194,8 +185,7 @@ public V PopBottom() /// There is no specified key. public void MoveToTop(K key) { - LinkedListNode> valueContainer; - if (!map.TryGetValue(key, out valueContainer)) + if (!map.TryGetValue(key, out var valueContainer)) throw new KeyNotFoundException(Strings.ExNoObjectWithSpecifiedKey); list.Remove(valueContainer); list.AddFirst(valueContainer); @@ -205,8 +195,7 @@ public void MoveToTop(K key) /// There is no specified key. public void MoveToBottom(K key) { - LinkedListNode> valueContainer; - if (!map.TryGetValue(key, out valueContainer)) + if (!map.TryGetValue(key, out var valueContainer)) throw new KeyNotFoundException(Strings.ExNoObjectWithSpecifiedKey); list.Remove(valueContainer); list.AddLast(valueContainer); @@ -271,10 +260,7 @@ public void Clear() /// [DebuggerStepThrough] - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); /// public IEnumerator GetEnumerator() @@ -293,7 +279,7 @@ public IEnumerator GetEnumerator() /// public TopDeque() { - list = new System.Collections.Generic.LinkedList>(); + list = new LinkedList>(); map = new Dictionary>>(); } @@ -303,7 +289,7 @@ public TopDeque() /// The initial capacity. public TopDeque(int capacity) { - list = new System.Collections.Generic.LinkedList>(); + list = new LinkedList>(); map = new Dictionary>>(capacity); } @@ -313,7 +299,7 @@ public TopDeque(int capacity) /// The key comparer. public TopDeque(IEqualityComparer keyComparer) { - list = new System.Collections.Generic.LinkedList>(); + list = new LinkedList>(); map = new Dictionary>>(keyComparer); } @@ -324,7 +310,7 @@ public TopDeque(IEqualityComparer keyComparer) /// The initial capacity. public TopDeque(IEqualityComparer keyComparer, int capacity) { - list = new System.Collections.Generic.LinkedList>(); + list = new LinkedList>(); map = new Dictionary>>(capacity, keyComparer); } } diff --git a/Orm/Xtensive.Orm/Collections/TypeRegistration.cs b/Orm/Xtensive.Orm/Collections/TypeRegistration.cs index 69bceb65f5..b9cdd60fda 100644 --- a/Orm/Xtensive.Orm/Collections/TypeRegistration.cs +++ b/Orm/Xtensive.Orm/Collections/TypeRegistration.cs @@ -15,49 +15,35 @@ namespace Xtensive.Collections /// /// Describes a single type registration call to . /// - [Serializable] [DebuggerDisplay("Type = {Type}, Assembly = {Assembly}, Namespace = {Namespace}")] public sealed class TypeRegistration : IEquatable { - private readonly Type type; - private readonly Assembly assembly; - private readonly string @namespace; - /// /// Gets the type registered by this action. /// - public Type Type - { - get { return type; } - } + public Type Type { get; } /// /// Gets the assembly registered by this action. /// - public Assembly Assembly - { - get { return assembly; } - } + public Assembly Assembly { get; } /// /// Gets the namespace registered by this action. /// - public string Namespace - { - get { return @namespace; } - } + public string Namespace { get; } #region Equality members /// public bool Equals(TypeRegistration other) { - if (other == null) + if (other is null) return false; return - type==other.type && - assembly==other.assembly && - @namespace==other.@namespace; + Type==other.Type && + Assembly==other.Assembly && + Namespace==other.Namespace; } /// @@ -72,9 +58,9 @@ public override bool Equals(object obj) public override int GetHashCode() { unchecked { - int result = (type!=null ? type.GetHashCode() : 0); - result = (result * 397) ^ (assembly!=null ? assembly.GetHashCode() : 0); - result = (result * 397) ^ (@namespace!=null ? @namespace.GetHashCode() : 0); + int result = (Type is not null ? Type.GetHashCode() : 0); + result = (result * 397) ^ (Assembly is not null ? Assembly.GetHashCode() : 0); + result = (result * 397) ^ (Namespace is not null ? Namespace.GetHashCode() : 0); return result; } } @@ -102,7 +88,7 @@ public override int GetHashCode() /// The type to register. public TypeRegistration(Type type) { - this.type = type ?? throw new ArgumentNullException(nameof(type)); + Type = type ?? throw new ArgumentNullException(nameof(type)); } /// @@ -111,7 +97,7 @@ public TypeRegistration(Type type) /// The assembly to register. public TypeRegistration(Assembly assembly) { - this.assembly = assembly ?? throw new ArgumentNullException(nameof(assembly)); + Assembly = assembly ?? throw new ArgumentNullException(nameof(assembly)); } /// @@ -122,7 +108,7 @@ public TypeRegistration(Assembly assembly) public TypeRegistration(Assembly assembly, string @namespace) : this(assembly) { - this.@namespace = @namespace ?? throw new ArgumentNullException(nameof(@namespace)); + Namespace = @namespace ?? throw new ArgumentNullException(nameof(@namespace)); } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Collections/TypeRegistrationProcessorBase.cs b/Orm/Xtensive.Orm/Collections/TypeRegistrationProcessorBase.cs index ce0694dd5a..53f6c59f87 100644 --- a/Orm/Xtensive.Orm/Collections/TypeRegistrationProcessorBase.cs +++ b/Orm/Xtensive.Orm/Collections/TypeRegistrationProcessorBase.cs @@ -16,7 +16,6 @@ namespace Xtensive.Collections /// /// Abstract base class for implementation. /// - [Serializable] public abstract class TypeRegistrationProcessorBase : ITypeRegistrationProcessor { /// @@ -32,7 +31,7 @@ public abstract class TypeRegistrationProcessorBase : ITypeRegistrationProcessor public virtual void Process(TypeRegistry registry, TypeRegistration registration) { var types = - registration.Type==null + registration.Type is null ? FindTypes(registration.Assembly, BaseType, (type, typeFilter) => IsAcceptable(registration, type)) : IsAcceptable(registration, registration.Type) ? Enumerable.Repeat(registration.Type, 1) @@ -48,9 +47,7 @@ public virtual void Process(TypeRegistry registry, TypeRegistration registration /// The registration. /// The type. protected virtual void Process(TypeRegistry registry, TypeRegistration registration, Type type) - { - registry.Register(type); - } + => registry.Register(type); /// /// Determines whether the specified type is acceptable for registration. @@ -82,16 +79,16 @@ private static IList FindTypes(Assembly assembly, Type baseType, TypeFilte e); } - List types = new List(allTypes.Length); + var types = new List(allTypes.Length); for (int index = 0; index < allTypes.Length; index++) { - Type type = allTypes[index]; + var type = allTypes[index]; if (type != baseType && !(type.IsSubclassOf(baseType) || (baseType.IsInterface && baseType.IsAssignableFrom(type)))) continue; if (baseType.IsAssignableFrom(type)) { - if (filter != null && !filter(type, null)) + if (filter is not null && !filter(type, null)) continue; types.Add(type); } diff --git a/Orm/Xtensive.Orm/Collections/TypeRegistry.cs b/Orm/Xtensive.Orm/Collections/TypeRegistry.cs index e110871568..2323c782c3 100644 --- a/Orm/Xtensive.Orm/Collections/TypeRegistry.cs +++ b/Orm/Xtensive.Orm/Collections/TypeRegistry.cs @@ -18,7 +18,6 @@ namespace Xtensive.Collections /// /// registration endpoint. /// - [Serializable] public class TypeRegistry : LockableBase, IEnumerable, ICloneable @@ -38,7 +37,7 @@ public class TypeRegistry : LockableBase, /// /// Gets assemblies containing registered types. /// - public IReadOnlySet Assemblies { get { return (IReadOnlySet)assemblies; } } + public IReadOnlySet Assemblies => (IReadOnlySet) assemblies; /// /// Determines whether the specified is contained in this instance. @@ -60,11 +59,11 @@ public void Register(Type type) EnsureNotLocked(); ArgumentNullException.ThrowIfNull(type); if (!isProcessingPendingActions) - Register(new TypeRegistration(type)); + _ = Register(new TypeRegistration(type)); else if (typeSet.Add(type)) { serviceRegistrations = null; types.Add(type); - assemblies.Add(type.Assembly); + _ = assemblies.Add(type.Assembly); } } @@ -80,7 +79,7 @@ public void Register(Assembly assembly) { EnsureNotLocked(); ArgumentNullException.ThrowIfNull(assembly); - Register(new TypeRegistration(assembly)); + _ = Register(new TypeRegistration(assembly)); } /// @@ -98,7 +97,7 @@ public void Register(Assembly assembly, string @namespace) EnsureNotLocked(); ArgumentNullException.ThrowIfNull(assembly); ArgumentValidator.EnsureArgumentNotNullOrEmpty(@namespace, nameof(@namespace)); - Register(new TypeRegistration(assembly, @namespace)); + _ = Register(new TypeRegistration(assembly, @namespace)); } /// @@ -113,7 +112,7 @@ public bool Register(TypeRegistration action) ArgumentNullException.ThrowIfNull(action); if (actionSet.Contains(action)) return false; - actionSet.Add(action); + _ = actionSet.Add(action); actions.Add(action); return true; } @@ -172,10 +171,7 @@ public IEnumerator GetEnumerator() } /// - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion diff --git a/Orm/Xtensive.Orm/Comparison/AdvancedComparer.cs b/Orm/Xtensive.Orm/Comparison/AdvancedComparer.cs index b3e599e61e..f5a179db86 100644 --- a/Orm/Xtensive.Orm/Comparison/AdvancedComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/AdvancedComparer.cs @@ -7,10 +7,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Runtime.Serialization; -using System.Security; using Xtensive.Core; -using Xtensive.Reflection; namespace Xtensive.Comparison { @@ -18,33 +15,28 @@ namespace Xtensive.Comparison /// Provides delegates allowing to call comparison methods faster. /// /// The type of generic argument. - [Serializable] public sealed class AdvancedComparer: MethodCacheBase> { - private static readonly Lazy> SystemCached = - new Lazy>(() => ComparerProvider.System.GetComparer()); - - private static readonly Lazy> DefaultCached = - new Lazy>(() => ComparerProvider.Default.GetComparer()); + private static readonly Lazy> SystemCached = new(ComparerProvider.System.GetComparer()); + private static readonly Lazy> DefaultCached = new(ComparerProvider.Default.GetComparer()); /// /// Gets default advanced comparer for type /// (uses ). /// - public static AdvancedComparer Default { + public static AdvancedComparer Default + { [DebuggerStepThrough] - get { - return DefaultCached.Value; - } + get => DefaultCached.Value; } /// /// Gets system comparers exposed as for type . /// - public static AdvancedComparer System { - get { - return SystemCached.Value; - } + public static AdvancedComparer System + { + [DebuggerStepThrough] + get => SystemCached.Value; } /// @@ -210,67 +202,5 @@ private AdvancedComparer(IAdvancedComparer a, IComparer c, IEqualityCompar } } } - - /// - /// Deserializes the instance of this class. - /// - /// Serialization info. - /// Streaming context. - private AdvancedComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - ComparerImplementation = (IComparer)info.GetValue("ComparerImplementation", WellKnownTypes.Object); - EqualityComparerImplementation = (IEqualityComparer)info.GetValue("EqualityComparerImplementation", WellKnownTypes.Object); - // Below code is the same between both primary constructors - if (Implementation!=null) { - Provider = Implementation.Provider; - ComparisonRules = Implementation.ComparisonRules; - ValueTypeComparerBase vtc = Implementation as ValueTypeComparerBase; - SystemComparer sc = Implementation as SystemComparer; - // Trying to get faster delegates - if (sc!=null) { - if (ComparisonRules.Value.Direction==Direction.Positive) - Compare = SystemComparerStruct.Instance.Compare; - Equals = SystemComparerStruct.Instance.Equals; - GetHashCode = SystemComparerStruct.Instance.GetHashCode; - } - else if (vtc!=null) { - if (ComparisonRules.Value.Direction==Direction.Positive && vtc.UsesDefaultCompare) - Compare = SystemComparerStruct.Instance.Compare; - if (vtc.UsesDefaultEquals) - Equals = SystemComparerStruct.Instance.Equals; - if (vtc.UsesDefaultGetHashCode) - GetHashCode = SystemComparerStruct.Instance.GetHashCode; - } - // Setting interface comparers, if unassigned - if (Compare==null) - Compare = ComparerImplementation.Compare; - if (Equals==null) - Equals = EqualityComparerImplementation.Equals; - if (GetHashCode==null) - GetHashCode = EqualityComparerImplementation.GetHashCode; - GetNearestValue = Implementation.GetNearestValue; - ApplyRules = Implementation.ApplyRules; - ValueRangeInfo = Implementation.ValueRangeInfo; - } - else { - ComparisonRules = ComparisonRules.Positive; - if (ComparerImplementation!=null) - Compare = ComparerImplementation.Compare; - if (EqualityComparerImplementation!=null) { - Equals = EqualityComparerImplementation.Equals; - GetHashCode = EqualityComparerImplementation.GetHashCode; - } - } - } - - /// - [SecurityCritical] - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddValue("ComparerImplementation", ComparerImplementation); - info.AddValue("EqualityComparerImplementation", EqualityComparerImplementation); - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Comparison/AdvancedComparerBase.cs b/Orm/Xtensive.Orm/Comparison/AdvancedComparerBase.cs index d6c01121a2..326bbfecab 100644 --- a/Orm/Xtensive.Orm/Comparison/AdvancedComparerBase.cs +++ b/Orm/Xtensive.Orm/Comparison/AdvancedComparerBase.cs @@ -8,10 +8,7 @@ using System.Collections; using System.Collections.Concurrent; using System.Diagnostics; -using System.Runtime.Serialization; -using System.Security; using Xtensive.Arithmetic; -using Xtensive.Collections; using Xtensive.Core; @@ -21,17 +18,15 @@ namespace Xtensive.Comparison /// Base class for implementations. /// /// The type to compare. - [Serializable] - public abstract class AdvancedComparerBase: IAdvancedComparer, - ISerializable, - IDeserializationCallback + public abstract class AdvancedComparerBase: IAdvancedComparer { private static Arithmetic cachedArithmetic; - [NonSerialized] + + private readonly IComparerProvider provider; + private ConcurrentDictionary<(ComparisonRules, AdvancedComparerBase), AdvancedComparer> cachedComparers = new ConcurrentDictionary<(ComparisonRules, AdvancedComparerBase), AdvancedComparer>(); - private IComparerProvider provider; private ValueRangeInfo valueRangeInfo; /// @@ -162,40 +157,5 @@ public AdvancedComparerBase(IComparerProvider provider, ComparisonRules comparis ComparisonRules = comparisonRules; DefaultDirectionMultiplier = comparisonRules.Value.Direction == Direction.Negative ? -1 : 1; } - - public AdvancedComparerBase(SerializationInfo info, StreamingContext context) - { - provider = (IComparerProvider) info.GetValue(nameof(provider), typeof(IComparerProvider)); - valueRangeInfo = (ValueRangeInfo) info.GetValue(nameof(valueRangeInfo), typeof(ValueRangeInfo)); - ComparisonRules = (ComparisonRules) info.GetValue(nameof(ComparisonRules), typeof(ComparisonRules)); - DefaultDirectionMultiplier = info.GetInt32(nameof(DefaultDirectionMultiplier)); - } - - /// - /// Performs post-deserialization actions. - /// - /// - public virtual void OnDeserialization(object sender) - { - if (provider == null) { - provider = ComparerProvider.Default; - } - else if (provider.GetType() == typeof(ComparerProvider)) { - provider = ComparerProvider.Default; - } - else if (provider is SystemComparerProvider) { - provider = ComparerProvider.System; - } - cachedComparers = new ConcurrentDictionary<(ComparisonRules, AdvancedComparerBase), AdvancedComparer>(); - } - - [SecurityCritical] - public virtual void GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue(nameof(provider), provider, provider.GetType()); - info.AddValue(nameof(valueRangeInfo), valueRangeInfo, valueRangeInfo.GetType()); - info.AddValue(nameof(ComparisonRules), ComparisonRules, ComparisonRules.GetType()); - info.AddValue(nameof(DefaultDirectionMultiplier), DefaultDirectionMultiplier); - } } } diff --git a/Orm/Xtensive.Orm/Comparison/AdvancedComparerStruct.cs b/Orm/Xtensive.Orm/Comparison/AdvancedComparerStruct.cs index c8de58fd89..edb1dcb4bb 100644 --- a/Orm/Xtensive.Orm/Comparison/AdvancedComparerStruct.cs +++ b/Orm/Xtensive.Orm/Comparison/AdvancedComparerStruct.cs @@ -6,9 +6,6 @@ using System; using System.Collections.Generic; -using System.Runtime.Serialization; -using System.Security; -using System.Security.Permissions; using Xtensive.Core; @@ -18,8 +15,7 @@ namespace Xtensive.Comparison /// A struct providing faster access for key delegates. /// /// The type of generic argument. - [Serializable] - public readonly struct AdvancedComparerStruct: ISerializable + public readonly struct AdvancedComparerStruct { /// /// Gets for comparer. @@ -98,27 +94,5 @@ private AdvancedComparerStruct(AdvancedComparer comparer) GetNearestValue = Comparer?.GetNearestValue; ValueRangeInfo = Comparer?.ValueRangeInfo; } - - /// - /// Deserializes the instance of this class. - /// - /// Serialization info. - /// Streaming context. - private AdvancedComparerStruct(SerializationInfo info, StreamingContext context) - { - Comparer = (AdvancedComparer)info.GetValue("Comparer", typeof(AdvancedComparer)); - Compare = Comparer?.Compare; - Equals = Comparer?.Equals; - GetHashCode = Comparer?.GetHashCode; - GetNearestValue = Comparer?.GetNearestValue; - ValueRangeInfo = Comparer?.ValueRangeInfo; - } - - /// - [SecurityCritical] - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue("Comparer", Comparer); - } } } diff --git a/Orm/Xtensive.Orm/Comparison/CastingComparer.cs b/Orm/Xtensive.Orm/Comparison/CastingComparer.cs index b97c95dec9..e4e175b427 100644 --- a/Orm/Xtensive.Orm/Comparison/CastingComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/CastingComparer.cs @@ -1,14 +1,12 @@ -// Copyright (C) 2008-2021 Xtensive LLC. +// Copyright (C) 2008-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: // Created: 2008.03.06 using System; -using System.Runtime.Serialization; using Xtensive.Conversion; using Xtensive.Core; -using Xtensive.Reflection; namespace Xtensive.Comparison @@ -18,20 +16,14 @@ namespace Xtensive.Comparison /// /// The type to compare. /// The base type of to provide a comparer for. - [Serializable] public sealed class CastingComparer: AdvancedComparerBase { - private class AsymmetricCompareHandler : + private class AsymmetricCompareHandler(Func baseCompare) : IComparer { - private readonly Func baseCompare; + private readonly Func baseCompare = baseCompare; public int Compare(TTarget x, TSecond y) => baseCompare(ToSource(x), y); - - public AsymmetricCompareHandler(Func baseCompare) - { - this.baseCompare = baseCompare; - } } private static readonly Converter ToSource = AdvancedConverterStruct.Default.Convert; @@ -88,10 +80,5 @@ public CastingComparer(AdvancedComparer sourceComparer) vi.HasDeltaValue, vi.HasDeltaValue ? ToTarget(vi.DeltaValue) : default(TTarget)); } - - public CastingComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Comparison/ComparerProvider.cs b/Orm/Xtensive.Orm/Comparison/ComparerProvider.cs index 1adec5cc24..3035995157 100644 --- a/Orm/Xtensive.Orm/Comparison/ComparerProvider.cs +++ b/Orm/Xtensive.Orm/Comparison/ComparerProvider.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Runtime.Serialization; using Xtensive.Core; using Xtensive.Reflection; @@ -17,7 +16,6 @@ namespace Xtensive.Comparison /// Default provider. /// Provides default comparer for the specified type. /// - [Serializable] public class ComparerProvider : AssociateProvider, IComparerProvider { @@ -58,14 +56,14 @@ public virtual AdvancedComparer GetComparer() protected override TAssociate CreateAssociate(out Type foundFor) { var associate = base.CreateAssociate(out foundFor); - if (associate != null) { + if (associate is not null) { return associate; } // Ok, null, but probably just because type cast has failed; // let's try to wrap it. TKey is type for which we're getting // the comparer. var comparer = base.CreateAssociate(out foundFor); - if (foundFor == null) { + if (foundFor is null) { if (CoreLog.IsLogged(Orm.Logging.LogLevel.Warning)) { CoreLog.Warning(nameof(Strings.LogCantFindAssociateFor), TypeSuffixes.ToDelimitedString(" \\ "), @@ -77,8 +75,8 @@ protected override TAssociate CreateAssociate(out Type foundFo if (foundFor == typeof(TKey)) { return (TAssociate) comparer; } - associate = BaseComparerWrapperType.Activate(new[] { typeof(TKey), foundFor }, ConstructorParams) as TAssociate; - if (associate != null) { + associate = BaseComparerWrapperType.Activate([typeof(TKey), foundFor], ConstructorParams) as TAssociate; + if (associate is not null) { if (CoreLog.IsLogged(Orm.Logging.LogLevel.Warning)) { CoreLog.Warning(nameof(Strings.LogGenericAssociateIsUsedFor), BaseComparerWrapperType.GetShortName(), @@ -118,14 +116,10 @@ protected override TResult ConvertAssociate(TAssociat /// protected ComparerProvider() { - TypeSuffixes = new[] { "Comparer" }; - ConstructorParams = new object[] { this, ComparisonRules.Positive }; + TypeSuffixes = ["Comparer"]; + ConstructorParams = [this, ComparisonRules.Positive]; AddHighPriorityLocation(BaseComparerWrapperType.Assembly, BaseComparerWrapperType.Namespace); } - protected ComparerProvider(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } diff --git a/Orm/Xtensive.Orm/Comparison/ComparisonRule.cs b/Orm/Xtensive.Orm/Comparison/ComparisonRule.cs index b38e14d4cf..0c1c1c2dc2 100644 --- a/Orm/Xtensive.Orm/Comparison/ComparisonRule.cs +++ b/Orm/Xtensive.Orm/Comparison/ComparisonRule.cs @@ -6,8 +6,6 @@ using System; using System.Globalization; -using System.Runtime.Serialization; -using System.Security; using Xtensive.Core; namespace Xtensive.Comparison @@ -15,10 +13,8 @@ namespace Xtensive.Comparison /// /// Describes how to compare values of comparable objects. /// - [Serializable] public readonly struct ComparisonRule : - IEquatable, - ISerializable + IEquatable { /// /// Predefined rule with = . @@ -181,27 +177,5 @@ public ComparisonRule(Direction direction, CultureInfo culture) Direction = direction; Culture = culture; } - - private ComparisonRule(SerializationInfo info, StreamingContext context) - { - if (info == null) { - throw new ArgumentNullException(nameof(info)); - } - Direction = (Direction) info.GetSByte(nameof(Direction)); - var cultureId = info.GetInt32(nameof(Culture)); - Culture = (cultureId != int.MinValue) ? CultureInfo.GetCultureInfo(cultureId) : null; - } - - [SecurityCritical] - void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) - { - if(info == null) { - throw new ArgumentNullException(nameof(info)); - } - info.AddValue(nameof(Direction), (sbyte) Direction); - - var cultureId = (Culture != null) ? Culture.LCID : int.MinValue; - info.AddValue(nameof(Culture), cultureId); - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Comparison/ComparisonRules.cs b/Orm/Xtensive.Orm/Comparison/ComparisonRules.cs index eb31a4343e..28378b48e8 100644 --- a/Orm/Xtensive.Orm/Comparison/ComparisonRules.cs +++ b/Orm/Xtensive.Orm/Comparison/ComparisonRules.cs @@ -11,13 +11,11 @@ using Xtensive.Core; - namespace Xtensive.Comparison { /// /// Ordering rule for comparer. /// - [Serializable] public sealed class ComparisonRules : IEquatable { @@ -307,7 +305,7 @@ public ComparisonRules(ComparisonRule value, ComparisonRules[] composite, Compar } } - private ComparisonRules(ComparisonRule value, ComparisonRules[] composite, bool ignore) + private ComparisonRules(ComparisonRule value, ComparisonRules[] composite, bool _) { this.value = value; this.composite = composite; diff --git a/Orm/Xtensive.Orm/Comparison/Internals/ArrayComparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/ArrayComparer.cs index e8a04998db..a66468ea9e 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/ArrayComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/ArrayComparer.cs @@ -1,15 +1,13 @@ -// Copyright (C) 2008-2021 Xtensive LLC. +// Copyright (C) 2008-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Gamzov // Created: 2008.01.16 using System; -using System.Runtime.Serialization; namespace Xtensive.Comparison { - [Serializable] internal sealed class ArrayComparer : WrappingComparer, ISystemComparer { @@ -82,10 +80,5 @@ public ArrayComparer(IComparerProvider provider, ComparisonRules comparisonRules { ValueRangeInfo = new ValueRangeInfo(true, null, false, null, false, null); } - - public ArrayComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } diff --git a/Orm/Xtensive.Orm/Comparison/Internals/AssemblyComparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/AssemblyComparer.cs index 52f34e71d5..83fb329ee9 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/AssemblyComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/AssemblyComparer.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2008-2021 Xtensive LLC. +// Copyright (C) 2008-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alex Yakunin @@ -6,11 +6,9 @@ using System; using System.Reflection; -using System.Runtime.Serialization; namespace Xtensive.Comparison { - [Serializable] internal sealed class AssemblyComparer: WrappingComparer, ISystemComparer { @@ -44,10 +42,5 @@ public AssemblyComparer(IComparerProvider provider, ComparisonRules comparisonRu : base(provider, comparisonRules) { } - - public AssemblyComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Comparison/Internals/BaseComparerWrapper.cs b/Orm/Xtensive.Orm/Comparison/Internals/BaseComparerWrapper.cs index 3c9e8be56b..4cda9d3211 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/BaseComparerWrapper.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/BaseComparerWrapper.cs @@ -1,16 +1,14 @@ -// Copyright (C) 2008-2021 Xtensive LLC. +// Copyright (C) 2008-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alex Yakunin // Created: 2008.01.22 using System; -using System.Runtime.Serialization; using Xtensive.Core; namespace Xtensive.Comparison { - [Serializable] internal class BaseComparerWrapper: WrappingComparer where T: TBase { @@ -32,10 +30,5 @@ public BaseComparerWrapper(IComparerProvider provider, ComparisonRules compariso : base(provider, comparisonRules) { } - - public BaseComparerWrapper(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Comparison/Internals/BooleanComparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/BooleanComparer.cs index 153784f943..0dc443af29 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/BooleanComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/BooleanComparer.cs @@ -1,17 +1,15 @@ -// Copyright (C) 2007-2021 Xtensive LLC. +// Copyright (C) 2007-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Nick Svetlov // Created: 2007.11.28 using System; -using System.Runtime.Serialization; using Xtensive.Core; namespace Xtensive.Comparison { - [Serializable] internal sealed class BooleanComparer : ValueTypeComparer { protected override BooleanComparer CreateNew(ComparisonRules rules) => new(Provider, ComparisonRules.Combine(rules)); @@ -33,10 +31,5 @@ public BooleanComparer(IComparerProvider provider, ComparisonRules comparisonRul { ValueRangeInfo = new ValueRangeInfo(true, false, true, true, true, true); } - - public BooleanComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Comparison/Internals/ByteComparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/ByteComparer.cs index f6a6b834ed..f5fcbbf6de 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/ByteComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/ByteComparer.cs @@ -1,15 +1,13 @@ -// Copyright (C) 2007-2021 Xtensive LLC. +// Copyright (C) 2007-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Nick Svetlov // Created: 2007.11.28 using System; -using System.Runtime.Serialization; namespace Xtensive.Comparison { - [Serializable] internal sealed class ByteComparer : ValueTypeComparer { protected override ByteComparer CreateNew(ComparisonRules rules) => new(Provider, ComparisonRules.Combine(rules)); @@ -22,10 +20,5 @@ public ByteComparer(IComparerProvider provider, ComparisonRules comparisonRules) { ValueRangeInfo = new ValueRangeInfo(true, byte.MinValue, true, byte.MaxValue, true, 1); } - - public ByteComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Comparison/Internals/CharComparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/CharComparer.cs index 136524c2f0..27effe3969 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/CharComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/CharComparer.cs @@ -1,15 +1,13 @@ -// Copyright (C) 2007-2021 Xtensive LLC. +// Copyright (C) 2007-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Nick Svetlov // Created: 2007.11.28 using System; -using System.Runtime.Serialization; namespace Xtensive.Comparison { - [Serializable] internal sealed class CharComparer : ValueTypeComparer { protected override CharComparer CreateNew(ComparisonRules rules) => new(Provider, ComparisonRules.Combine(rules)); @@ -22,10 +20,5 @@ public CharComparer(IComparerProvider provider, ComparisonRules comparisonRules) { ValueRangeInfo = new ValueRangeInfo(true, char.MinValue, true, char.MaxValue, true, '\x0001'); } - - public CharComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Comparison/Internals/DecimalComparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/DecimalComparer.cs index 579df40e22..b365670573 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/DecimalComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/DecimalComparer.cs @@ -1,15 +1,13 @@ -// Copyright (C) 2007-2021 Xtensive LLC. +// Copyright (C) 2007-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Nick Svetlov // Created: 2007.11.28 using System; -using System.Runtime.Serialization; namespace Xtensive.Comparison { - [Serializable] internal sealed class DecimalComparer : ValueTypeComparer { protected override DecimalComparer CreateNew(ComparisonRules rules) => new(Provider, ComparisonRules.Combine(rules)); @@ -22,10 +20,5 @@ public DecimalComparer(IComparerProvider provider, ComparisonRules comparisonRul { ValueRangeInfo = new ValueRangeInfo(true, decimal.MinValue, true, decimal.MaxValue, false, 0m); } - - public DecimalComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Comparison/Internals/DoubleComparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/DoubleComparer.cs index 1a686c910a..5a9dcfdff2 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/DoubleComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/DoubleComparer.cs @@ -1,15 +1,13 @@ -// Copyright (C) 2007-2021 Xtensive LLC. +// Copyright (C) 2007-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Nick Svetlov // Created: 2007.11.28 using System; -using System.Runtime.Serialization; namespace Xtensive.Comparison { - [Serializable] internal sealed class DoubleComparer : ValueTypeComparer { protected override DoubleComparer CreateNew(ComparisonRules rules) => new(Provider, ComparisonRules.Combine(rules)); @@ -22,10 +20,5 @@ public DoubleComparer(IComparerProvider provider, ComparisonRules comparisonRule { ValueRangeInfo = new ValueRangeInfo(true, double.MinValue, true, double.MaxValue, false, 0d); } - - public DoubleComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Comparison/Internals/EnumComparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/EnumComparer.cs index d0c7dd0a54..22488968c2 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/EnumComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/EnumComparer.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2008-2021 Xtensive LLC. +// Copyright (C) 2008-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alex Yakunin @@ -6,15 +6,11 @@ using System; using System.Collections.Generic; -using System.Runtime.Serialization; -using System.Security; using Xtensive.Core; - using Xtensive.Reflection; namespace Xtensive.Comparison { - [Serializable] internal sealed class EnumComparer : WrappingComparer, ISystemComparer where TEnum: struct @@ -102,17 +98,5 @@ public EnumComparer(IComparerProvider provider, ComparisonRules comparisonRules) true, values[valueCount - 1], false, default(TEnum)); } - - public EnumComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - valueToIndex = new Dictionary(); - values = BuildValues(out var valueCount); - maxIndex = valueCount - 1; - ValueRangeInfo = new ValueRangeInfo( - true, values[0], - true, values[valueCount - 1], - false, default(TEnum)); - } } } diff --git a/Orm/Xtensive.Orm/Comparison/Internals/EnumerableInterfaceComparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/EnumerableInterfaceComparer.cs index eca2e7de7e..e90cf7566d 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/EnumerableInterfaceComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/EnumerableInterfaceComparer.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2008-2021 Xtensive LLC. +// Copyright (C) 2008-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Gamzov @@ -6,11 +6,9 @@ using System; using System.Collections.Generic; -using System.Runtime.Serialization; namespace Xtensive.Comparison { - [Serializable] internal sealed class EnumerableInterfaceComparer : WrappingComparer, ISystemComparer where TEnumerable: class, IEnumerable @@ -108,10 +106,5 @@ public EnumerableInterfaceComparer(IComparerProvider provider, ComparisonRules c { ValueRangeInfo = new ValueRangeInfo(true, null, false, null, false, null); } - - public EnumerableInterfaceComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } diff --git a/Orm/Xtensive.Orm/Comparison/Internals/GuidComparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/GuidComparer.cs index 63be565e9b..6be7a112bd 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/GuidComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/GuidComparer.cs @@ -1,15 +1,13 @@ -// Copyright (C) 2003-2010 Xtensive LLC. +// Copyright (C) 2007-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Nick Svetlov // Created: 2007.11.28 using System; -using System.Runtime.Serialization; namespace Xtensive.Comparison { - [Serializable] internal sealed class GuidComparer: ValueTypeComparer { protected override GuidComparer CreateNew(ComparisonRules rules) => new(Provider, ComparisonRules.Combine(rules)); @@ -25,10 +23,5 @@ public GuidComparer(IComparerProvider provider, ComparisonRules comparisonRules) true, new Guid(0xFFFFFFFF, 0xFFFF, 0xFFFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF), false, Guid.Empty); } - - public GuidComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Comparison/Internals/Int16Comparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/Int16Comparer.cs index 6ddd8d06bd..9634a260f1 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/Int16Comparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/Int16Comparer.cs @@ -1,15 +1,13 @@ -// Copyright (C) 2007-2021 Xtensive LLC. +// Copyright (C) 2007-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Nick Svetlov // Created: 2007.11.28 using System; -using System.Runtime.Serialization; namespace Xtensive.Comparison { - [Serializable] internal sealed class Int16Comparer : ValueTypeComparer { protected override Int16Comparer CreateNew(ComparisonRules rules) => new(Provider, ComparisonRules.Combine(rules)); @@ -22,10 +20,5 @@ public Int16Comparer(IComparerProvider provider, ComparisonRules comparisonRules { ValueRangeInfo = new ValueRangeInfo(true, short.MinValue, true, short.MaxValue, true, 1); } - - public Int16Comparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Comparison/Internals/Int32Comparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/Int32Comparer.cs index 9e77defa43..eeef5769a1 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/Int32Comparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/Int32Comparer.cs @@ -1,15 +1,14 @@ -// Copyright (C) 2007-2021 Xtensive LLC. +// Copyright (C) 2007-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Nick Svetlov // Created: 2007.11.28 using System; -using System.Runtime.Serialization; +using System.Collections.Generic; namespace Xtensive.Comparison { - [Serializable] internal sealed class Int32Comparer : ValueTypeComparer { protected override Int32Comparer CreateNew(ComparisonRules rules) => new(Provider, ComparisonRules.Combine(rules)); @@ -20,12 +19,8 @@ internal sealed class Int32Comparer : ValueTypeComparer public Int32Comparer(IComparerProvider provider, ComparisonRules comparisonRules) : base(provider, comparisonRules) { + var abc = EqualityComparer.Default; ValueRangeInfo = new ValueRangeInfo(true, int.MinValue, true, int.MaxValue, true, 1); } - - public Int32Comparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Comparison/Internals/Int64Comparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/Int64Comparer.cs index df62ffc003..ef68fd4cb3 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/Int64Comparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/Int64Comparer.cs @@ -1,15 +1,13 @@ -// Copyright (C) 2007-2021 Xtensive LLC. +// Copyright (C) 2007-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Nick Svetlov // Created: 2007.11.28 using System; -using System.Runtime.Serialization; namespace Xtensive.Comparison { - [Serializable] internal sealed class Int64Comparer : ValueTypeComparer { protected override Int64Comparer CreateNew(ComparisonRules rules) => new(Provider, ComparisonRules.Combine(rules)); @@ -22,10 +20,5 @@ public Int64Comparer(IComparerProvider provider, ComparisonRules comparisonRules { ValueRangeInfo = new ValueRangeInfo(true, long.MinValue, true, long.MaxValue, true, 1); } - - public Int64Comparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Comparison/Internals/KeyValuePairComparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/KeyValuePairComparer.cs index b691600c58..27313738ff 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/KeyValuePairComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/KeyValuePairComparer.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2008-2021 Xtensive LLC. +// Copyright (C) 2008-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alex Yakunin @@ -6,12 +6,10 @@ using System; using System.Collections.Generic; -using System.Runtime.Serialization; using Xtensive.Core; namespace Xtensive.Comparison { - [Serializable] internal sealed class KeyValuePairComparer: WrappingComparer, T1, T2>, ISystemComparer> { @@ -59,10 +57,5 @@ public KeyValuePairComparer(IComparerProvider provider, ComparisonRules comparis } ValueRangeInfo = new ValueRangeInfo>(hasMinValue, minValue, hasMaxValue, maxValue, hasDeltaValue, deltaValue); } - - public KeyValuePairComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } diff --git a/Orm/Xtensive.Orm/Comparison/Internals/NullableComparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/NullableComparer.cs index 4727b41a0d..f9dcbe8323 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/NullableComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/NullableComparer.cs @@ -1,26 +1,20 @@ -// Copyright (C) 2008-2021 Xtensive LLC. +// Copyright (C) 2008-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: // Created: 2008.01.23 using System; -using System.Runtime.Serialization; -using System.Security; using Xtensive.Core; namespace Xtensive.Comparison { - [Serializable] internal sealed class NullableComparer: WrappingComparer where T: struct { - [NonSerialized] - private Func currentBaseCompare; - [NonSerialized] - private Predicate currentBaseEquals; - [NonSerialized] - private Func currentBaseGetHashCode; + private readonly Func currentBaseCompare; + private readonly Predicate currentBaseEquals; + private readonly Func currentBaseGetHashCode; protected override NullableComparer CreateNew(ComparisonRules rules) => new(Provider, ComparisonRules.Combine(rules)); @@ -67,7 +61,10 @@ public override int GetHashCode(T? obj) return BaseComparer.GetNearestValue(value.GetValueOrDefault(), direction); } - private void Initialize() + // Constructors + + public NullableComparer(IComparerProvider provider, ComparisonRules comparisonRules) + : base(provider, comparisonRules) { var baseValueRangeInfo = BaseComparer.ValueRangeInfo; ValueRangeInfo = @@ -78,29 +75,9 @@ private void Initialize() baseValueRangeInfo.HasDeltaValue, baseValueRangeInfo.HasDeltaValue ? baseValueRangeInfo.DeltaValue : default(T)); - currentBaseCompare = BaseComparer.Compare; - currentBaseEquals = BaseComparer.Equals; + currentBaseCompare = BaseComparer.Compare; + currentBaseEquals = BaseComparer.Equals; currentBaseGetHashCode = BaseComparer.GetHashCode; } - - - // Constructors - - public NullableComparer(IComparerProvider provider, ComparisonRules comparisonRules) - : base(provider, comparisonRules) - { - Initialize(); - } - - public NullableComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - - public override void OnDeserialization(object sender) - { - base.OnDeserialization(sender); - Initialize(); - } } } diff --git a/Orm/Xtensive.Orm/Comparison/Internals/ObjectComparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/ObjectComparer.cs index 9c6d5da60b..11e56af4d7 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/ObjectComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/ObjectComparer.cs @@ -1,24 +1,19 @@ -// Copyright (C) 2008-2021 Xtensive LLC. +// Copyright (C) 2008-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alex Yakunin // Created: 2008.01.23 using System; -using System.Collections.Generic; -using System.Runtime.Serialization; namespace Xtensive.Comparison { // Fall back to Comparer.Default, EqualityComparer.Default - [Serializable] internal sealed class ObjectComparer: AdvancedComparerBase where T: class, IComparable, IEquatable { - [NonSerialized] - private AdvancedComparer systemComparer; - [NonSerialized] - private int nullHashCode; + private readonly AdvancedComparer systemComparer; + private readonly int nullHashCode; protected override ObjectComparer CreateNew(ComparisonRules rules) => new(Provider, ComparisonRules.Combine(rules)); @@ -47,31 +42,15 @@ public override bool Equals(T x, T y) public override int GetHashCode(T obj) => ReferenceEquals(obj, null) ? nullHashCode : obj.GetHashCode(); - private void Initialize() - { - systemComparer = new AdvancedComparer(null); - nullHashCode = systemComparer.GetHashCode(null); - ValueRangeInfo = systemComparer.ValueRangeInfo; - } - // Constructors public ObjectComparer(IComparerProvider provider, ComparisonRules comparisonRules) : base(provider, comparisonRules) { - Initialize(); - } - - public ObjectComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - - public override void OnDeserialization(object sender) - { - base.OnDeserialization(sender); - Initialize(); + systemComparer = new AdvancedComparer(null); + nullHashCode = systemComparer.GetHashCode(null); + ValueRangeInfo = systemComparer.ValueRangeInfo; } } } diff --git a/Orm/Xtensive.Orm/Comparison/Internals/PairComparer{T1,T2}.cs b/Orm/Xtensive.Orm/Comparison/Internals/PairComparer{T1,T2}.cs index 37decfcb85..976daa8202 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/PairComparer{T1,T2}.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/PairComparer{T1,T2}.cs @@ -1,16 +1,14 @@ -// Copyright (C) 2008-2021 Xtensive LLC. +// Copyright (C) 2008-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alex Yakunin // Created: 2008.01.22 using System; -using System.Runtime.Serialization; using Xtensive.Core; namespace Xtensive.Comparison { - [Serializable] internal sealed class PairComparer: WrappingComparer, T1, T2> { protected override PairComparer CreateNew(ComparisonRules rules) => new(Provider, ComparisonRules.Combine(rules)); @@ -33,7 +31,10 @@ public override int GetHashCode(Pair obj) public override Pair GetNearestValue(Pair value, Direction direction) => new Pair(value.First, BaseComparer2.GetNearestValue(value.Second, direction)); - private void Initialize() + // Constructors + + public PairComparer(IComparerProvider provider, ComparisonRules comparisonRules) + : base(provider, comparisonRules) { Pair minValue, maxValue, deltaValue; bool hasMinValue = false, hasMaxValue = false, hasDeltaValue = false; @@ -53,20 +54,5 @@ private void Initialize() } ValueRangeInfo = new ValueRangeInfo>(hasMinValue, minValue, hasMaxValue, maxValue, hasDeltaValue, deltaValue); } - - - // Constructors - - public PairComparer(IComparerProvider provider, ComparisonRules comparisonRules) - : base(provider, comparisonRules) - { - Initialize(); - } - - public PairComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - Initialize(); - } } } diff --git a/Orm/Xtensive.Orm/Comparison/Internals/PairComparer{T}.cs b/Orm/Xtensive.Orm/Comparison/Internals/PairComparer{T}.cs index 8bd508ce66..8203b3da56 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/PairComparer{T}.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/PairComparer{T}.cs @@ -1,16 +1,14 @@ -// Copyright (C) 2008-2021 Xtensive LLC. +// Copyright (C) 2008-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alex Yakunin // Created: 2008.01.22 using System; -using System.Runtime.Serialization; using Xtensive.Core; namespace Xtensive.Comparison { - [Serializable] internal sealed class PairComparer: WrappingComparer, T> { protected override PairComparer CreateNew(ComparisonRules rules) => new(Provider, ComparisonRules.Combine(rules)); @@ -33,7 +31,11 @@ public override int GetHashCode(Pair obj) public override Pair GetNearestValue(Pair value, Direction direction) => new Pair(value.First, BaseComparer.GetNearestValue(value.Second, direction)); - private void Initialize() + + // Constructors + + public PairComparer(IComparerProvider provider, ComparisonRules comparisonRules) + : base(provider, comparisonRules) { Pair minValue, maxValue, deltaValue; bool hasMinValue = false, hasMaxValue = false, hasDeltaValue = false; @@ -53,20 +55,5 @@ private void Initialize() } ValueRangeInfo = new ValueRangeInfo>(hasMinValue, minValue, hasMaxValue, maxValue, hasDeltaValue, deltaValue); } - - - // Constructors - - public PairComparer(IComparerProvider provider, ComparisonRules comparisonRules) - : base(provider, comparisonRules) - { - Initialize(); - } - - public PairComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - Initialize(); - } } } diff --git a/Orm/Xtensive.Orm/Comparison/Internals/SByteComparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/SByteComparer.cs index 5ae937bbf9..a3fa940ec3 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/SByteComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/SByteComparer.cs @@ -1,15 +1,13 @@ -// Copyright (C) 2007-2021 Xtensive LLC. +// Copyright (C) 2007-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Nick Svetlov // Created: 2007.11.28 using System; -using System.Runtime.Serialization; namespace Xtensive.Comparison { - [Serializable] internal sealed class SByteComparer : ValueTypeComparer { protected override SByteComparer CreateNew(ComparisonRules rules) => new(Provider, ComparisonRules.Combine(rules)); @@ -22,10 +20,5 @@ public SByteComparer(IComparerProvider provider, ComparisonRules comparisonRules { ValueRangeInfo = new ValueRangeInfo(true, sbyte.MinValue, true, sbyte.MaxValue, true, 1); } - - public SByteComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Comparison/Internals/SingleComparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/SingleComparer.cs index f6b790a9ef..5fc79d4d37 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/SingleComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/SingleComparer.cs @@ -1,15 +1,13 @@ -// Copyright (C) 2007-2021 Xtensive LLC. +// Copyright (C) 2007-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Gamzov // Created: 2007.11.14 using System; -using System.Runtime.Serialization; namespace Xtensive.Comparison { - [Serializable] internal sealed class SingleComparer : ValueTypeComparer { protected override SingleComparer CreateNew(ComparisonRules rules) => new(Provider, ComparisonRules.Combine(rules)); @@ -22,10 +20,5 @@ public SingleComparer(IComparerProvider provider, ComparisonRules comparisonRule { ValueRangeInfo = new ValueRangeInfo(true, float.MinValue, true, float.MaxValue, false, default(float)); } - - public SingleComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Comparison/Internals/StringComparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/StringComparer.cs index aa749126f1..1f9aaa384c 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/StringComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/StringComparer.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2007-2021 Xtensive LLC. +// Copyright (C) 2007-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Nick Svetlov @@ -6,21 +6,18 @@ using System; using System.Globalization; -using System.Runtime.Serialization; using Xtensive.Core; namespace Xtensive.Comparison { - [Serializable] internal sealed class StringComparer: AdvancedComparerBase, ISystemComparer { private static readonly int EmptyHash = string.Empty.GetHashCode(); - [NonSerialized] - private Func stringCompare; - [NonSerialized] - private Func stringIsSuffix; + + private readonly Func stringCompare; + private readonly Func stringIsSuffix; protected override StringComparer CreateNew(ComparisonRules rules) => new(Provider, ComparisonRules.Combine(rules)); @@ -85,20 +82,6 @@ public override string GetNearestValue(string value, Direction direction) } } - private void Initialize() - { - ValueRangeInfo = new ValueRangeInfo(true, null, false, null, false, null); - var culture = ComparisonRules.Value.Culture; - if (culture != null) { - stringCompare = culture.CompareInfo.Compare; - stringIsSuffix = culture.CompareInfo.IsSuffix; - } - else { - stringCompare = CompareOrdinal; - stringIsSuffix = CultureInfo.InvariantCulture.CompareInfo.IsSuffix; - } - } - private static int CompareOrdinal(string first, string second, CompareOptions options) => string.CompareOrdinal(first, second); @@ -108,18 +91,16 @@ private static int CompareOrdinal(string first, string second, CompareOptions op public StringComparer(IComparerProvider provider, ComparisonRules comparisonRules) : base(provider, comparisonRules) { - Initialize(); - } - - public StringComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - - public override void OnDeserialization(object sender) - { - base.OnDeserialization(sender); - Initialize(); + ValueRangeInfo = new ValueRangeInfo(true, null, false, null, false, null); + var culture = ComparisonRules.Value.Culture; + if (culture != null) { + stringCompare = culture.CompareInfo.Compare; + stringIsSuffix = culture.CompareInfo.IsSuffix; + } + else { + stringCompare = CompareOrdinal; + stringIsSuffix = CultureInfo.InvariantCulture.CompareInfo.IsSuffix; + } } } } diff --git a/Orm/Xtensive.Orm/Comparison/Internals/SystemComparerStruct.cs b/Orm/Xtensive.Orm/Comparison/Internals/SystemComparerStruct.cs index ee6930f159..add3baec97 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/SystemComparerStruct.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/SystemComparerStruct.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Generic; -using System.Runtime.Serialization; using Xtensive.Core; namespace Xtensive.Comparison diff --git a/Orm/Xtensive.Orm/Comparison/Internals/TupleComparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/TupleComparer.cs index 6b3f54a02d..e790ae7235 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/TupleComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/TupleComparer.cs @@ -1,21 +1,18 @@ -// Copyright (C) 2008-2021 Xtensive LLC. +// Copyright (C) 2008-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alex Yakunin // Created: 2008.01.29 using System; -using System.Runtime.Serialization; using Tuple = Xtensive.Tuples.Tuple; namespace Xtensive.Comparison { - [Serializable] internal sealed class TupleComparer : AdvancedComparerBase, ISystemComparer { - [NonSerialized] - private int nullHashCode; + private readonly int nullHashCode; protected override TupleComparer CreateNew(ComparisonRules rules) => new(Provider, ComparisonRules.Combine(rules)); @@ -31,27 +28,13 @@ public override int GetHashCode(Tuple obj) : obj.GetHashCode(); } - private void Initialize() - => nullHashCode = SystemComparerStruct.Instance.GetHashCode(null); - // Constructors public TupleComparer(IComparerProvider provider, ComparisonRules comparisonRules) : base(provider, comparisonRules) { - Initialize(); - } - - public TupleComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - - public override void OnDeserialization(object sender) - { - base.OnDeserialization(sender); - Initialize(); + nullHashCode = SystemComparerStruct.Instance.GetHashCode(null); } } } diff --git a/Orm/Xtensive.Orm/Comparison/Internals/TupleDescriptorComparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/TupleDescriptorComparer.cs index d1c17f341b..7b29462a0d 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/TupleDescriptorComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/TupleDescriptorComparer.cs @@ -1,21 +1,15 @@ -// Copyright (C) 2008-2021 Xtensive LLC. +// Copyright (C) 2008-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alex Yakunin // Created: 2008.01.22 using System; -using System.Reflection; -using System.Runtime.Serialization; -using Xtensive.Collections; -using Xtensive.Core; - using Xtensive.Tuples; using Tuple = Xtensive.Tuples.Tuple; namespace Xtensive.Comparison { - [Serializable] internal sealed class TupleDescriptorComparer: WrappingComparer, ISystemComparer { @@ -34,14 +28,5 @@ public TupleDescriptorComparer(IComparerProvider provider, ComparisonRules compa : base(provider, comparisonRules) { } - - public TupleDescriptorComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - - public override void OnDeserialization(object sender) - { - } } } diff --git a/Orm/Xtensive.Orm/Comparison/Internals/TypeComparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/TypeComparer.cs index 1182916664..b4077e47f4 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/TypeComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/TypeComparer.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2008-2021 Xtensive LLC. +// Copyright (C) 2008-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alex Yakunin @@ -7,19 +7,14 @@ using System; using System.Collections.Concurrent; using System.Reflection; -using System.Runtime.Serialization; -using Xtensive.Collections; -using Xtensive.Core; namespace Xtensive.Comparison { - [Serializable] internal sealed class TypeComparer: WrappingComparer, ISystemComparer { - [NonSerialized] - private ConcurrentDictionary<(Type, Type, TypeComparer), int> results; + private readonly ConcurrentDictionary<(Type, Type, TypeComparer), int> results = new(); protected override TypeComparer CreateNew(ComparisonRules rules) => new TypeComparer(Provider, ComparisonRules.Combine(rules)); @@ -42,22 +37,12 @@ static int TypeComparison((Type, Type, TypeComparer) tuple) public override int GetHashCode(Type obj) => AdvancedComparerStruct.System.GetHashCode(obj); - private void Initialize() => results = new ConcurrentDictionary<(Type, Type, TypeComparer), int>(); - // Constructors public TypeComparer(IComparerProvider provider, ComparisonRules comparisonRules) : base(provider, comparisonRules) { - Initialize(); } - - public TypeComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - - public override void OnDeserialization(object sender) => Initialize(); } } diff --git a/Orm/Xtensive.Orm/Comparison/Internals/UInt16Comparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/UInt16Comparer.cs index 750ba01718..556c2c2f6e 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/UInt16Comparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/UInt16Comparer.cs @@ -1,15 +1,13 @@ -// Copyright (C) 2007-2021 Xtensive LLC. +// Copyright (C) 2007-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Nick Svetlov // Created: 2007.11.28 using System; -using System.Runtime.Serialization; namespace Xtensive.Comparison { - [Serializable] internal sealed class UInt16Comparer : ValueTypeComparer { protected override UInt16Comparer CreateNew(ComparisonRules rules) => new(Provider, ComparisonRules.Combine(rules)); @@ -22,10 +20,5 @@ public UInt16Comparer(IComparerProvider provider, ComparisonRules comparisonRule { ValueRangeInfo = new ValueRangeInfo(true, ushort.MinValue, true, ushort.MaxValue, true, 1); } - - public UInt16Comparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Comparison/Internals/UInt32Comparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/UInt32Comparer.cs index 37522d85df..5b349842ba 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/UInt32Comparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/UInt32Comparer.cs @@ -1,15 +1,13 @@ -// Copyright (C) 2007-2021 Xtensive LLC. +// Copyright (C) 2007-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Nick Svetlov // Created: 2007.11.28 using System; -using System.Runtime.Serialization; namespace Xtensive.Comparison { - [Serializable] internal sealed class UInt32Comparer : ValueTypeComparer { protected override UInt32Comparer CreateNew(ComparisonRules rules) => new(Provider, ComparisonRules.Combine(rules)); @@ -22,10 +20,5 @@ public UInt32Comparer(IComparerProvider provider, ComparisonRules comparisonRule { ValueRangeInfo = new ValueRangeInfo(true, uint.MinValue, true, uint.MaxValue, true, 1); } - - public UInt32Comparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Comparison/Internals/UInt64Comparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/UInt64Comparer.cs index e928554ff3..191a5fea0c 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/UInt64Comparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/UInt64Comparer.cs @@ -1,15 +1,13 @@ -// Copyright (C) 2007-2021 Xtensive LLC. +// Copyright (C) 2007-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Nick Svetlov // Created: 2007.11.28 using System; -using System.Runtime.Serialization; namespace Xtensive.Comparison { - [Serializable] internal sealed class UInt64Comparer : ValueTypeComparer { protected override UInt64Comparer CreateNew(ComparisonRules rules) => new(Provider, ComparisonRules.Combine(rules)); @@ -22,10 +20,5 @@ public UInt64Comparer(IComparerProvider provider, ComparisonRules comparisonRule { ValueRangeInfo = new ValueRangeInfo(true, ulong.MinValue, true, ulong.MaxValue, true, 1); } - - public UInt64Comparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Comparison/Internals/ValueTypeComparer.cs b/Orm/Xtensive.Orm/Comparison/Internals/ValueTypeComparer.cs index 6bb7a151b9..6e3e75dc21 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/ValueTypeComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/ValueTypeComparer.cs @@ -1,18 +1,16 @@ -// Copyright (C) 2008-2021 Xtensive LLC. +// Copyright (C) 2008-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alex Yakunin // Created: 2008.01.23 using System; -using System.Collections.Generic; using System.Reflection; -using System.Runtime.Serialization; +using Xtensive.Reflection; namespace Xtensive.Comparison { // Fall back to Comparer.Default, EqualityComparer.Default - [Serializable] internal class ValueTypeComparer: ValueTypeComparerBase where T: struct, IComparable, IEquatable { @@ -26,43 +24,28 @@ public override int Compare(T x, T y) public override int GetHashCode(T obj) => obj.GetHashCode(); - private void Initialize() + + // Constructors + + public ValueTypeComparer(IComparerProvider provider, ComparisonRules comparisonRules) + : base(provider, comparisonRules) { var valueTypeComparerType = typeof(ValueTypeComparer); var myType = GetType(); - var tType = typeof (T); + var tType = typeof(T); var searchFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + var mCompare = myType.GetMethod("Compare", searchFlags, null, new Type[] { tType, tType }, null); UsesDefaultCompare = mCompare.DeclaringType == valueTypeComparerType; - var mEquals = myType.GetMethod("Equals", searchFlags, + var mEquals = myType.GetMethod(WellKnown.Object.Equals, searchFlags, null, new Type[] { tType, tType }, null); UsesDefaultEquals = mEquals.DeclaringType == valueTypeComparerType; - var mGetHashCode = myType.GetMethod("GetHashCode", searchFlags, + var mGetHashCode = myType.GetMethod(WellKnown.Object.GetHashCode, searchFlags, null, new Type[] { tType }, null); UsesDefaultGetHashCode = mGetHashCode.DeclaringType == valueTypeComparerType; } - - - // Constructors - - public ValueTypeComparer(IComparerProvider provider, ComparisonRules comparisonRules) - : base(provider, comparisonRules) - { - Initialize(); - } - - public ValueTypeComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - - public override void OnDeserialization(object sender) - { - base.OnDeserialization(sender); - Initialize(); - } } } diff --git a/Orm/Xtensive.Orm/Comparison/Internals/ValueTypeComparerBase.cs b/Orm/Xtensive.Orm/Comparison/Internals/ValueTypeComparerBase.cs index 19a457b3cb..8a4f6485ce 100644 --- a/Orm/Xtensive.Orm/Comparison/Internals/ValueTypeComparerBase.cs +++ b/Orm/Xtensive.Orm/Comparison/Internals/ValueTypeComparerBase.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2008-2021 Xtensive LLC. +// Copyright (C) 2008-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alex Yakunin @@ -6,20 +6,14 @@ using System; using System.Collections.Generic; -using System.Reflection; -using System.Runtime.Serialization; namespace Xtensive.Comparison { // Fall back to Comparer.Default, EqualityComparer.Default - [Serializable] internal abstract class ValueTypeComparerBase: AdvancedComparerBase { - [NonSerialized] public bool UsesDefaultCompare; - [NonSerialized] public bool UsesDefaultEquals; - [NonSerialized] public bool UsesDefaultGetHashCode; @@ -29,10 +23,5 @@ public ValueTypeComparerBase(IComparerProvider provider, ComparisonRules compari : base(provider, comparisonRules) { } - - public ValueTypeComparerBase(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } diff --git a/Orm/Xtensive.Orm/Comparison/ReferenceEqualityComparer.cs b/Orm/Xtensive.Orm/Comparison/ReferenceEqualityComparer.cs index 83ad94a00c..762074e953 100644 --- a/Orm/Xtensive.Orm/Comparison/ReferenceEqualityComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/ReferenceEqualityComparer.cs @@ -16,24 +16,17 @@ namespace Xtensive.Comparison /// Compares two objects by their reference values. /// /// Type of the object to compare. - [Serializable] public sealed class ReferenceEqualityComparer : IEqualityComparer { /// /// Gets the only instance of this type. /// - public static ReferenceEqualityComparer Instance = new ReferenceEqualityComparer(); + public readonly static ReferenceEqualityComparer Instance = new(); /// - public bool Equals(T x, T y) - { - return ReferenceEquals(x, y); - } + public bool Equals(T x, T y) => ReferenceEquals(x, y); /// - public int GetHashCode(T obj) - { - return RuntimeHelpers.GetHashCode(obj); - } + public int GetHashCode(T obj) => RuntimeHelpers.GetHashCode(obj); } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Comparison/SystemComparer.cs b/Orm/Xtensive.Orm/Comparison/SystemComparer.cs index e83903d374..3a693dc86b 100644 --- a/Orm/Xtensive.Orm/Comparison/SystemComparer.cs +++ b/Orm/Xtensive.Orm/Comparison/SystemComparer.cs @@ -1,11 +1,10 @@ -// Copyright (C) 2008-2021 Xtensive LLC. +// Copyright (C) 2008-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alex Yakunin // Created: 2008.02.10 using System; -using System.Runtime.Serialization; namespace Xtensive.Comparison { @@ -13,7 +12,6 @@ namespace Xtensive.Comparison /// wrapper for system comparers. /// /// Type to compare. - [Serializable] public sealed class SystemComparer: AdvancedComparerBase { /// @@ -42,10 +40,5 @@ internal SystemComparer(IComparerProvider provider, ComparisonRules comparisonRu : base(provider, comparisonRules) { } - - public SystemComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } diff --git a/Orm/Xtensive.Orm/Comparison/SystemComparerProvider.cs b/Orm/Xtensive.Orm/Comparison/SystemComparerProvider.cs index a717aa7384..e578a907a3 100644 --- a/Orm/Xtensive.Orm/Comparison/SystemComparerProvider.cs +++ b/Orm/Xtensive.Orm/Comparison/SystemComparerProvider.cs @@ -6,7 +6,6 @@ using System; using System.Diagnostics; -using System.Runtime.Serialization; namespace Xtensive.Comparison { @@ -41,10 +40,5 @@ protected override TAssociate CreateAssociate(out Type foundFo private SystemComparerProvider() { } - - public SystemComparerProvider(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Comparison/ValueRangeInfo.cs b/Orm/Xtensive.Orm/Comparison/ValueRangeInfo.cs index 45047bd350..27b7bccc47 100644 --- a/Orm/Xtensive.Orm/Comparison/ValueRangeInfo.cs +++ b/Orm/Xtensive.Orm/Comparison/ValueRangeInfo.cs @@ -16,15 +16,14 @@ namespace Xtensive.Comparison /// Represents a pair of smallest and largest values defined for . /// /// the type of . - [Serializable] public sealed class ValueRangeInfo { - private bool hasMaxValue; - private bool hasMinValue; - private bool hasDeltaValue; - private T maxValue; - private T minValue; - private T deltaValue; + private readonly bool hasMaxValue; + private readonly bool hasMinValue; + private readonly bool hasDeltaValue; + private readonly T maxValue; + private readonly T minValue; + private readonly T deltaValue; /// /// Gets a value indicating whether this instance has . @@ -32,10 +31,7 @@ public sealed class ValueRangeInfo /// /// if this instance has ; otherwise, . /// - public bool HasMinValue - { - get { return hasMinValue; } - } + public bool HasMinValue => hasMinValue; /// /// Gets a value indicating whether this instance has . @@ -43,10 +39,7 @@ public bool HasMinValue /// /// if this instance has ; otherwise, . /// - public bool HasMaxValue - { - get { return hasMaxValue; } - } + public bool HasMaxValue => hasMaxValue; /// /// Gets a value indicating whether this instance has . @@ -54,52 +47,25 @@ public bool HasMaxValue /// /// if this instance has ; otherwise, . /// - public bool HasDeltaValue - { - get { return hasDeltaValue; } - } + public bool HasDeltaValue => hasDeltaValue; /// /// Represents the smallest possible value of a T. /// /// The smallest possible value. - public T MinValue - { - get - { - if (!hasMinValue) - throw new InvalidOperationException(Strings.ExValueIsNotAvailable); - return minValue; - } - } + public T MinValue => hasMinValue ? minValue : throw new InvalidOperationException(Strings.ExValueIsNotAvailable); /// /// Represents the largest possible value of a T. /// /// The largest possible value. - public T MaxValue - { - get - { - if (!hasMaxValue) - throw new InvalidOperationException(Strings.ExValueIsNotAvailable); - return maxValue; - } - } + public T MaxValue => hasMaxValue ? maxValue : throw new InvalidOperationException(Strings.ExValueIsNotAvailable); /// /// Represents the smallest possible delta value of a . /// /// The smallest possible delta value. - public T DeltaValue - { - get - { - if (!hasDeltaValue) - throw new InvalidOperationException(Strings.ExValueIsNotAvailable); - return deltaValue; - } - } + public T DeltaValue => hasDeltaValue ? deltaValue : throw new InvalidOperationException(Strings.ExValueIsNotAvailable); /// /// Inverts the instance of . diff --git a/Orm/Xtensive.Orm/Comparison/WrappingComparer{T,TBase1,TBase2}.cs b/Orm/Xtensive.Orm/Comparison/WrappingComparer{T,TBase1,TBase2}.cs index f910b161e7..6b43177d8b 100644 --- a/Orm/Xtensive.Orm/Comparison/WrappingComparer{T,TBase1,TBase2}.cs +++ b/Orm/Xtensive.Orm/Comparison/WrappingComparer{T,TBase1,TBase2}.cs @@ -1,12 +1,10 @@ -// Copyright (C) 2008-2021 Xtensive LLC. +// Copyright (C) 2008-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alex Yakunin // Created: 2008.01.21 using System; -using System.Runtime.Serialization; -using System.Security; using Xtensive.Core; @@ -18,18 +16,17 @@ namespace Xtensive.Comparison /// The type to compare. /// First base (wrapped) type. /// Second base (wrapped) type. - [Serializable] public abstract class WrappingComparer: AdvancedComparerBase { /// /// Comparer delegates for type. /// - protected AdvancedComparerStruct BaseComparer1; + protected readonly AdvancedComparerStruct BaseComparer1; /// /// Comparer delegates for type. /// - protected AdvancedComparerStruct BaseComparer2; + protected readonly AdvancedComparerStruct BaseComparer2; // Constructors @@ -45,20 +42,5 @@ public WrappingComparer(IComparerProvider provider, ComparisonRules comparisonRu BaseComparer1 = provider.GetComparer().ApplyRules(comparisonRules[0]); BaseComparer2 = provider.GetComparer().ApplyRules(comparisonRules[1]); } - - public WrappingComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - BaseComparer1 = (AdvancedComparerStruct) info.GetValue(nameof(BaseComparer1), typeof(AdvancedComparerStruct)); - BaseComparer2 = (AdvancedComparerStruct) info.GetValue(nameof(BaseComparer2), typeof(AdvancedComparerStruct)); - } - - [SecurityCritical] - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddValue(nameof(BaseComparer1), BaseComparer1, BaseComparer1.GetType()); - info.AddValue(nameof(BaseComparer2), BaseComparer2, BaseComparer2.GetType()); - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Comparison/WrappingComparer{T,TBase}.cs b/Orm/Xtensive.Orm/Comparison/WrappingComparer{T,TBase}.cs index b34af02563..c80d300e6a 100644 --- a/Orm/Xtensive.Orm/Comparison/WrappingComparer{T,TBase}.cs +++ b/Orm/Xtensive.Orm/Comparison/WrappingComparer{T,TBase}.cs @@ -1,16 +1,13 @@ -// Copyright (C) 2008-2021 Xtensive LLC. +// Copyright (C) 2008-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alex Yakunin // Created: 2008.01.21 using System; -using System.Runtime.Serialization; -using System.Security; using Xtensive.Core; - namespace Xtensive.Comparison { /// @@ -18,13 +15,12 @@ namespace Xtensive.Comparison /// /// The type to compare. /// Base (wrapped) type. - [Serializable] public abstract class WrappingComparer : AdvancedComparerBase { /// /// Comparer delegates for type. /// - protected AdvancedComparerStruct BaseComparer; + protected readonly AdvancedComparerStruct BaseComparer; // Constructors @@ -40,18 +36,5 @@ public WrappingComparer(IComparerProvider provider, ComparisonRules comparisonRu ArgumentNullException.ThrowIfNull(provider); BaseComparer = provider.GetComparer().ApplyRules(comparisonRules); } - - public WrappingComparer(SerializationInfo info, StreamingContext context) - : base(info, context) - { - BaseComparer = (AdvancedComparerStruct) info.GetValue(nameof(BaseComparer), typeof(AdvancedComparerStruct)); - } - - [SecurityCritical] - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddValue(nameof(BaseComparer), BaseComparer, BaseComparer.GetType()); - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Conversion/AdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/AdvancedConverter.cs index 2d5bc7e347..5a79d75147 100644 --- a/Orm/Xtensive.Orm/Conversion/AdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/AdvancedConverter.cs @@ -6,8 +6,6 @@ using System; using System.Diagnostics; -using System.Runtime.Serialization; -using System.Threading; using Xtensive.Core; @@ -19,21 +17,19 @@ namespace Xtensive.Conversion /// /// Type of the first generic argument. /// Type of the second generic argument. - [Serializable] public sealed class AdvancedConverter : MethodCacheBase> { private static readonly Lazy> CachedConverter = - new Lazy>(() => AdvancedConverterProvider.Default.GetConverter()); + new (() => AdvancedConverterProvider.Default.GetConverter()); /// /// Gets default advanced converter for types and . /// (uses ). /// - public static AdvancedConverter Default { + public static AdvancedConverter Default + { [DebuggerStepThrough] - get { - return CachedConverter.Value; - } + get => CachedConverter.Value; } /// @@ -65,18 +61,5 @@ public AdvancedConverter(IAdvancedConverter implementation) Convert = Implementation.Convert; IsRough = Implementation.IsRough; } - - /// - /// Deserializes the instance of this class. - /// - /// Serialization info. - /// Streaming context. - public AdvancedConverter(SerializationInfo info, StreamingContext context) - : base(info, context) - { - Provider = Implementation.Provider; - Convert = Implementation.Convert; - IsRough = Implementation.IsRough; - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Conversion/AdvancedConverterBase.cs b/Orm/Xtensive.Orm/Conversion/AdvancedConverterBase.cs index e9a9f65bcb..86b4e473b5 100644 --- a/Orm/Xtensive.Orm/Conversion/AdvancedConverterBase.cs +++ b/Orm/Xtensive.Orm/Conversion/AdvancedConverterBase.cs @@ -5,9 +5,6 @@ // Created: 2008.02.15 using System; -using System.Diagnostics; -using System.Runtime.Serialization; -using Xtensive.Core; namespace Xtensive.Conversion @@ -15,19 +12,11 @@ namespace Xtensive.Conversion /// /// Base class for any advanced converter. /// - [Serializable] public abstract class AdvancedConverterBase : - IAdvancedConverterBase, - IDeserializationCallback + IAdvancedConverterBase { - private IAdvancedConverterProvider provider; - /// - public IAdvancedConverterProvider Provider - { - [DebuggerStepThrough] - get { return provider; } - } + public IAdvancedConverterProvider Provider { get; } // Constructors @@ -38,17 +27,7 @@ public IAdvancedConverterProvider Provider /// The provider this advanced converter is bound to. public AdvancedConverterBase(IAdvancedConverterProvider provider) { - this.provider = provider ?? throw new ArgumentNullException(nameof(provider)); - } - - /// - /// Performs post-deserialization actions. - /// - /// - public virtual void OnDeserialization(object sender) - { - if (provider==null || provider.GetType()==typeof (AdvancedConverterProvider)) - provider = AdvancedConverterProvider.Default; + Provider = provider ?? throw new ArgumentNullException(nameof(provider)); } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Conversion/AdvancedConverterProvider.cs b/Orm/Xtensive.Orm/Conversion/AdvancedConverterProvider.cs index b676265f80..f5497e2cb7 100644 --- a/Orm/Xtensive.Orm/Conversion/AdvancedConverterProvider.cs +++ b/Orm/Xtensive.Orm/Conversion/AdvancedConverterProvider.cs @@ -17,22 +17,21 @@ namespace Xtensive.Conversion /// Default provider. /// Provides default converter for specified types. /// - [Serializable] public class AdvancedConverterProvider : AssociateProvider, IAdvancedConverterProvider { /// /// Zero time point (for conversion of to e.g. ). /// - public static readonly DateTime ZeroTime = new DateTime(2000, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); - private static readonly AdvancedConverterProvider @default = new AdvancedConverterProvider(); + public static readonly DateTime ZeroTime = new(2000, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); + private static readonly AdvancedConverterProvider @default = new(); - private static readonly AsyncLocal, bool>> inProgressAsync = new AsyncLocal, bool>>(); + private static readonly AsyncLocal, bool>> inProgressAsync = new(); private static Dictionary, bool> InProgress { get { var returnedValue = inProgressAsync.Value; - if (returnedValue==null) + if (returnedValue is null) inProgressAsync.Value = returnedValue = new Dictionary, bool>(); return returnedValue; } @@ -44,20 +43,18 @@ private static Dictionary, bool> InProgress public static IAdvancedConverterProvider Default { [DebuggerStepThrough] - get { return @default; } + get => @default; } /// public virtual AdvancedConverter GetConverter() - { - return GetAssociate, AdvancedConverter>(); - } + => GetAssociate, AdvancedConverter>(); /// public virtual DateTime BaseTime { [DebuggerStepThrough] - get { return ZeroTime; } + get => ZeroTime; } /// @@ -82,24 +79,24 @@ protected override TAssociate CreateCustomAssociate() } try { TAssociate associate = base.CreateCustomAssociate(); - if (associate!=null) + if (associate is not null) return associate; IAdvancedConverterFactory f1 = base.GetAssociate, IAdvancedConverterFactory>(); - if (f1!=null) { + if (f1 is not null) { associate = f1.CreateForwardConverter() as TAssociate; - if (associate!=null) + if (associate is not null) return associate; } IAdvancedConverterFactory f2 = base.GetAssociate, IAdvancedConverterFactory>(); - if (f2!=null) { + if (f2 is not null) { associate = f2.CreateBackwardConverter() as TAssociate; - if (associate!=null) + if (associate is not null) return associate; } return null; } finally { - InProgress.Remove(keyTypePair); + _ = InProgress.Remove(keyTypePair); } } @@ -120,7 +117,7 @@ protected override TResult ConvertAssociate(T /// protected AdvancedConverterProvider() { - TypeSuffixes = new string[] {"AdvancedConverter", "RoughAdvancedConverter", "AdvancedConverterFactory"}; + TypeSuffixes = ["AdvancedConverter", "RoughAdvancedConverter", "AdvancedConverterFactory"]; Type t = typeof (AdvancedConverterProvider); AddHighPriorityLocation(t.Assembly, t.Namespace); } diff --git a/Orm/Xtensive.Orm/Conversion/AdvancedConverterStruct.cs b/Orm/Xtensive.Orm/Conversion/AdvancedConverterStruct.cs index a03d971d46..ea7ac89a16 100644 --- a/Orm/Xtensive.Orm/Conversion/AdvancedConverterStruct.cs +++ b/Orm/Xtensive.Orm/Conversion/AdvancedConverterStruct.cs @@ -5,25 +5,20 @@ // Created: 2008.02.15 using System; -using System.Runtime.Serialization; -using System.Security; -using System.Security.Permissions; - -using C=Xtensive.Conversion; +using C = Xtensive.Conversion; namespace Xtensive.Conversion { /// /// A struct providing faster access for key delegates. /// - [Serializable] - public struct AdvancedConverterStruct : ISerializable + public struct AdvancedConverterStruct { /// /// Gets for /// hasher. /// - public static readonly AdvancedConverterStruct Default = new AdvancedConverterStruct(AdvancedConverter.Default); + public static readonly AdvancedConverterStruct Default = new(AdvancedConverter.Default); /// @@ -61,27 +56,14 @@ public static implicit operator AdvancedConverterStruct(AdvancedConv private AdvancedConverterStruct(AdvancedConverter advancedConverter) { AdvancedConverter = advancedConverter; - Convert = AdvancedConverter==null ? null : AdvancedConverter.Convert; - IsRough = AdvancedConverter==null ? true : AdvancedConverter.IsRough; - } - - /// - /// Deserializes the instance of this class. - /// - /// Serialization info. - /// Streaming context. - private AdvancedConverterStruct(SerializationInfo info, StreamingContext context) - { - AdvancedConverter = (AdvancedConverter) info.GetValue("AdvancedConverter", typeof (AdvancedConverter)); - Convert = AdvancedConverter==null ? null : AdvancedConverter.Convert; - IsRough = AdvancedConverter==null ? true : AdvancedConverter.IsRough; - } - - /// - [SecurityCritical] - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue("AdvancedConverter", AdvancedConverter); + if (AdvancedConverter is null) { + Convert = null; + IsRough = true; + } + else { + Convert = AdvancedConverter.Convert; + IsRough = AdvancedConverter.IsRough; + } } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Conversion/Biconverter.cs b/Orm/Xtensive.Orm/Conversion/Biconverter.cs index 174512e7d1..12d174f32b 100644 --- a/Orm/Xtensive.Orm/Conversion/Biconverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Biconverter.cs @@ -14,7 +14,6 @@ namespace Xtensive.Conversion /// /// Type to convert from. /// Type to convert to. - [Serializable] public readonly struct Biconverter : IEquatable> { @@ -48,9 +47,7 @@ public static Biconverter AsIs { /// public bool Equals(Biconverter obj) - { - return Equals(obj.ConvertForward, ConvertForward) && Equals(obj.ConvertBackward, ConvertBackward); - } + => Equals(obj.ConvertForward, ConvertForward) && Equals(obj.ConvertBackward, ConvertBackward); /// public override bool Equals(object obj) => diff --git a/Orm/Xtensive.Orm/Conversion/Internals/BooleanAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/BooleanAdvancedConverter.cs index 61bd631af9..d648be50e5 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/BooleanAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/BooleanAdvancedConverter.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2003-2010 Xtensive LLC. +// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Roman Churakov @@ -8,7 +8,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class BooleanAdvancedConverter : StrictAdvancedConverterBase, IAdvancedConverter, @@ -24,65 +23,18 @@ internal class BooleanAdvancedConverter : IAdvancedConverter, IAdvancedConverter { - byte IAdvancedConverter.Convert(bool value) - { - return System.Convert.ToByte(value); - } - - sbyte IAdvancedConverter.Convert(bool value) - { - return System.Convert.ToSByte(value); - } - - short IAdvancedConverter.Convert(bool value) - { - return System.Convert.ToInt16(value); - } - - ushort IAdvancedConverter.Convert(bool value) - { - return System.Convert.ToUInt16(value); - } - - int IAdvancedConverter.Convert(bool value) - { - return System.Convert.ToInt32(value); - } - - uint IAdvancedConverter.Convert(bool value) - { - return System.Convert.ToUInt32(value); - } - - long IAdvancedConverter.Convert(bool value) - { - return System.Convert.ToInt64(value); - } - - ulong IAdvancedConverter.Convert(bool value) - { - return System.Convert.ToUInt64(value); - } - - float IAdvancedConverter.Convert(bool value) - { - return System.Convert.ToSingle(value); - } - - double IAdvancedConverter.Convert(bool value) - { - return System.Convert.ToDouble(value); - } - - decimal IAdvancedConverter.Convert(bool value) - { - return System.Convert.ToDecimal(value); - } - - string IAdvancedConverter.Convert(bool value) - { - return value.ToString(); // Culture is not used for Boolean string - } + byte IAdvancedConverter.Convert(bool value) => System.Convert.ToByte(value); + sbyte IAdvancedConverter.Convert(bool value) => System.Convert.ToSByte(value); + short IAdvancedConverter.Convert(bool value) => System.Convert.ToInt16(value); + ushort IAdvancedConverter.Convert(bool value) => System.Convert.ToUInt16(value); + int IAdvancedConverter.Convert(bool value) => System.Convert.ToInt32(value); + uint IAdvancedConverter.Convert(bool value) => System.Convert.ToUInt32(value); + long IAdvancedConverter.Convert(bool value) => System.Convert.ToInt64(value); + ulong IAdvancedConverter.Convert(bool value) => System.Convert.ToUInt64(value); + float IAdvancedConverter.Convert(bool value) => System.Convert.ToSingle(value); + double IAdvancedConverter.Convert(bool value) => System.Convert.ToDouble(value); + decimal IAdvancedConverter.Convert(bool value) => System.Convert.ToDecimal(value); + string IAdvancedConverter.Convert(bool value) => value.ToString(); // Culture is not used for Boolean string // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/ByteAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/ByteAdvancedConverter.cs index b0ec7e77f6..9fc483bd5f 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/ByteAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/ByteAdvancedConverter.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2003-2010 Xtensive LLC. +// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Roman Churakov @@ -9,7 +9,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class ByteAdvancedConverter : StrictAdvancedConverterBase, IAdvancedConverter, @@ -36,50 +35,23 @@ sbyte IAdvancedConverter.Convert(byte value) } } - short IAdvancedConverter.Convert(byte value) - { - return value; - } + short IAdvancedConverter.Convert(byte value) => value; - ushort IAdvancedConverter.Convert(byte value) - { - return value; - } + ushort IAdvancedConverter.Convert(byte value) => value; - int IAdvancedConverter.Convert(byte value) - { - return value; - } + int IAdvancedConverter.Convert(byte value) => value; - uint IAdvancedConverter.Convert(byte value) - { - return value; - } + uint IAdvancedConverter.Convert(byte value) => value; - long IAdvancedConverter.Convert(byte value) - { - return value; - } + long IAdvancedConverter.Convert(byte value) => value; - ulong IAdvancedConverter.Convert(byte value) - { - return value; - } + ulong IAdvancedConverter.Convert(byte value) => value; - float IAdvancedConverter.Convert(byte value) - { - return System.Convert.ToSingle(value); - } + float IAdvancedConverter.Convert(byte value) => System.Convert.ToSingle(value); - double IAdvancedConverter.Convert(byte value) - { - return System.Convert.ToDouble(value); - } + double IAdvancedConverter.Convert(byte value) => System.Convert.ToDouble(value); - decimal IAdvancedConverter.Convert(byte value) - { - return System.Convert.ToDecimal(value); - } + decimal IAdvancedConverter.Convert(byte value) => System.Convert.ToDecimal(value); DateTime IAdvancedConverter.Convert(byte value) { @@ -95,15 +67,9 @@ TimeSpan IAdvancedConverter.Convert(byte value) } } - string IAdvancedConverter.Convert(byte value) - { - return value.ToString(CultureInfo.InvariantCulture); - } + string IAdvancedConverter.Convert(byte value) => value.ToString(CultureInfo.InvariantCulture); - char IAdvancedConverter.Convert(byte value) - { - return System.Convert.ToChar(value); - } + char IAdvancedConverter.Convert(byte value) => System.Convert.ToChar(value); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/ByteArrayAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/ByteArrayAdvancedConverter.cs new file mode 100644 index 0000000000..45b8cbde6d --- /dev/null +++ b/Orm/Xtensive.Orm/Conversion/Internals/ByteArrayAdvancedConverter.cs @@ -0,0 +1,42 @@ +// Copyright (C) 2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System; + +namespace Xtensive.Conversion +{ + internal class ByteArrayAdvancedConverter : + StrictAdvancedConverterBase, + IAdvancedConverter, + IAdvancedConverter + { + string IAdvancedConverter.Convert(byte[] value) + => (value is null) + ? null + : (value.Length == 0) + ? string.Empty + : $"0x{System.Convert.ToHexString(value)}"; + + byte[] IAdvancedConverter.Convert(string value) + { + if (value == null) + return null; + if (string.IsNullOrEmpty(value)) + return Array.Empty(); + + if (!value.StartsWith("0x")) + throw new ArgumentException("Bad format", value); + + var usefulPart = value.AsSpan().Slice(2); + return System.Convert.FromHexString(usefulPart); + } + + // Constructors + + public ByteArrayAdvancedConverter(IAdvancedConverterProvider provider) + : base(provider) + { + } + } +} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Conversion/Internals/ByteRoughAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/ByteRoughAdvancedConverter.cs index 1156171516..cc266a42e5 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/ByteRoughAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/ByteRoughAdvancedConverter.cs @@ -8,15 +8,11 @@ namespace Xtensive.Conversion { - [Serializable] internal class ByteRoughAdvancedConverter : RoughAdvancedConverterBase, IAdvancedConverter { - bool IAdvancedConverter.Convert(byte value) - { - return System.Convert.ToBoolean(value); - } + bool IAdvancedConverter.Convert(byte value) => Convert.ToBoolean(value); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/CharAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/CharAdvancedConverter.cs index 0e1ee35ccd..05441dad06 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/CharAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/CharAdvancedConverter.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.23 @@ -8,7 +8,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class CharAdvancedConverter : StrictAdvancedConverterBase, IAdvancedConverter, @@ -21,62 +20,21 @@ internal class CharAdvancedConverter : IAdvancedConverter, IAdvancedConverter, IAdvancedConverter, - IAdvancedConverter + IAdvancedConverter, + IAdvancedConverter { - byte IAdvancedConverter.Convert(char value) - { - return System.Convert.ToByte(value); - } - - sbyte IAdvancedConverter.Convert(char value) - { - return System.Convert.ToSByte(value); - } - - short IAdvancedConverter.Convert(char value) - { - return System.Convert.ToInt16(value); - } - - ushort IAdvancedConverter.Convert(char value) - { - return System.Convert.ToUInt16(value); - } - - int IAdvancedConverter.Convert(char value) - { - return System.Convert.ToInt32(value); - } - - uint IAdvancedConverter.Convert(char value) - { - return System.Convert.ToUInt32(value); - } - - long IAdvancedConverter.Convert(char value) - { - return System.Convert.ToInt64(value); - } - - ulong IAdvancedConverter.Convert(char value) - { - return System.Convert.ToUInt64(value); - } - - float IAdvancedConverter.Convert(char value) - { - return System.Convert.ToSingle(System.Convert.ToUInt16(value)); - } - - double IAdvancedConverter.Convert(char value) - { - return System.Convert.ToDouble(System.Convert.ToUInt16(value)); - } - - decimal IAdvancedConverter.Convert(char value) - { - return System.Convert.ToDecimal(System.Convert.ToUInt16(value)); - } + byte IAdvancedConverter.Convert(char value) => System.Convert.ToByte(value); + sbyte IAdvancedConverter.Convert(char value) => System.Convert.ToSByte(value); + short IAdvancedConverter.Convert(char value) => System.Convert.ToInt16(value); + ushort IAdvancedConverter.Convert(char value) => System.Convert.ToUInt16(value); + int IAdvancedConverter.Convert(char value) => System.Convert.ToInt32(value); + uint IAdvancedConverter.Convert(char value) => System.Convert.ToUInt32(value); + long IAdvancedConverter.Convert(char value) => System.Convert.ToInt64(value); + ulong IAdvancedConverter.Convert(char value) => System.Convert.ToUInt64(value); + float IAdvancedConverter.Convert(char value) => System.Convert.ToSingle(System.Convert.ToUInt16(value)); + double IAdvancedConverter.Convert(char value) => System.Convert.ToDouble(System.Convert.ToUInt16(value)); + decimal IAdvancedConverter.Convert(char value) => System.Convert.ToDecimal(System.Convert.ToUInt16(value)); + string IAdvancedConverter.Convert(char value) => value.ToString(); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/ConvertingEnumerator.cs b/Orm/Xtensive.Orm/Conversion/Internals/ConvertingEnumerator.cs index 19e88478c1..0b1fa10717 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/ConvertingEnumerator.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/ConvertingEnumerator.cs @@ -6,15 +6,13 @@ using System; using System.Collections.Generic; -using Xtensive.Core; namespace Xtensive.Conversion { - [Serializable] internal class ConvertingEnumerator : IEnumerator { - private IEnumerator innerEnumerator; + private readonly IEnumerator innerEnumerator; private readonly Converter converter; private T2 current; private bool currentIsValid = false; @@ -38,7 +36,7 @@ public T2 Current } return current; } - } + } public bool MoveNext() { @@ -76,7 +74,6 @@ public void Dispose() { currentIsValid = false; innerEnumerator.Dispose(); - innerEnumerator = null; } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Conversion/Internals/DateOnlyAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/DateOnlyAdvancedConverter.cs new file mode 100644 index 0000000000..e2da1238e6 --- /dev/null +++ b/Orm/Xtensive.Orm/Conversion/Internals/DateOnlyAdvancedConverter.cs @@ -0,0 +1,64 @@ +// Copyright (C) 2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System; +using System.Globalization; + +namespace Xtensive.Conversion +{ + internal class DateOnlyAdvancedConverter : + StrictAdvancedConverterBase, + IAdvancedConverter, + IAdvancedConverter, + IAdvancedConverter, + IAdvancedConverter, + IAdvancedConverter, + IAdvancedConverter, + IAdvancedConverter, + IAdvancedConverter + { + int IAdvancedConverter.Convert(DateOnly value) + { + checked { + return value.DayNumber; + } + } + + uint IAdvancedConverter.Convert(DateOnly value) + { + checked { + return (uint) value.DayNumber; + } + } + + long IAdvancedConverter.Convert(DateOnly value) + { + checked { + return value.DayNumber; + } + } + + ulong IAdvancedConverter.Convert(DateOnly value) + { + checked { + return (ulong) value.DayNumber; + } + } + + decimal IAdvancedConverter.Convert(DateOnly value) => System.Convert.ToDecimal(value.DayNumber); + + DateTime IAdvancedConverter.Convert(DateOnly value) => value.ToDateTime(TimeOnly.MinValue); + + TimeSpan IAdvancedConverter.Convert(DateOnly value) + => TimeSpan.FromDays(value.DayNumber); + + string IAdvancedConverter.Convert(DateOnly value) + => value.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture); + + public DateOnlyAdvancedConverter(IAdvancedConverterProvider provider) + : base(provider) + { + } + } +} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Conversion/Internals/DateOnlyRoughAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/DateOnlyRoughAdvancedConverter.cs new file mode 100644 index 0000000000..492adbda9a --- /dev/null +++ b/Orm/Xtensive.Orm/Conversion/Internals/DateOnlyRoughAdvancedConverter.cs @@ -0,0 +1,25 @@ +// Copyright (C) 2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System; + +namespace Xtensive.Conversion +{ + internal class DateOnlyRoughAdvancedConverter : + RoughAdvancedConverterBase, + IAdvancedConverter, + IAdvancedConverter + { + float IAdvancedConverter.Convert(DateOnly value) => Convert.ToSingle(value.DayNumber); + double IAdvancedConverter.Convert(DateOnly value) => Convert.ToDouble(value.DayNumber); + + + // Constructors + + public DateOnlyRoughAdvancedConverter(IAdvancedConverterProvider provider) + : base(provider) + { + } + } +} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Conversion/Internals/DateTimeAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/DateTimeAdvancedConverter.cs index ee3cfa080d..f513ee20bf 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/DateTimeAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/DateTimeAdvancedConverter.cs @@ -9,7 +9,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class DateTimeAdvancedConverter : StrictAdvancedConverterBase, IAdvancedConverter, @@ -83,25 +82,14 @@ ulong IAdvancedConverter.Convert(DateTime value) } } - decimal IAdvancedConverter.Convert(DateTime value) - { - return System.Convert.ToDecimal(value.Ticks - baseDateTimeTicks); - } + decimal IAdvancedConverter.Convert(DateTime value) => System.Convert.ToDecimal(value.Ticks - baseDateTimeTicks); - DateTime IAdvancedConverter.Convert(DateTime value) - { - return value; - } + DateTime IAdvancedConverter.Convert(DateTime value) => value; - TimeSpan IAdvancedConverter.Convert(DateTime value) - { - return new TimeSpan(value.Ticks - baseDateTimeTicks); - } + TimeSpan IAdvancedConverter.Convert(DateTime value) => new TimeSpan(value.Ticks - baseDateTimeTicks); string IAdvancedConverter.Convert(DateTime value) - { - return value.ToString("yyyy/MM/dd hh:mm:ss.fffffff tt K ", CultureInfo.InvariantCulture); - } + => value.ToString("yyyy/MM/dd hh:mm:ss.fffffff tt K ", CultureInfo.InvariantCulture); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/DateTimeOffsetAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/DateTimeOffsetAdvancedConverter.cs new file mode 100644 index 0000000000..2bdcf45e57 --- /dev/null +++ b/Orm/Xtensive.Orm/Conversion/Internals/DateTimeOffsetAdvancedConverter.cs @@ -0,0 +1,22 @@ +// Copyright (C) 2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System; +using System.Globalization; + +namespace Xtensive.Conversion +{ + internal class DateTimeOffsetAdvancedConverter : + StrictAdvancedConverterBase, + IAdvancedConverter + { + string IAdvancedConverter.Convert(DateTimeOffset value) + => value.ToString("yyyy/MM/dd hh:mm:ss.fffffff tt zzz", CultureInfo.InvariantCulture); + + public DateTimeOffsetAdvancedConverter(IAdvancedConverterProvider provider) + : base(provider) + { + } + } +} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Conversion/Internals/DateTimeOffsetRoughAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/DateTimeOffsetRoughAdvancedConverter.cs new file mode 100644 index 0000000000..62d9126b0b --- /dev/null +++ b/Orm/Xtensive.Orm/Conversion/Internals/DateTimeOffsetRoughAdvancedConverter.cs @@ -0,0 +1,30 @@ +// Copyright (C) 2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System; + +namespace Xtensive.Conversion +{ + internal class DateTimeOffsetRoughAdvancedConverter : + RoughAdvancedConverterBase, + + IAdvancedConverter, + IAdvancedConverter, + IAdvancedConverter, + IAdvancedConverter, + IAdvancedConverter + { + long IAdvancedConverter.Convert(DateTimeOffset value) => value.UtcTicks; + ulong IAdvancedConverter.Convert(DateTimeOffset value) => (ulong)value.UtcTicks; + decimal IAdvancedConverter.Convert(DateTimeOffset value) => value.UtcTicks; + DateTime IAdvancedConverter.Convert(DateTimeOffset value) => value.UtcDateTime; + TimeSpan IAdvancedConverter.Convert(DateTimeOffset value) => TimeSpan.FromTicks(value.UtcTicks); + + + public DateTimeOffsetRoughAdvancedConverter(IAdvancedConverterProvider provider) + : base(provider) + { + } + } +} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Conversion/Internals/DateTimeRoughAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/DateTimeRoughAdvancedConverter.cs index 278fcb2b2d..c66af50604 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/DateTimeRoughAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/DateTimeRoughAdvancedConverter.cs @@ -8,22 +8,26 @@ namespace Xtensive.Conversion { - [Serializable] internal class DateTimeRoughAdvancedConverter : RoughAdvancedConverterBase, IAdvancedConverter, - IAdvancedConverter + IAdvancedConverter, + IAdvancedConverter + { private readonly long baseDateTimeTicks; - float IAdvancedConverter.Convert(DateTime value) - { - return Convert.ToSingle(value.Ticks - baseDateTimeTicks); - } - - double IAdvancedConverter.Convert(DateTime value) + float IAdvancedConverter.Convert(DateTime value) => Convert.ToSingle(value.Ticks - baseDateTimeTicks); + double IAdvancedConverter.Convert(DateTime value) => Convert.ToDouble(value.Ticks - baseDateTimeTicks); + DateTimeOffset IAdvancedConverter.Convert(DateTime value) { - return Convert.ToDouble(value.Ticks - baseDateTimeTicks); + if (value.Kind == DateTimeKind.Utc) { + return new DateTimeOffset(value, TimeSpan.Zero); + } + if (value.Kind == DateTimeKind.Local) { + return new DateTimeOffset(value, DateTimeOffset.Now.Offset); + } + return new DateTimeOffset(value.Ticks, TimeSpan.Zero); } diff --git a/Orm/Xtensive.Orm/Conversion/Internals/DecimalAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/DecimalAdvancedConverter.cs index f1884ea861..4a85aae59d 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/DecimalAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/DecimalAdvancedConverter.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2003-2010 Xtensive LLC. +// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Roman Churakov @@ -9,21 +9,10 @@ namespace Xtensive.Conversion { - [Serializable] - internal class DecimalAdvancedConverter : - StrictAdvancedConverterBase, + internal class DecimalAdvancedConverter(IAdvancedConverterProvider provider) : + StrictAdvancedConverterBase(provider), IAdvancedConverter { - string IAdvancedConverter.Convert(decimal value) - { - return System.Convert.ToString(value, CultureInfo.InvariantCulture); - } - - - // Constructors - - public DecimalAdvancedConverter(IAdvancedConverterProvider provider) : base(provider) - { - } + string IAdvancedConverter.Convert(decimal value) => System.Convert.ToString(value, CultureInfo.InvariantCulture); } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Conversion/Internals/DecimalRoughAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/DecimalRoughAdvancedConverter.cs index c3bfa09969..5fc8f4f142 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/DecimalRoughAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/DecimalRoughAdvancedConverter.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Gamzov // Created: 2008.02.08 @@ -8,7 +8,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class DecimalRoughAdvancedConverter : RoughAdvancedConverterBase, IAdvancedConverter, @@ -22,96 +21,68 @@ internal class DecimalRoughAdvancedConverter : IAdvancedConverter, IAdvancedConverter, IAdvancedConverter, + IAdvancedConverter, IAdvancedConverter, + IAdvancedConverter, + IAdvancedConverter, IAdvancedConverter, IAdvancedConverter { private readonly long baseDateTimeTicks; /// - bool IAdvancedConverter.Convert(decimal value) - { - return Convert.ToBoolean(value); - } + bool IAdvancedConverter.Convert(decimal value) => Convert.ToBoolean(value); /// - byte IAdvancedConverter.Convert(decimal value) - { - return Convert.ToByte(value); - } + byte IAdvancedConverter.Convert(decimal value) => Convert.ToByte(value); /// - sbyte IAdvancedConverter.Convert(decimal value) - { - return Convert.ToSByte(value); - } + sbyte IAdvancedConverter.Convert(decimal value) => Convert.ToSByte(value); /// - short IAdvancedConverter.Convert(decimal value) - { - return Convert.ToInt16(value); - } + short IAdvancedConverter.Convert(decimal value) => Convert.ToInt16(value); /// - ushort IAdvancedConverter.Convert(decimal value) - { - return Convert.ToUInt16(value); - } + ushort IAdvancedConverter.Convert(decimal value) => Convert.ToUInt16(value); /// - int IAdvancedConverter.Convert(decimal value) - { - return Convert.ToInt32(value); - } + int IAdvancedConverter.Convert(decimal value) => Convert.ToInt32(value); /// - uint IAdvancedConverter.Convert(decimal value) - { - return Convert.ToUInt32(value); - } + uint IAdvancedConverter.Convert(decimal value) => Convert.ToUInt32(value); /// - long IAdvancedConverter.Convert(decimal value) - { - return Convert.ToInt64(value); - } + long IAdvancedConverter.Convert(decimal value) => Convert.ToInt64(value); /// - ulong IAdvancedConverter.Convert(decimal value) - { - return Convert.ToUInt64(value); - } + ulong IAdvancedConverter.Convert(decimal value) => Convert.ToUInt64(value); /// - float IAdvancedConverter.Convert(decimal value) - { - return Convert.ToSingle(value); - } + float IAdvancedConverter.Convert(decimal value) => Convert.ToSingle(value); /// - double IAdvancedConverter.Convert(decimal value) - { - return Convert.ToDouble(value); - } + double IAdvancedConverter.Convert(decimal value) => Convert.ToDouble(value); + /// + DateTimeOffset IAdvancedConverter.Convert(decimal value) + => new DateTimeOffset(Convert.ToInt64(value), TimeSpan.Zero); /// DateTime IAdvancedConverter.Convert(decimal value) - { - return new DateTime(Convert.ToInt64(value) + baseDateTimeTicks, DateTimeKind.Utc); - } + => new DateTime(Convert.ToInt64(value) + baseDateTimeTicks, DateTimeKind.Utc); /// - TimeSpan IAdvancedConverter.Convert(decimal value) - { - return new TimeSpan(Convert.ToInt64(value)); - } + DateOnly IAdvancedConverter.Convert(decimal value) + => DateOnly.FromDayNumber(Convert.ToInt32(value)); + + /// + TimeOnly IAdvancedConverter.Convert(decimal value) + => new TimeOnly(Convert.ToInt64(value)); + /// + TimeSpan IAdvancedConverter.Convert(decimal value) => new TimeSpan(Convert.ToInt64(value)); /// - char IAdvancedConverter.Convert(decimal value) - { - return Convert.ToChar(Convert.ToInt64(value)); - } + char IAdvancedConverter.Convert(decimal value) => Convert.ToChar(Convert.ToInt64(value)); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/DoubleAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/DoubleAdvancedConverter.cs index 0e96e47d34..81bd0a6f14 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/DoubleAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/DoubleAdvancedConverter.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2003-2010 Xtensive LLC. +// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Roman Churakov @@ -9,7 +9,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class DoubleAdvancedConverter : StrictAdvancedConverterBase, IAdvancedConverter diff --git a/Orm/Xtensive.Orm/Conversion/Internals/DoubleRoughAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/DoubleRoughAdvancedConverter.cs index c1650425c5..dc0ce31105 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/DoubleRoughAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/DoubleRoughAdvancedConverter.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Gamzov // Created: 2008.02.08 @@ -8,7 +8,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class DoubleRoughAdvancedConverter : RoughAdvancedConverterBase, IAdvancedConverter, @@ -23,45 +22,27 @@ internal class DoubleRoughAdvancedConverter : IAdvancedConverter, IAdvancedConverter, IAdvancedConverter, + IAdvancedConverter, + IAdvancedConverter, IAdvancedConverter, IAdvancedConverter { private readonly long baseDateTimeTicks; + private readonly long ticksPerDay; - bool IAdvancedConverter.Convert(double value) - { - return Convert.ToBoolean(value); - } + bool IAdvancedConverter.Convert(double value) => Convert.ToBoolean(value); - byte IAdvancedConverter.Convert(double value) - { - return Convert.ToByte(value); - } + byte IAdvancedConverter.Convert(double value) => Convert.ToByte(value); - sbyte IAdvancedConverter.Convert(double value) - { - return Convert.ToSByte(value); - } + sbyte IAdvancedConverter.Convert(double value) => Convert.ToSByte(value); - short IAdvancedConverter.Convert(double value) - { - return Convert.ToInt16(value); - } + short IAdvancedConverter.Convert(double value) => Convert.ToInt16(value); - ushort IAdvancedConverter.Convert(double value) - { - return Convert.ToUInt16(value); - } + ushort IAdvancedConverter.Convert(double value) => Convert.ToUInt16(value); - int IAdvancedConverter.Convert(double value) - { - return Convert.ToInt32(value); - } + int IAdvancedConverter.Convert(double value) => Convert.ToInt32(value); - uint IAdvancedConverter.Convert(double value) - { - return Convert.ToUInt32(value); - } + uint IAdvancedConverter.Convert(double value) => Convert.ToUInt32(value); long IAdvancedConverter.Convert(double value) { @@ -84,10 +65,7 @@ float IAdvancedConverter.Convert(double value) return Convert.ToSingle(value); } - decimal IAdvancedConverter.Convert(double value) - { - return Convert.ToDecimal(value); - } + decimal IAdvancedConverter.Convert(double value) => Convert.ToDecimal(value); DateTime IAdvancedConverter.Convert(double value) { @@ -96,6 +74,20 @@ DateTime IAdvancedConverter.Convert(double value) } } + DateOnly IAdvancedConverter.Convert(double value) + { + checked { + return DateOnly.FromDayNumber(Convert.ToInt32(Math.Round(value))); + } + } + + TimeOnly IAdvancedConverter.Convert(double value) + { + checked { + return new TimeOnly((long) Math.Round(value)); + } + } + TimeSpan IAdvancedConverter.Convert(double value) { checked { @@ -117,6 +109,7 @@ public DoubleRoughAdvancedConverter(IAdvancedConverterProvider provider) : base(provider) { baseDateTimeTicks = provider.BaseTime.Ticks; + ticksPerDay = TimeSpan.FromDays(1).Ticks; } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Conversion/Internals/EnumAdvancedConverterFactory.cs b/Orm/Xtensive.Orm/Conversion/Internals/EnumAdvancedConverterFactory.cs index 631ac2a911..c457cc0dc1 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/EnumAdvancedConverterFactory.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/EnumAdvancedConverterFactory.cs @@ -9,37 +9,36 @@ namespace Xtensive.Conversion { - [Serializable] internal class EnumAdvancedConverterFactory : IAdvancedConverterFactory { private readonly IAdvancedConverterProvider provider; public IAdvancedConverter CreateForwardConverter() { - Type fromType = typeof (TFrom); - Type toType = typeof (TTo); + var fromType = typeof (TFrom); + var toType = typeof (TTo); if (fromType.IsEnum) { - Type fromUnderlyingType = Enum.GetUnderlyingType(fromType); + var fromUnderlyingType = Enum.GetUnderlyingType(fromType); Type[] genericArguments; Type genericType; if (toType.IsEnum) { Type toUnderlyingType = Enum.GetUnderlyingType(toType); if (fromUnderlyingType==toUnderlyingType) { - genericArguments = new Type[] {fromType, toType, fromUnderlyingType}; + genericArguments = [fromType, toType, fromUnderlyingType]; genericType = typeof (EnumAdvancedConverter<,,>); } else { - genericArguments = new Type[] {fromType, toType, fromUnderlyingType, toUnderlyingType}; + genericArguments = [fromType, toType, fromUnderlyingType, toUnderlyingType]; genericType = typeof (EnumAdvancedConverter<,,,>); } } else { if (toType==fromUnderlyingType) { - genericArguments = new Type[] {fromType, toType}; + genericArguments = [fromType, toType]; genericType = typeof (EnumAdvancedConverter<,>); } else { - genericArguments = new Type[] {fromType, toType, fromUnderlyingType}; + genericArguments = [fromType, toType, fromUnderlyingType]; genericType = typeof (EnumAdvancedConverter<,,>); } } @@ -50,18 +49,18 @@ public IAdvancedConverter CreateForwardConverter() public IAdvancedConverter CreateBackwardConverter() { - Type fromType = typeof (TFrom); - Type toType = typeof (TTo); + var fromType = typeof (TFrom); + var toType = typeof (TTo); if (fromType.IsEnum) { - Type fromUnderlyingType = Enum.GetUnderlyingType(fromType); + var fromUnderlyingType = Enum.GetUnderlyingType(fromType); Type[] genericArguments; Type genericType; if (toType==fromUnderlyingType) { - genericArguments = new Type[] {toType, fromType}; + genericArguments = [toType, fromType]; genericType = typeof (EnumAdvancedConverter<,>); } else { - genericArguments = new Type[] {toType, fromType, fromUnderlyingType}; + genericArguments = [toType, fromType, fromUnderlyingType]; genericType = typeof (EnumAdvancedConverter<,,>); } object result = genericType.Activate(genericArguments, provider); diff --git a/Orm/Xtensive.Orm/Conversion/Internals/EnumAdvancedConverter{TFrom, TTo, TIntermediate}.cs b/Orm/Xtensive.Orm/Conversion/Internals/EnumAdvancedConverter{TFrom, TTo, TIntermediate}.cs index d6a6088ad2..83365d2efd 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/EnumAdvancedConverter{TFrom, TTo, TIntermediate}.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/EnumAdvancedConverter{TFrom, TTo, TIntermediate}.cs @@ -9,28 +9,27 @@ namespace Xtensive.Conversion { - [Serializable] internal class EnumAdvancedConverter : AdvancedConverterBase, IAdvancedConverter where TFrom : struct where TTo : struct where TIntermediate : struct { - private static readonly Converter outputEnumConverter = typeof(TTo).IsEnum ? DelegateHelper.CreatePrimitiveCastDelegate() : null; - private static readonly Converter inputEnumConverter = typeof(TFrom).IsEnum ? DelegateHelper.CreatePrimitiveCastDelegate() : null; + private static readonly Converter OutputEnumConverter + = typeof(TTo).IsEnum ? DelegateHelper.CreatePrimitiveCastDelegate() : null; + + private static readonly Converter InputEnumConverter + = typeof(TFrom).IsEnum ? DelegateHelper.CreatePrimitiveCastDelegate() : null; private readonly AdvancedConverterStruct outputValueTypeAdvancedConverter; private readonly AdvancedConverterStruct inputValueTypeAdvancedConverter; - public virtual TTo Convert(TFrom value) - { - TIntermediate intermediate = inputEnumConverter==null ? inputValueTypeAdvancedConverter.Convert(value) : inputEnumConverter(value); - return outputEnumConverter==null ? outputValueTypeAdvancedConverter.Convert(intermediate) : outputEnumConverter(intermediate); - } + public bool IsRough => true; - public bool IsRough + public virtual TTo Convert(TFrom value) { - get { return true; } + TIntermediate intermediate = InputEnumConverter is null ? inputValueTypeAdvancedConverter.Convert(value) : InputEnumConverter(value); + return OutputEnumConverter is null ? outputValueTypeAdvancedConverter.Convert(intermediate) : OutputEnumConverter(intermediate); } @@ -39,13 +38,13 @@ public bool IsRough public EnumAdvancedConverter(IAdvancedConverterProvider provider) : base(provider) { - Type toType = typeof (TTo); - Type fromType = typeof (TFrom); + var toType = typeof(TTo); + var fromType = typeof(TFrom); if (!toType.IsEnum && !fromType.IsEnum) throw new InvalidOperationException(); - if (!typeof (TFrom).IsEnum) + if (!fromType.IsEnum) inputValueTypeAdvancedConverter = provider.GetConverter(); - if (!typeof (TTo).IsEnum) + if (!toType.IsEnum) outputValueTypeAdvancedConverter = provider.GetConverter(); } } diff --git a/Orm/Xtensive.Orm/Conversion/Internals/EnumAdvancedConverter{TFrom, TTo, TUnderlyingFrom, TUnderlyingTo}.cs b/Orm/Xtensive.Orm/Conversion/Internals/EnumAdvancedConverter{TFrom, TTo, TUnderlyingFrom, TUnderlyingTo}.cs index c8e691cd43..23aea78080 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/EnumAdvancedConverter{TFrom, TTo, TUnderlyingFrom, TUnderlyingTo}.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/EnumAdvancedConverter{TFrom, TTo, TUnderlyingFrom, TUnderlyingTo}.cs @@ -9,7 +9,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class EnumAdvancedConverter : AdvancedConverterBase, IAdvancedConverter where TFrom : struct @@ -17,20 +16,14 @@ internal class EnumAdvancedConverter where TUnderlyingFrom : struct where TUnderlyingTo : struct { - private static readonly Converter intermediateConverter1 = DelegateHelper.CreatePrimitiveCastDelegate(); - private static readonly Converter outputConverter = DelegateHelper.CreatePrimitiveCastDelegate(); - private readonly AdvancedConverterStruct intermediateConverter2; + private static readonly Converter IntermediateConverter1 = DelegateHelper.CreatePrimitiveCastDelegate(); + private static readonly Converter OutputConverter = DelegateHelper.CreatePrimitiveCastDelegate(); + private readonly AdvancedConverterStruct intermediateConverter2; - public TTo Convert(TFrom value) - { - return outputConverter(intermediateConverter2.Convert(intermediateConverter1(value))); - } + public bool IsRough => true; - public bool IsRough - { - get { return true; } - } + public TTo Convert(TFrom value) => OutputConverter(intermediateConverter2.Convert(IntermediateConverter1(value))); // Constructors @@ -39,8 +32,8 @@ public EnumAdvancedConverter(IAdvancedConverterProvider provider) : base(provider) { // Checking types - Type toType = typeof (TTo); - Type fromType = typeof (TFrom); + var toType = typeof (TTo); + var fromType = typeof (TFrom); if (!toType.IsEnum && !fromType.IsEnum) throw new InvalidOperationException(); intermediateConverter2 = provider.GetConverter(); diff --git a/Orm/Xtensive.Orm/Conversion/Internals/EnumAdvancedConverter{TFrom, TTo}.cs b/Orm/Xtensive.Orm/Conversion/Internals/EnumAdvancedConverter{TFrom, TTo}.cs index 6f52122279..fa2b0b325f 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/EnumAdvancedConverter{TFrom, TTo}.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/EnumAdvancedConverter{TFrom, TTo}.cs @@ -9,23 +9,16 @@ namespace Xtensive.Conversion { - [Serializable] internal class EnumAdvancedConverter : AdvancedConverterBase, IAdvancedConverter where TFrom : struct where TTo : struct { - private static readonly Converter converter = DelegateHelper.CreatePrimitiveCastDelegate(); + private static readonly Converter Converter = DelegateHelper.CreatePrimitiveCastDelegate(); - public virtual TTo Convert(TFrom value) - { - return converter(value); - } + public bool IsRough => true; - public bool IsRough - { - get { return true; } - } + public virtual TTo Convert(TFrom value) => Converter(value); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/GuidAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/GuidAdvancedConverter.cs index 96ab72e772..9e54860604 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/GuidAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/GuidAdvancedConverter.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2003-2010 Xtensive LLC. +// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Roman Churakov @@ -8,15 +8,11 @@ namespace Xtensive.Conversion { - [Serializable] internal class GuidAdvancedConverter : StrictAdvancedConverterBase, IAdvancedConverter { - string IAdvancedConverter.Convert(Guid value) - { - return value.ToString(); - } + string IAdvancedConverter.Convert(Guid value) => value.ToString(); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/Int16AdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/Int16AdvancedConverter.cs index 8d13df7bcf..2bdcc8c0ea 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/Int16AdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/Int16AdvancedConverter.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2003-2010 Xtensive LLC. +// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Roman Churakov @@ -9,7 +9,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class Int16AdvancedConverter : StrictAdvancedConverterBase, IAdvancedConverter, @@ -62,10 +61,7 @@ uint IAdvancedConverter.Convert(short value) } } - long IAdvancedConverter.Convert(short value) - { - return value; - } + long IAdvancedConverter.Convert(short value) => value; ulong IAdvancedConverter.Convert(short value) { @@ -74,20 +70,11 @@ ulong IAdvancedConverter.Convert(short value) } } - float IAdvancedConverter.Convert(short value) - { - return System.Convert.ToSingle(value); - } + float IAdvancedConverter.Convert(short value) => System.Convert.ToSingle(value); - double IAdvancedConverter.Convert(short value) - { - return System.Convert.ToDouble(value); - } + double IAdvancedConverter.Convert(short value) => System.Convert.ToDouble(value); - decimal IAdvancedConverter.Convert(short value) - { - return System.Convert.ToDecimal(value); - } + decimal IAdvancedConverter.Convert(short value) => System.Convert.ToDecimal(value); DateTime IAdvancedConverter.Convert(short value) { @@ -103,15 +90,9 @@ TimeSpan IAdvancedConverter.Convert(short value) } } - string IAdvancedConverter.Convert(short value) - { - return value.ToString(CultureInfo.InvariantCulture); - } + string IAdvancedConverter.Convert(short value) => value.ToString(CultureInfo.InvariantCulture); - char IAdvancedConverter.Convert(short value) - { - return System.Convert.ToChar(value); - } + char IAdvancedConverter.Convert(short value) => System.Convert.ToChar(value); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/Int16RoughAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/Int16RoughAdvancedConverter.cs index 4c251aab93..19d93ea76f 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/Int16RoughAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/Int16RoughAdvancedConverter.cs @@ -8,15 +8,11 @@ namespace Xtensive.Conversion { - [Serializable] internal class Int16RoughAdvancedConverter : RoughAdvancedConverterBase, IAdvancedConverter { - bool IAdvancedConverter.Convert(short value) - { - return System.Convert.ToBoolean(value); - } + bool IAdvancedConverter.Convert(short value) => System.Convert.ToBoolean(value); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/Int32AdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/Int32AdvancedConverter.cs index b1c6a4baaf..3f944ac61c 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/Int32AdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/Int32AdvancedConverter.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Gamzov // Created: 2008.01.21 @@ -9,7 +9,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class Int32AdvancedConverter : StrictAdvancedConverterBase, IAdvancedConverter, @@ -22,6 +21,7 @@ internal class Int32AdvancedConverter : IAdvancedConverter, IAdvancedConverter, IAdvancedConverter, + IAdvancedConverter, IAdvancedConverter, IAdvancedConverter, IAdvancedConverter @@ -63,10 +63,7 @@ uint IAdvancedConverter.Convert(int value) } } - long IAdvancedConverter.Convert(int value) - { - return value; - } + long IAdvancedConverter.Convert(int value) => value; ulong IAdvancedConverter.Convert(int value) { @@ -75,15 +72,9 @@ ulong IAdvancedConverter.Convert(int value) } } - double IAdvancedConverter.Convert(int value) - { - return System.Convert.ToDouble(value); - } + double IAdvancedConverter.Convert(int value) => System.Convert.ToDouble(value); - decimal IAdvancedConverter.Convert(int value) - { - return System.Convert.ToDecimal(value); - } + decimal IAdvancedConverter.Convert(int value) => System.Convert.ToDecimal(value); DateTime IAdvancedConverter.Convert(int value) { @@ -92,6 +83,11 @@ DateTime IAdvancedConverter.Convert(int value) } } + DateOnly IAdvancedConverter.Convert(int value) + { + return DateOnly.FromDayNumber(value); + } + TimeSpan IAdvancedConverter.Convert(int value) { checked { @@ -99,16 +95,9 @@ TimeSpan IAdvancedConverter.Convert(int value) } } + string IAdvancedConverter.Convert(int value) => value.ToString(CultureInfo.InvariantCulture); - string IAdvancedConverter.Convert(int value) - { - return value.ToString(CultureInfo.InvariantCulture); - } - - char IAdvancedConverter.Convert(int value) - { - return System.Convert.ToChar(value); - } + char IAdvancedConverter.Convert(int value) => System.Convert.ToChar(value); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/Int32RoughAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/Int32RoughAdvancedConverter.cs index 6bd798c01e..43d124dada 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/Int32RoughAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/Int32RoughAdvancedConverter.cs @@ -8,21 +8,14 @@ namespace Xtensive.Conversion { - [Serializable] internal class Int32RoughAdvancedConverter : RoughAdvancedConverterBase, IAdvancedConverter, IAdvancedConverter { - bool IAdvancedConverter.Convert(int value) - { - return Convert.ToBoolean(value); - } + bool IAdvancedConverter.Convert(int value) => Convert.ToBoolean(value); - float IAdvancedConverter.Convert(int value) - { - return Convert.ToSingle(value); - } + float IAdvancedConverter.Convert(int value) => Convert.ToSingle(value); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/Int64AdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/Int64AdvancedConverter.cs index 2e2f5dd3a3..23c1cc0203 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/Int64AdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/Int64AdvancedConverter.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Gamzov // Created: 2008.01.22 @@ -9,7 +9,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class Int64AdvancedConverter : StrictAdvancedConverterBase, IAdvancedConverter, @@ -21,6 +20,8 @@ internal class Int64AdvancedConverter : IAdvancedConverter, IAdvancedConverter, IAdvancedConverter, + IAdvancedConverter, + IAdvancedConverter, IAdvancedConverter, IAdvancedConverter, IAdvancedConverter @@ -76,10 +77,7 @@ ulong IAdvancedConverter.Convert(long value) } } - decimal IAdvancedConverter.Convert(long value) - { - return System.Convert.ToDecimal(value); - } + decimal IAdvancedConverter.Convert(long value) => System.Convert.ToDecimal(value); DateTime IAdvancedConverter.Convert(long value) { @@ -88,23 +86,31 @@ DateTime IAdvancedConverter.Convert(long value) } } - TimeSpan IAdvancedConverter.Convert(long value) + DateOnly IAdvancedConverter.Convert(long value) { checked { - return new TimeSpan(value); + return DateOnly.FromDayNumber((int) value); } } - string IAdvancedConverter.Convert(long value) + TimeOnly IAdvancedConverter.Convert(long value) { - return value.ToString(CultureInfo.InvariantCulture); + checked { + return new TimeOnly(value); + } } - char IAdvancedConverter.Convert(long value) + TimeSpan IAdvancedConverter.Convert(long value) { - return System.Convert.ToChar(value); + checked { + return new TimeSpan(value); + } } + string IAdvancedConverter.Convert(long value) => value.ToString(CultureInfo.InvariantCulture); + + char IAdvancedConverter.Convert(long value) => System.Convert.ToChar(value); + // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/Int64RoughAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/Int64RoughAdvancedConverter.cs index 3a1c786c3d..0d3ca7d3a1 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/Int64RoughAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/Int64RoughAdvancedConverter.cs @@ -8,28 +8,20 @@ namespace Xtensive.Conversion { - [Serializable] internal class Int64RoughAdvancedConverter: RoughAdvancedConverterBase, IAdvancedConverter, IAdvancedConverter, - IAdvancedConverter + IAdvancedConverter, + IAdvancedConverter { - bool IAdvancedConverter.Convert(long value) - { - return Convert.ToBoolean(value); - } + bool IAdvancedConverter.Convert(long value) => Convert.ToBoolean(value); - float IAdvancedConverter.Convert(long value) - { - return Convert.ToSingle(value); - } + float IAdvancedConverter.Convert(long value) => Convert.ToSingle(value); - double IAdvancedConverter.Convert(long value) - { - return Convert.ToDouble(value); - } + double IAdvancedConverter.Convert(long value) => Convert.ToDouble(value); + DateTimeOffset IAdvancedConverter.Convert(long value) => new DateTimeOffset(value, TimeSpan.Zero); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/NullableAdvancedConverterFactory.cs b/Orm/Xtensive.Orm/Conversion/Internals/NullableAdvancedConverterFactory.cs index 5536d234dc..111c45ed6f 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/NullableAdvancedConverterFactory.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/NullableAdvancedConverterFactory.cs @@ -9,10 +9,9 @@ namespace Xtensive.Conversion { - [Serializable] internal class NullableAdvancedConverterFactory : IAdvancedConverterFactory { - private IAdvancedConverterProvider provider; + private readonly IAdvancedConverterProvider provider; public IAdvancedConverter CreateForwardConverter() { @@ -22,7 +21,7 @@ public IAdvancedConverter CreateForwardConverter() try { return typeof (NullableNullableAdvancedConverter<,>).Activate( - new Type[] { typeof(TFrom).GetGenericArguments()[0], typeof(TTo).GetGenericArguments()[0] }, provider) + [typeof(TFrom).GetGenericArguments()[0], typeof(TTo).GetGenericArguments()[0]], provider) as IAdvancedConverter; } catch { @@ -31,12 +30,12 @@ public IAdvancedConverter CreateForwardConverter() } else if (fromIsNullable) { return typeof (NullableForwardAdvancedConverter<,>).Activate( - new Type[] { typeof(TFrom).GetGenericArguments()[0], typeof(TTo) }, provider) + [typeof(TFrom).GetGenericArguments()[0], typeof(TTo)], provider) as IAdvancedConverter; } else if (toIsNullable) { return typeof (NullableReverseAdvancedConverter<,>).Activate( - new Type[] { typeof(TFrom), typeof(TTo).GetGenericArguments()[0] }, provider) + [typeof(TFrom), typeof(TTo).GetGenericArguments()[0]], provider) as IAdvancedConverter; } return null; @@ -47,7 +46,7 @@ public IAdvancedConverter CreateBackwardConverter() bool fromIsNullable = TypeHelper.IsNullable(); if (fromIsNullable) { return typeof (NullableReverseAdvancedConverter<,>).Activate( - new Type[] { typeof(TTo), typeof(TFrom).GetGenericArguments()[0] }, provider) + [typeof(TTo), typeof(TFrom).GetGenericArguments()[0]], provider) as IAdvancedConverter; } return null; diff --git a/Orm/Xtensive.Orm/Conversion/Internals/NullableForwardAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/NullableForwardAdvancedConverter.cs index 78d1992533..1ec892ce1f 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/NullableForwardAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/NullableForwardAdvancedConverter.cs @@ -8,7 +8,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class NullableForwardAdvancedConverter : WrappingAdvancedConverter where TFrom : struct { diff --git a/Orm/Xtensive.Orm/Conversion/Internals/NullableNullableAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/NullableNullableAdvancedConverter.cs index 0a3a62950d..ef8aeaa791 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/NullableNullableAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/NullableNullableAdvancedConverter.cs @@ -8,7 +8,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class NullableNullableAdvancedConverter : WrappingAdvancedConverter where TFrom : struct where TTo : struct diff --git a/Orm/Xtensive.Orm/Conversion/Internals/NullableReverseAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/NullableReverseAdvancedConverter.cs index cff8e55ac1..61fc63e5ff 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/NullableReverseAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/NullableReverseAdvancedConverter.cs @@ -8,15 +8,11 @@ namespace Xtensive.Conversion { - [Serializable] internal class NullableReverseAdvancedConverter : WrappingAdvancedConverter where TTo : struct { /// - public override TTo? Convert(TFrom value) - { - return BaseConverter.Convert(value); - } + public override TTo? Convert(TFrom value) => BaseConverter.Convert(value); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/ObjectAdvancedConverterFactory.cs b/Orm/Xtensive.Orm/Conversion/Internals/ObjectAdvancedConverterFactory.cs index 600d8a691a..024c852c18 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/ObjectAdvancedConverterFactory.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/ObjectAdvancedConverterFactory.cs @@ -9,7 +9,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class ObjectAdvancedConverterFactory : IAdvancedConverterFactory { @@ -34,15 +33,15 @@ public IAdvancedConverter CreateForwardConverter() public IAdvancedConverter CreateBackwardConverter() { - Type fromType = typeof (TFrom); - Type toType = typeof (TTo); + var fromType = typeof (TFrom); + var toType = typeof (TTo); if (fromType.IsAssignableFrom(toType)) { - Type[] genericArguments = new Type[] {toType, fromType}; + Type[] genericArguments = [toType, fromType]; Type genericType = typeof (ObjectToBaseAdvancedConverter<,>); return genericType.Activate(genericArguments, provider) as IAdvancedConverter; } else if (toType.IsAssignableFrom(fromType)) { - Type[] genericArguments = new Type[] {toType, fromType}; + Type[] genericArguments = [toType, fromType]; Type genericType = typeof (ObjectToDescendantAdvancedConverter<,>); return genericType.Activate(genericArguments, provider) as IAdvancedConverter; } diff --git a/Orm/Xtensive.Orm/Conversion/Internals/ObjectToBaseAdvancedConverter{TFrom, TTo}.cs b/Orm/Xtensive.Orm/Conversion/Internals/ObjectToBaseAdvancedConverter{TFrom, TTo}.cs index 64361596bc..d662fd35bd 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/ObjectToBaseAdvancedConverter{TFrom, TTo}.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/ObjectToBaseAdvancedConverter{TFrom, TTo}.cs @@ -8,7 +8,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class ObjectToBaseAdvancedConverter : AdvancedConverterBase, IAdvancedConverter where TFrom : TTo diff --git a/Orm/Xtensive.Orm/Conversion/Internals/ObjectToDescendantAdvancedConverter{TFrom, TTo}.cs b/Orm/Xtensive.Orm/Conversion/Internals/ObjectToDescendantAdvancedConverter{TFrom, TTo}.cs index 78f8c0a9cd..3a487085bd 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/ObjectToDescendantAdvancedConverter{TFrom, TTo}.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/ObjectToDescendantAdvancedConverter{TFrom, TTo}.cs @@ -8,20 +8,13 @@ namespace Xtensive.Conversion { - [Serializable] internal class ObjectToDescendantAdvancedConverter : AdvancedConverterBase, IAdvancedConverter where TTo : TFrom { - public virtual TTo Convert(TFrom value) - { - return (TTo)value; - } + public bool IsRough => false; - public bool IsRough - { - get { return false; } - } + public virtual TTo Convert(TFrom value) => (TTo) value; // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/RoughAdvancedConverterBase.cs b/Orm/Xtensive.Orm/Conversion/Internals/RoughAdvancedConverterBase.cs index 18cdcbf57e..029ce1c34f 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/RoughAdvancedConverterBase.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/RoughAdvancedConverterBase.cs @@ -8,16 +8,12 @@ namespace Xtensive.Conversion { - [Serializable] internal abstract class RoughAdvancedConverterBase: AdvancedConverterBase { /// /// Gets if converter is rough, otherwise gets . /// - public bool IsRough - { - get { return true; } - } + public bool IsRough => true; // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/SByteAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/SByteAdvancedConverter.cs index 5de87348ff..7e40b0404b 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/SByteAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/SByteAdvancedConverter.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2003-2010 Xtensive LLC. +// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Roman Churakov @@ -9,7 +9,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class SByteAdvancedConverter : StrictAdvancedConverterBase, IAdvancedConverter, @@ -36,10 +35,7 @@ byte IAdvancedConverter.Convert(sbyte value) } } - short IAdvancedConverter.Convert(sbyte value) - { - return value; - } + short IAdvancedConverter.Convert(sbyte value) => value; ushort IAdvancedConverter.Convert(sbyte value) { @@ -48,10 +44,7 @@ ushort IAdvancedConverter.Convert(sbyte value) } } - int IAdvancedConverter.Convert(sbyte value) - { - return value; - } + int IAdvancedConverter.Convert(sbyte value) => value; uint IAdvancedConverter.Convert(sbyte value) { @@ -60,10 +53,7 @@ uint IAdvancedConverter.Convert(sbyte value) } } - long IAdvancedConverter.Convert(sbyte value) - { - return value; - } + long IAdvancedConverter.Convert(sbyte value) => value; ulong IAdvancedConverter.Convert(sbyte value) { @@ -72,20 +62,11 @@ ulong IAdvancedConverter.Convert(sbyte value) } } - float IAdvancedConverter.Convert(sbyte value) - { - return System.Convert.ToSingle(value); - } + float IAdvancedConverter.Convert(sbyte value) => System.Convert.ToSingle(value); - double IAdvancedConverter.Convert(sbyte value) - { - return System.Convert.ToDouble(value); - } + double IAdvancedConverter.Convert(sbyte value) => System.Convert.ToDouble(value); - decimal IAdvancedConverter.Convert(sbyte value) - { - return System.Convert.ToDecimal(value); - } + decimal IAdvancedConverter.Convert(sbyte value) => System.Convert.ToDecimal(value); DateTime IAdvancedConverter.Convert(sbyte value) { @@ -101,15 +82,9 @@ TimeSpan IAdvancedConverter.Convert(sbyte value) } } - string IAdvancedConverter.Convert(sbyte value) - { - return value.ToString(CultureInfo.InvariantCulture); - } + string IAdvancedConverter.Convert(sbyte value) => value.ToString(CultureInfo.InvariantCulture); - char IAdvancedConverter.Convert(sbyte value) - { - return System.Convert.ToChar(value); - } + char IAdvancedConverter.Convert(sbyte value) => System.Convert.ToChar(value); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/SByteRoughAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/SByteRoughAdvancedConverter.cs index 192c75ca58..5f1e0fc1b0 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/SByteRoughAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/SByteRoughAdvancedConverter.cs @@ -8,15 +8,11 @@ namespace Xtensive.Conversion { - [Serializable] internal class SByteRoughAdvancedConverter : RoughAdvancedConverterBase, IAdvancedConverter { - bool IAdvancedConverter.Convert(sbyte value) - { - return Convert.ToBoolean(value); - } + bool IAdvancedConverter.Convert(sbyte value) => Convert.ToBoolean(value); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/SingleAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/SingleAdvancedConverter.cs index 149ce9b75d..d32a6eda5a 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/SingleAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/SingleAdvancedConverter.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2003-2010 Xtensive LLC. +// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Roman Churakov @@ -9,7 +9,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class SingleAdvancedConverter : StrictAdvancedConverterBase, IAdvancedConverter diff --git a/Orm/Xtensive.Orm/Conversion/Internals/SingleRoughAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/SingleRoughAdvancedConverter.cs index e58d3474f5..0d50b57a97 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/SingleRoughAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/SingleRoughAdvancedConverter.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Alexey Gamzov // Created: 2008.02.08 @@ -8,7 +8,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class SingleRoughAdvancedConverter : RoughAdvancedConverterBase, IAdvancedConverter, @@ -23,10 +22,13 @@ internal class SingleRoughAdvancedConverter : IAdvancedConverter, IAdvancedConverter, IAdvancedConverter, + IAdvancedConverter, + IAdvancedConverter, IAdvancedConverter, IAdvancedConverter { private readonly long baseDateTimeTicks; + private readonly long ticksPerDay; bool IAdvancedConverter.Convert(float value) { @@ -97,6 +99,20 @@ DateTime IAdvancedConverter.Convert(float value) } } + DateOnly IAdvancedConverter.Convert(float value) + { + checked { + return DateOnly.FromDayNumber(Convert.ToInt32(Math.Round(value))); + } + } + + TimeOnly IAdvancedConverter.Convert(float value) + { + checked { + return new TimeOnly((long) Math.Round(value)); + } + } + TimeSpan IAdvancedConverter.Convert(float value) { // Since "Convert.ToUInt64(double)" does not check overflow: @@ -120,6 +136,7 @@ public SingleRoughAdvancedConverter(IAdvancedConverterProvider provider) : base(provider) { baseDateTimeTicks = provider.BaseTime.Ticks; + ticksPerDay = TimeSpan.FromDays(1).Ticks; } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Conversion/Internals/StrictAdvancedConverterBase.cs b/Orm/Xtensive.Orm/Conversion/Internals/StrictAdvancedConverterBase.cs index 18792846e2..d3510aa8b3 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/StrictAdvancedConverterBase.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/StrictAdvancedConverterBase.cs @@ -8,7 +8,6 @@ namespace Xtensive.Conversion { - [Serializable] internal abstract class StrictAdvancedConverterBase: AdvancedConverterBase, IAdvancedConverter { diff --git a/Orm/Xtensive.Orm/Conversion/Internals/StringAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/StringAdvancedConverter.cs index 7288bca1c8..e19b364ee6 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/StringAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/StringAdvancedConverter.cs @@ -8,7 +8,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class StringAdvancedConverter : StrictAdvancedConverterBase { diff --git a/Orm/Xtensive.Orm/Conversion/Internals/StringRoughAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/StringRoughAdvancedConverter.cs index acb2dbdc78..d80bbfaf5d 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/StringRoughAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/StringRoughAdvancedConverter.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2008-2020 Xtensive LLC. +// Copyright (C) 2008-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexey Gamzov @@ -9,7 +9,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class StringRoughAdvancedConverter : RoughAdvancedConverterBase, IAdvancedConverter, @@ -24,23 +23,24 @@ internal class StringRoughAdvancedConverter : IAdvancedConverter, IAdvancedConverter, IAdvancedConverter, + IAdvancedConverter, IAdvancedConverter, + IAdvancedConverter, + IAdvancedConverter, IAdvancedConverter, - IAdvancedConverter + IAdvancedConverter, + IAdvancedConverter { - bool IAdvancedConverter.Convert(string value) - { - return Boolean.Parse(value); - } + bool IAdvancedConverter.Convert(string value) => bool.Parse(value); byte IAdvancedConverter.Convert(string value) { try { - return Byte.Parse(value, NumberStyles.Any, CultureInfo.InvariantCulture); + return byte.Parse(value, NumberStyles.Any, CultureInfo.InvariantCulture); } catch (FormatException) { if (value.Substring(0, 2).ToUpper().Equals("0X")) - return Byte.Parse(value.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture); + return byte.Parse(value.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture); throw; } } @@ -48,11 +48,11 @@ byte IAdvancedConverter.Convert(string value) sbyte IAdvancedConverter.Convert(string value) { try { - return SByte.Parse(value, NumberStyles.Any, CultureInfo.InvariantCulture); + return sbyte.Parse(value, NumberStyles.Any, CultureInfo.InvariantCulture); } catch (FormatException) { if (value.Substring(0, 2).ToUpper().Equals("0X")) - return SByte.Parse(value.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture); + return sbyte.Parse(value.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture); throw; } } @@ -144,9 +144,20 @@ decimal IAdvancedConverter.Convert(string value) return decimal.Parse(value, NumberStyles.Any, CultureInfo.InvariantCulture); } + DateTimeOffset IAdvancedConverter.Convert(string value) + { + string[] strings = { "yyyy/MM/dd hh:mm:ss.fffffff tt zzz", "yyyy/MM/dd hh:mm:ss.fffffff ttzzz" }; + try { + return DateTimeOffset.ParseExact(value, strings, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces); + } + catch (FormatException) { + return DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces); + } + } + DateTime IAdvancedConverter.Convert(string value) { - string[] strings = {"yyyy/MM/dd hh:mm:ss.fffffff tt K "}; + string[] strings = { "yyyy/MM/dd hh:mm:ss.fffffff tt K " }; try { return DateTime.ParseExact(value, strings, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); } @@ -155,16 +166,34 @@ DateTime IAdvancedConverter.Convert(string value) } } - TimeSpan IAdvancedConverter.Convert(string value) + DateOnly IAdvancedConverter.Convert(string value) { - return TimeSpan.Parse(value); + string[] strings = { "yyyy/MM/dd" }; + try { + return DateOnly.ParseExact(value, strings, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces); + } + catch (FormatException) { + return DateOnly.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces); + } } - Guid IAdvancedConverter.Convert(string value) + TimeOnly IAdvancedConverter.Convert(string value) { - return new Guid(value); + string[] strings = { "hh:mm:ss.fffffff tt" }; + try { + return TimeOnly.ParseExact(value, strings, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces); + } + catch (FormatException) { + return TimeOnly.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces); + } } + TimeSpan IAdvancedConverter.Convert(string value) => TimeSpan.Parse(value); + + Guid IAdvancedConverter.Convert(string value) => new Guid(value); + + char IAdvancedConverter.Convert(string value) => char.Parse(value); + // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/StringRoughAdvancedConverter{T}.cs b/Orm/Xtensive.Orm/Conversion/Internals/StringRoughAdvancedConverter{T}.cs index f2d6d2dc7d..ab1435fc43 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/StringRoughAdvancedConverter{T}.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/StringRoughAdvancedConverter{T}.cs @@ -8,15 +8,11 @@ namespace Xtensive.Conversion { - [Serializable] internal class StringRoughAdvancedConverter : RoughAdvancedConverterBase, IAdvancedConverter { - string IAdvancedConverter.Convert(T value) - { - return value.ToString(); - } + string IAdvancedConverter.Convert(T value) => value.ToString(); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/TimeOnlyAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/TimeOnlyAdvancedConverter.cs new file mode 100644 index 0000000000..e8449771b5 --- /dev/null +++ b/Orm/Xtensive.Orm/Conversion/Internals/TimeOnlyAdvancedConverter.cs @@ -0,0 +1,42 @@ +// Copyright (C) 2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System; +using System.Globalization; + +namespace Xtensive.Conversion +{ + internal class TimeOnlyAdvancedConverter : + StrictAdvancedConverterBase, + IAdvancedConverter, + IAdvancedConverter, + IAdvancedConverter, + IAdvancedConverter, + IAdvancedConverter + { + long IAdvancedConverter.Convert(TimeOnly value) => value.Ticks; + + ulong IAdvancedConverter.Convert(TimeOnly value) + { + checked { + return (ulong) (value.Ticks); + } + } + + decimal IAdvancedConverter.Convert(TimeOnly value) => System.Convert.ToDecimal(value.Ticks); + + TimeSpan IAdvancedConverter.Convert(TimeOnly value) => value.ToTimeSpan(); + + string IAdvancedConverter.Convert(TimeOnly value) + => value.ToString("hh:mm:ss.fffffff tt K ", CultureInfo.InvariantCulture); + + + // Constructors + + public TimeOnlyAdvancedConverter(IAdvancedConverterProvider provider) + : base(provider) + { + } + } +} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Conversion/Internals/TimeOnlyRoughAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/TimeOnlyRoughAdvancedConverter.cs new file mode 100644 index 0000000000..f88a97944d --- /dev/null +++ b/Orm/Xtensive.Orm/Conversion/Internals/TimeOnlyRoughAdvancedConverter.cs @@ -0,0 +1,25 @@ +// Copyright (C) 2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System; + +namespace Xtensive.Conversion +{ + internal class TimeOnlyRoughAdvancedConverter : + RoughAdvancedConverterBase, + IAdvancedConverter, + IAdvancedConverter + { + float IAdvancedConverter.Convert(TimeOnly value) => Convert.ToSingle(value.Ticks); + double IAdvancedConverter.Convert(TimeOnly value) => Convert.ToDouble(value.Ticks); + + + // Constructors + + public TimeOnlyRoughAdvancedConverter(IAdvancedConverterProvider provider) + : base(provider) + { + } + } +} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Conversion/Internals/TimeSpanAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/TimeSpanAdvancedConverter.cs index a03b9d3a87..6c4c1bfa6c 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/TimeSpanAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/TimeSpanAdvancedConverter.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Elena Vakhtina // Created: 2008.11.11 @@ -8,7 +8,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class TimeSpanAdvancedConverter : StrictAdvancedConverterBase, IAdvancedConverter, @@ -20,6 +19,7 @@ internal class TimeSpanAdvancedConverter : IAdvancedConverter, IAdvancedConverter, IAdvancedConverter, + IAdvancedConverter, IAdvancedConverter, IAdvancedConverter { @@ -79,20 +79,13 @@ ulong IAdvancedConverter.Convert(TimeSpan value) } } - decimal IAdvancedConverter.Convert(TimeSpan value) - { - return System.Convert.ToDecimal(value.Ticks); - } + decimal IAdvancedConverter.Convert(TimeSpan value) => System.Convert.ToDecimal(value.Ticks); - TimeSpan IAdvancedConverter.Convert(TimeSpan value) - { - return value; - } + TimeSpan IAdvancedConverter.Convert(TimeSpan value) => value; - string IAdvancedConverter.Convert(TimeSpan value) - { - return value.ToString(); - } + TimeOnly IAdvancedConverter.Convert(TimeSpan value) => TimeOnly.FromTimeSpan(value); + + string IAdvancedConverter.Convert(TimeSpan value) => value.ToString(); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/TimeSpanRoughAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/TimeSpanRoughAdvancedConverter.cs index 044131728e..c64584ab62 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/TimeSpanRoughAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/TimeSpanRoughAdvancedConverter.cs @@ -8,22 +8,20 @@ namespace Xtensive.Conversion { - [Serializable] internal class TimeSpanRoughAdvancedConverter : RoughAdvancedConverterBase, IAdvancedConverter, - IAdvancedConverter + IAdvancedConverter, + IAdvancedConverter, + IAdvancedConverter { - float IAdvancedConverter.Convert(TimeSpan value) - { - return Convert.ToSingle(value.Ticks); - } + float IAdvancedConverter.Convert(TimeSpan value) => Convert.ToSingle(value.Ticks); - double IAdvancedConverter.Convert(TimeSpan value) - { - return Convert.ToDouble(value.Ticks); - } + double IAdvancedConverter.Convert(TimeSpan value) => Convert.ToDouble(value.Ticks); + + DateOnly IAdvancedConverter.Convert(TimeSpan value) => DateOnly.FromDayNumber((int) Math.Round(value.TotalDays)); + DateTimeOffset IAdvancedConverter.Convert(TimeSpan value) => new DateTimeOffset(value.Ticks, TimeSpan.Zero); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/TypeAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/TypeAdvancedConverter.cs index 0241bfe769..b9b1774926 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/TypeAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/TypeAdvancedConverter.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2003-2010 Xtensive LLC. +// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Alex Yakunin @@ -8,21 +8,14 @@ namespace Xtensive.Conversion { - [Serializable] internal class TypeAdvancedConverter : StrictAdvancedConverterBase, IAdvancedConverter, IAdvancedConverter { - string IAdvancedConverter.Convert(Type value) - { - return value.AssemblyQualifiedName; - } + string IAdvancedConverter.Convert(Type value) => value.AssemblyQualifiedName; - Type IAdvancedConverter.Convert(string value) - { - return Type.GetType(value, true, false); - } + Type IAdvancedConverter.Convert(string value) => Type.GetType(value, true, false); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/UInt16AdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/UInt16AdvancedConverter.cs index a50db528a3..133e5172e8 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/UInt16AdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/UInt16AdvancedConverter.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2003-2010 Xtensive LLC. +// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Roman Churakov @@ -9,7 +9,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class UInt16AdvancedConverter : StrictAdvancedConverterBase, IAdvancedConverter, @@ -51,40 +50,19 @@ short IAdvancedConverter.Convert(ushort value) } } - int IAdvancedConverter.Convert(ushort value) - { - return value; - } + int IAdvancedConverter.Convert(ushort value) => value; - uint IAdvancedConverter.Convert(ushort value) - { - return value; - } + uint IAdvancedConverter.Convert(ushort value) => value; - long IAdvancedConverter.Convert(ushort value) - { - return value; - } + long IAdvancedConverter.Convert(ushort value) => value; - ulong IAdvancedConverter.Convert(ushort value) - { - return value; - } + ulong IAdvancedConverter.Convert(ushort value) => value; - float IAdvancedConverter.Convert(ushort value) - { - return System.Convert.ToSingle(value); - } + float IAdvancedConverter.Convert(ushort value) => System.Convert.ToSingle(value); - double IAdvancedConverter.Convert(ushort value) - { - return System.Convert.ToDouble(value); - } + double IAdvancedConverter.Convert(ushort value) => System.Convert.ToDouble(value); - decimal IAdvancedConverter.Convert(ushort value) - { - return System.Convert.ToDecimal(value); - } + decimal IAdvancedConverter.Convert(ushort value) => System.Convert.ToDecimal(value); DateTime IAdvancedConverter.Convert(ushort value) { @@ -100,15 +78,9 @@ TimeSpan IAdvancedConverter.Convert(ushort value) } } - string IAdvancedConverter.Convert(ushort value) - { - return System.Convert.ToString(value, CultureInfo.InvariantCulture); - } + string IAdvancedConverter.Convert(ushort value) => System.Convert.ToString(value, CultureInfo.InvariantCulture); - char IAdvancedConverter.Convert(ushort value) - { - return System.Convert.ToChar(value); - } + char IAdvancedConverter.Convert(ushort value) => System.Convert.ToChar(value); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/UInt16RoughAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/UInt16RoughAdvancedConverter.cs index 25630838db..81c8402019 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/UInt16RoughAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/UInt16RoughAdvancedConverter.cs @@ -8,15 +8,11 @@ namespace Xtensive.Conversion { - [Serializable] internal class UInt16RoughAdvancedConverter : RoughAdvancedConverterBase, IAdvancedConverter { - bool IAdvancedConverter.Convert(ushort value) - { - return Convert.ToBoolean(value); - } + bool IAdvancedConverter.Convert(ushort value) => Convert.ToBoolean(value); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/UInt32AdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/UInt32AdvancedConverter.cs index 6a32e8d6e2..6bf936d7f3 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/UInt32AdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/UInt32AdvancedConverter.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.23 @@ -9,7 +9,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class UInt32AdvancedConverter : StrictAdvancedConverterBase, IAdvancedConverter, @@ -22,6 +21,7 @@ internal class UInt32AdvancedConverter : IAdvancedConverter, IAdvancedConverter, IAdvancedConverter, + IAdvancedConverter, IAdvancedConverter, IAdvancedConverter, IAdvancedConverter @@ -63,26 +63,13 @@ int IAdvancedConverter.Convert(uint value) } } - long IAdvancedConverter.Convert(uint value) - { - return value; - } + long IAdvancedConverter.Convert(uint value) => value; - ulong IAdvancedConverter.Convert(uint value) - { - return value; - } + ulong IAdvancedConverter.Convert(uint value) => value; + double IAdvancedConverter.Convert(uint value) => System.Convert.ToDouble(value); - double IAdvancedConverter.Convert(uint value) - { - return System.Convert.ToDouble(value); - } - - decimal IAdvancedConverter.Convert(uint value) - { - return System.Convert.ToDecimal(value); - } + decimal IAdvancedConverter.Convert(uint value) => System.Convert.ToDecimal(value); DateTime IAdvancedConverter.Convert(uint value) { @@ -91,22 +78,23 @@ DateTime IAdvancedConverter.Convert(uint value) } } - TimeSpan IAdvancedConverter.Convert(uint value) + DateOnly IAdvancedConverter.Convert(uint value) { checked { - return new TimeSpan(value); + return DateOnly.FromDayNumber((int) value); } } - string IAdvancedConverter.Convert(uint value) + TimeSpan IAdvancedConverter.Convert(uint value) { - return System.Convert.ToString(value, CultureInfo.InvariantCulture); + checked { + return new TimeSpan(value); + } } - char IAdvancedConverter.Convert(uint value) - { - return System.Convert.ToChar(value); - } + string IAdvancedConverter.Convert(uint value) => System.Convert.ToString(value, CultureInfo.InvariantCulture); + + char IAdvancedConverter.Convert(uint value) => System.Convert.ToChar(value); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/UInt32RoughAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/UInt32RoughAdvancedConverter.cs index 922127759f..4bba95205b 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/UInt32RoughAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/UInt32RoughAdvancedConverter.cs @@ -8,21 +8,14 @@ namespace Xtensive.Conversion { - [Serializable] internal class UInt32RoughAdvancedConverter : RoughAdvancedConverterBase, IAdvancedConverter, IAdvancedConverter { - bool IAdvancedConverter.Convert(uint value) - { - return Convert.ToBoolean(value); - } + bool IAdvancedConverter.Convert(uint value) => Convert.ToBoolean(value); - float IAdvancedConverter.Convert(uint value) - { - return Convert.ToSingle(value); - } + float IAdvancedConverter.Convert(uint value) => Convert.ToSingle(value); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/Internals/UInt64AdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/UInt64AdvancedConverter.cs index 0391cf95d3..7110a2c490 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/UInt64AdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/UInt64AdvancedConverter.cs @@ -1,6 +1,6 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. +// Copyright (C) 2008-2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. // Created by: Roman Churakov // Created: 2008.01.23 @@ -9,7 +9,6 @@ namespace Xtensive.Conversion { - [Serializable] internal class UInt64AdvancedConverter : StrictAdvancedConverterBase, IAdvancedConverter, @@ -21,6 +20,8 @@ internal class UInt64AdvancedConverter : IAdvancedConverter, IAdvancedConverter, IAdvancedConverter, + IAdvancedConverter, + IAdvancedConverter, IAdvancedConverter, IAdvancedConverter, IAdvancedConverter @@ -88,6 +89,20 @@ DateTime IAdvancedConverter.Convert(ulong value) } } + DateOnly IAdvancedConverter.Convert(ulong value) + { + checked { + return DateOnly.FromDayNumber((int) value); + } + } + + TimeOnly IAdvancedConverter.Convert(ulong value) + { + checked { + return new TimeOnly((long) value); + } + } + TimeSpan IAdvancedConverter.Convert(ulong value) { checked { diff --git a/Orm/Xtensive.Orm/Conversion/Internals/UInt64RoughAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/Internals/UInt64RoughAdvancedConverter.cs index e2878dc4fa..3aeaf845ed 100644 --- a/Orm/Xtensive.Orm/Conversion/Internals/UInt64RoughAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/Internals/UInt64RoughAdvancedConverter.cs @@ -8,27 +8,20 @@ namespace Xtensive.Conversion { - [Serializable] internal class UInt64RoughAdvancedConverter : RoughAdvancedConverterBase, IAdvancedConverter, IAdvancedConverter, - IAdvancedConverter + IAdvancedConverter, + IAdvancedConverter { - bool IAdvancedConverter.Convert(ulong value) - { - return Convert.ToBoolean(value); - } + bool IAdvancedConverter.Convert(ulong value) => Convert.ToBoolean(value); - float IAdvancedConverter.Convert(ulong value) - { - return Convert.ToSingle(value); - } + float IAdvancedConverter.Convert(ulong value) => Convert.ToSingle(value); - double IAdvancedConverter.Convert(ulong value) - { - return Convert.ToDouble(value); - } + double IAdvancedConverter.Convert(ulong value) => Convert.ToDouble(value); + + DateTimeOffset IAdvancedConverter.Convert(ulong value) => new DateTimeOffset(Convert.ToInt64(value), TimeSpan.Zero); // Constructors diff --git a/Orm/Xtensive.Orm/Conversion/WrappingAdvancedConverter.cs b/Orm/Xtensive.Orm/Conversion/WrappingAdvancedConverter.cs index 51eef3c4e0..f6654f38d4 100644 --- a/Orm/Xtensive.Orm/Conversion/WrappingAdvancedConverter.cs +++ b/Orm/Xtensive.Orm/Conversion/WrappingAdvancedConverter.cs @@ -11,7 +11,6 @@ namespace Xtensive.Conversion /// /// Base class for any wrapping s. /// - [Serializable] public abstract class WrappingAdvancedConverter : AdvancedConverterBase, IAdvancedConverter { @@ -20,6 +19,11 @@ public abstract class WrappingAdvancedConverter /// protected AdvancedConverterStruct BaseConverter; + /// + /// Gets if converter is rough, otherwise gets . + /// + public virtual bool IsRough => BaseConverter.IsRough; + /// /// Converts specified value of type /// to type. @@ -28,14 +32,6 @@ public abstract class WrappingAdvancedConverter ///Converted value. public abstract TTo Convert(TFrom value); - /// - /// Gets if converter is rough, otherwise gets . - /// - public virtual bool IsRough - { - get { return BaseConverter.IsRough; } - } - // Constructors diff --git a/Orm/Xtensive.Orm/Core/AliasGenerator.cs b/Orm/Xtensive.Orm/Core/AliasGenerator.cs index 8550343d47..9a1cc26744 100644 --- a/Orm/Xtensive.Orm/Core/AliasGenerator.cs +++ b/Orm/Xtensive.Orm/Core/AliasGenerator.cs @@ -11,7 +11,6 @@ namespace Xtensive.Core /// /// Universal alias generator. /// - [Serializable] public sealed class AliasGenerator { /// @@ -57,28 +56,19 @@ private void VerifyState() /// Creates generator with default settings. /// /// - public static AliasGenerator Create() - { - return new AliasGenerator(); - } + public static AliasGenerator Create() => new AliasGenerator(); /// /// Creates generator using specified alias template. /// /// Alias template. Could use two template parameters: {0} - for prefix and {1} for suffix. - public static AliasGenerator Create(string aliasTemplate) - { - return new AliasGenerator(aliasTemplate); - } + public static AliasGenerator Create(string aliasTemplate) => new AliasGenerator(aliasTemplate); /// /// Creates generator using specified prefix sequence. /// /// The overridden prefix sequence. - public static AliasGenerator Create(string [] overriddenPrefixes) - { - return new AliasGenerator(overriddenPrefixes); - } + public static AliasGenerator Create(string[] overriddenPrefixes) => new AliasGenerator(overriddenPrefixes); /// /// Creates generator using specified and . @@ -86,9 +76,7 @@ public static AliasGenerator Create(string [] overriddenPrefixes) /// The overridden prefix sequence. /// The alias template. public static AliasGenerator Create(string[] overriddenPrefixes, string aliasTemplate) - { - return new AliasGenerator(overriddenPrefixes, aliasTemplate); - } + => new AliasGenerator(overriddenPrefixes, aliasTemplate); // Constructors diff --git a/Orm/Xtensive.Orm/Core/AssociateProvider.cs b/Orm/Xtensive.Orm/Core/AssociateProvider.cs index 5df18cedfe..c0fedf0252 100644 --- a/Orm/Xtensive.Orm/Core/AssociateProvider.cs +++ b/Orm/Xtensive.Orm/Core/AssociateProvider.cs @@ -9,8 +9,6 @@ using System.Collections.Concurrent; using System.Diagnostics; using System.Reflection; -using System.Runtime.Serialization; -using System.Security; using System.Text; using System.Threading; using Xtensive.Comparison; @@ -23,10 +21,7 @@ namespace Xtensive.Core /// Implements base functionality for associate provider. /// Creates and caches associates. /// - [Serializable] - public abstract class AssociateProvider : - IDeserializationCallback, - ISerializable + public abstract class AssociateProvider { private static readonly AsyncLocal> inProgressAsync = new AsyncLocal>(); @@ -36,16 +31,10 @@ public abstract class AssociateProvider : set => inProgressAsync.Value = value; } - [NonSerialized] private readonly object highPriorityLocationsLock = new object(); + private readonly ConcurrentDictionary<(Type, Type), Lazy> cache = new(); - [NonSerialized] - private ConcurrentDictionary<(Type, Type), Lazy> cache; - - private object[] constructorParams; - private string[] typeSuffixes; - - private List> highPriorityLocations = new List>(); + private List> highPriorityLocations = new(); private List> HighPriorityLocations { get { @@ -58,24 +47,12 @@ private List> HighPriorityLocations { /// /// Gets associate constructor parameters. /// - protected object[] ConstructorParams - { - [DebuggerStepThrough] - get => constructorParams; - [DebuggerStepThrough] - set => constructorParams = value; - } + protected object[] ConstructorParams { get; set; } /// /// Gets or sets associate type suffixes. /// - protected string[] TypeSuffixes - { - [DebuggerStepThrough] - get => typeSuffixes; - [DebuggerStepThrough] - set => typeSuffixes = value; - } + protected string[] TypeSuffixes { get; set; } /// /// Adds high priority location for associate search. @@ -83,9 +60,7 @@ protected string[] TypeSuffixes /// Assembly to search in. /// Namespace to search in. public void AddHighPriorityLocation(Assembly assembly, string nameSpace) - { - AddHighPriorityLocation(assembly, nameSpace, false); - } + => AddHighPriorityLocation(assembly, nameSpace, false); /// /// Adds high priority location for associate search. @@ -239,7 +214,7 @@ protected virtual TAssociate CreateAssociate(out Type foundFor } try { return TypeHelper.CreateAssociate( - typeof(TKey), out foundFor, TypeSuffixes, constructorParams, HighPriorityLocations); + typeof(TKey), out foundFor, TypeSuffixes, ConstructorParams, HighPriorityLocations); } finally { _ = InProgress.Remove(progressionMark); @@ -289,54 +264,7 @@ protected virtual TResult ConvertAssociate(TA /// protected AssociateProvider() { - constructorParams = new object[] { this }; - cache = new ConcurrentDictionary<(Type, Type), Lazy>(); - } - - protected AssociateProvider(SerializationInfo info, StreamingContext context) - { - if (info == null) { - throw new ArgumentNullException(nameof(info)); - } - - var constructorParamsExceptThis = (object[]) info.GetValue(nameof(constructorParams), typeof(object[])); - constructorParams = new object[constructorParamsExceptThis.Length + 1]; - constructorParams[0] = this; - Array.Copy(constructorParamsExceptThis, 0, constructorParams, 1, constructorParamsExceptThis.Length); - - typeSuffixes = (string[]) info.GetValue(nameof(typeSuffixes), typeof(string[])); - - var highPriorityLocationsSerializable = (List>) info.GetValue(nameof(highPriorityLocations), typeof(List>)); - highPriorityLocations = highPriorityLocationsSerializable.SelectToList(ls => new Pair(Assembly.Load(ls.First), ls.Second)); - } - - /// - /// Performs post-deserialization actions. - /// - /// - public virtual void OnDeserialization(object sender) - { - cache = new ConcurrentDictionary<(Type, Type), Lazy>(); - } - - /// - [SecurityCritical] - public virtual void GetObjectData(SerializationInfo info, StreamingContext context) - { - object[] constructorParamsExceptThis = null; - // need to exclude this form parameters to prevent loop - if (constructorParams.Length == 1) { - constructorParamsExceptThis = Array.Empty(); - } - else { - constructorParamsExceptThis = new object[constructorParams.Length - 1]; - Array.Copy(constructorParams, 1, constructorParamsExceptThis, 0, constructorParamsExceptThis.Length); - } - info.AddValue(nameof(constructorParams), constructorParamsExceptThis, constructorParams.GetType()); - info.AddValue(nameof(typeSuffixes), typeSuffixes, typeSuffixes.GetType()); - - var highPriorityLocationsSerializable = HighPriorityLocations.SelectToList(l => new Pair(l.First.FullName, l.Second)); - info.AddValue(nameof(highPriorityLocations), highPriorityLocationsSerializable, highPriorityLocationsSerializable.GetType()); + ConstructorParams = new object[] { this }; } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Core/Direction.cs b/Orm/Xtensive.Orm/Core/Direction.cs index be1ab678b4..76741a5a49 100644 --- a/Orm/Xtensive.Orm/Core/Direction.cs +++ b/Orm/Xtensive.Orm/Core/Direction.cs @@ -11,7 +11,6 @@ namespace Xtensive.Core /// /// Possible directions of iteration through the enumerable. /// - [Serializable] public enum Direction : sbyte { /// diff --git a/Orm/Xtensive.Orm/Core/ExceptionAggregator.cs b/Orm/Xtensive.Orm/Core/ExceptionAggregator.cs index 5a7dd6b345..524e1da501 100644 --- a/Orm/Xtensive.Orm/Core/ExceptionAggregator.cs +++ b/Orm/Xtensive.Orm/Core/ExceptionAggregator.cs @@ -10,8 +10,6 @@ using System.Diagnostics; using System.Linq; using System.Threading.Tasks; -using Xtensive.Collections; -using Xtensive.Core; namespace Xtensive.Core @@ -19,14 +17,13 @@ namespace Xtensive.Core /// /// Provides exception aggregation support. /// - [Serializable] public class ExceptionAggregator : IDisposable, IEnumerable { + private readonly string exceptionMessage; private Action exceptionHandler; private List exceptions; - private string exceptionMessage; private bool isCompleted = false; private bool isDisposed = false; @@ -37,17 +34,18 @@ public class ExceptionAggregator : public Action ExceptionHandler { [DebuggerStepThrough] - get { return exceptionHandler; } + get => exceptionHandler; [DebuggerStepThrough] - set { exceptionHandler = value; } + set => exceptionHandler = value; } /// /// Gets the number of caught exceptions. /// - public int Count { + public int Count + { [DebuggerStepThrough] - get { return exceptions!=null ? exceptions.Count : 0; } + get => exceptions != null ? exceptions.Count : 0; } /// @@ -55,9 +53,10 @@ public int Count { /// i.e. aggregated exceptions, if any, can be thrown on disposal. /// Set to by method call. /// - public bool IsCompleted { + public bool IsCompleted + { [DebuggerStepThrough] - get { return isCompleted; } + get => isCompleted; } /// @@ -87,7 +86,7 @@ public void Add(Exception exception, bool handle) private void InnerAdd(Exception exception) { - if (exceptions==null) + if (exceptions is null) exceptions = new List(); exceptions.Add(exception); } @@ -343,7 +342,7 @@ public IEnumerator GetEnumerator() /// protected virtual void HandleException(Exception exception) { - if (exceptionHandler!=null) + if (exceptionHandler is not null) exceptionHandler(exception); InnerAdd(exception); } diff --git a/Orm/Xtensive.Orm/Core/Exceptions/ActivationException.cs b/Orm/Xtensive.Orm/Core/Exceptions/ActivationException.cs index 12a737343f..1736219736 100644 --- a/Orm/Xtensive.Orm/Core/Exceptions/ActivationException.cs +++ b/Orm/Xtensive.Orm/Core/Exceptions/ActivationException.cs @@ -5,8 +5,6 @@ // Created: 2010.01.30 using System; -using System.Runtime.Serialization; - using Xtensive.IoC; namespace Xtensive.Core @@ -14,8 +12,7 @@ namespace Xtensive.Core /// /// Thrown by on activation errors. /// - [Serializable] - public class ActivationException : Exception + public sealed class ActivationException : Exception { /// /// Initializes new instance of this type. @@ -42,18 +39,5 @@ public ActivationException(string message, Exception innerException) : base(message, innerException) { } - - /// - /// Deserializes instance of this type. - /// - /// - /// -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - protected ActivationException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Core/Exceptions/AggregateException.cs b/Orm/Xtensive.Orm/Core/Exceptions/AggregateException.cs index 81f57ee770..fe3f98cfd2 100644 --- a/Orm/Xtensive.Orm/Core/Exceptions/AggregateException.cs +++ b/Orm/Xtensive.Orm/Core/Exceptions/AggregateException.cs @@ -7,8 +7,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Runtime.Serialization; -using System.Security; using System.Text; using System.Linq; @@ -17,18 +15,15 @@ namespace Xtensive.Core /// /// Aggregates a set of caught exceptions. /// - [Serializable] public class AggregateException : Exception { - private Exception[] exceptions; - /// /// Gets the list of caught exceptions. /// public IReadOnlyList Exceptions { [DebuggerStepThrough] - get { return exceptions; } + get; } /// @@ -41,9 +36,8 @@ public List GetFlatExceptions() { var result = new List(); - foreach (var exception in exceptions) { - var ae = exception as AggregateException; - if (ae!=null) + foreach (var exception in Exceptions) { + if (exception is AggregateException ae) result.AddRange(ae.GetFlatExceptions()); else result.Add(exception); @@ -55,30 +49,16 @@ public List GetFlatExceptions() /// public override string ToString() { - StringBuilder sb = new StringBuilder(64); - _ = sb.Append(base.ToString()) + var sb = new StringBuilder(64) + .Append(base.ToString()) .AppendLine() .AppendFormat($"{Strings.OriginalExceptions}:"); int i = 1; - foreach (Exception exception in exceptions) + foreach (var exception in Exceptions) _ = sb.AppendLine().AppendFormat($"{i++}: {exception}"); return sb.ToString(); } - #region Private \ internal methods - - private void SetExceptions(Exception[] exceptions) - { - this.exceptions = exceptions; - } - - private void SetExceptions(Exception exception) - { - exceptions = new Exception[] { exception }; - } - - #endregion - // Constructors @@ -107,7 +87,7 @@ public AggregateException(string text) public AggregateException(string message, Exception innerException) : base(message, innerException) { - SetExceptions(innerException); + Exceptions = new[] { innerException }; } /// @@ -117,7 +97,7 @@ public AggregateException(string message, Exception innerException) public AggregateException(Exception[] exceptions) : base(Strings.ExASetOfExceptionsIsCaught, exceptions.First()) { - SetExceptions(exceptions); + Exceptions = exceptions; } /// @@ -128,39 +108,7 @@ public AggregateException(Exception[] exceptions) public AggregateException(string message, Exception[] exceptions) : base(message, exceptions.First()) { - SetExceptions(exceptions); - } - - - // Serialization - - /// - /// Deserializes instance of this type. - /// - /// - /// -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - protected AggregateException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - exceptions = (Exception[]) info.GetValue("Exceptions", typeof (Exception[])); - } - - /// - /// Serializes instance of this type. - /// - /// - /// - [SecurityCritical] -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddValue("Exceptions", exceptions); + Exceptions = exceptions; } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Core/Exceptions/InstanceIsLockedException.cs b/Orm/Xtensive.Orm/Core/Exceptions/InstanceIsLockedException.cs index 17f8ec1645..5f77eb4623 100644 --- a/Orm/Xtensive.Orm/Core/Exceptions/InstanceIsLockedException.cs +++ b/Orm/Xtensive.Orm/Core/Exceptions/InstanceIsLockedException.cs @@ -5,8 +5,6 @@ // Created: 2007.06.08 using System; -using System.Runtime.Serialization; - namespace Xtensive.Core @@ -15,8 +13,7 @@ namespace Xtensive.Core /// Thrown by implementors on attempts /// to change instance properties in the locked state. /// - [Serializable] - public class InstanceIsLockedException : InvalidOperationException + public sealed class InstanceIsLockedException : InvalidOperationException { /// /// Initializes a new instance of this type. @@ -34,18 +31,5 @@ public InstanceIsLockedException(string text) : base(text) { } - - /// - /// Deserialization constructor. - /// - /// object. - /// object. -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - protected InstanceIsLockedException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Core/Extensions/ExpressionExtensions.cs b/Orm/Xtensive.Orm/Core/Extensions/ExpressionExtensions.cs index 23e2a8fa30..18c531d4f1 100644 --- a/Orm/Xtensive.Orm/Core/Extensions/ExpressionExtensions.cs +++ b/Orm/Xtensive.Orm/Core/Extensions/ExpressionExtensions.cs @@ -1,19 +1,16 @@ -// Copyright (C) 2009-2023 Xtensive LLC. +// Copyright (C) 2009-2026 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Alexis Kochetov // Created: 2009.04.21 using System; +using System.Collections.Concurrent; using System.Linq.Expressions; using System.Reflection; using Xtensive.Linq; -using Xtensive.Linq.SerializableExpressions; -using Xtensive.Linq.SerializableExpressions.Internals; - -using System.Linq; using Xtensive.Reflection; -using System.Collections.Concurrent; + namespace Xtensive.Core { @@ -95,26 +92,6 @@ public static Expression BindParameters(this LambdaExpression lambdaExpression, lambdaExpression.Body, lambdaExpression.Parameters, convertedParameters); } - /// - /// Converts specified to . - /// - /// The expression to convert. - /// Serializable expression that represents . - public static SerializableExpression ToSerializableExpression(this Expression expression) - { - return new ExpressionToSerializableExpressionConverter(expression).Convert(); - } - - /// - /// Converts specified to . - /// - /// The expression to convert. - /// Expression that represents given . - public static Expression ToExpression(this SerializableExpression expression) - { - return new SerializableExpressionToExpressionConverter(expression).Convert(); - } - /// /// Converts to /// with value of default value of type in the . diff --git a/Orm/Xtensive.Orm/Core/HasVersion{TValue,TVersion}.cs b/Orm/Xtensive.Orm/Core/HasVersion{TValue,TVersion}.cs index 630107db85..26dba51164 100644 --- a/Orm/Xtensive.Orm/Core/HasVersion{TValue,TVersion}.cs +++ b/Orm/Xtensive.Orm/Core/HasVersion{TValue,TVersion}.cs @@ -17,7 +17,6 @@ namespace Xtensive.Core /// /// The of . /// The of . - [Serializable] [DebuggerDisplay("{Value}, Version = {Version}")] public struct HasVersion : IComparable>, diff --git a/Orm/Xtensive.Orm/Core/InheritableScope.cs b/Orm/Xtensive.Orm/Core/InheritableScope.cs index 3e5ca969be..66f76e0814 100644 --- a/Orm/Xtensive.Orm/Core/InheritableScope.cs +++ b/Orm/Xtensive.Orm/Core/InheritableScope.cs @@ -16,7 +16,6 @@ namespace Xtensive.Core /// /// The type of the context. /// The type of the very base ancestor. - [Serializable] public class InheritableScope : Scope where TContext : class where TBaseAncestor: Scope @@ -54,9 +53,11 @@ protected internal InheritableScope() static InheritableScope() { var ancestorType = typeof(TBaseAncestor); - if (allowedType==null) lock (@lock) if (allowedType==null) - allowedType = ancestorType; - if (allowedType!=ancestorType) + if (allowedType is null) + lock (@lock) + if (allowedType is null) + allowedType = ancestorType; + if (allowedType != ancestorType) throw new SecurityException( Strings.ExOnlyOneAncestorOfEachInstanceOfThisGenericTypeIsAllowed); } diff --git a/Orm/Xtensive.Orm/Core/JoiningDisposable.cs b/Orm/Xtensive.Orm/Core/JoiningDisposable.cs index 9304c86c23..aecc813846 100644 --- a/Orm/Xtensive.Orm/Core/JoiningDisposable.cs +++ b/Orm/Xtensive.Orm/Core/JoiningDisposable.cs @@ -14,7 +14,6 @@ namespace Xtensive.Core /// /// Disposes two objects. /// - [Serializable] public sealed class JoiningDisposable : IDisposable { private IDisposable first; @@ -23,16 +22,12 @@ public sealed class JoiningDisposable : IDisposable /// /// Gets the first object to dispose. /// - public IDisposable First { - get { return first; } - } + public IDisposable First => first; /// /// Gets the second object to dispose. /// - public IDisposable Second { - get { return second; } - } + public IDisposable Second => second; /// /// Joins the and . @@ -43,7 +38,7 @@ public IDisposable Second { /// dispose both of them on its disposal public static JoiningDisposable operator &(JoiningDisposable first, IDisposable second) { - if (second==null) + if (second is null) return first; return new JoiningDisposable(first, second); } diff --git a/Orm/Xtensive.Orm/Core/LockableBase.cs b/Orm/Xtensive.Orm/Core/LockableBase.cs index 48cb59a6d9..badefdf687 100644 --- a/Orm/Xtensive.Orm/Core/LockableBase.cs +++ b/Orm/Xtensive.Orm/Core/LockableBase.cs @@ -13,12 +13,11 @@ namespace Xtensive.Core /// /// Base class for implementors. /// - [Serializable] public abstract class LockableBase: ILockable { /// - public bool IsLocked { [DebuggerStepThrough] get; private set; } + public bool IsLocked { get; private set; } /// /// Ensures the object is not locked (see ) yet. diff --git a/Orm/Xtensive.Orm/Core/MatchType.cs b/Orm/Xtensive.Orm/Core/MatchType.cs index 3d8d09bc2d..ba6e2cd8ba 100644 --- a/Orm/Xtensive.Orm/Core/MatchType.cs +++ b/Orm/Xtensive.Orm/Core/MatchType.cs @@ -11,7 +11,6 @@ namespace Xtensive.Core /// /// Possible types of match to look for. /// - [Serializable] public enum MatchType { None = 0, diff --git a/Orm/Xtensive.Orm/Core/MethodCacheBase.cs b/Orm/Xtensive.Orm/Core/MethodCacheBase.cs index 6506dd2e32..e9a1e0ab6a 100644 --- a/Orm/Xtensive.Orm/Core/MethodCacheBase.cs +++ b/Orm/Xtensive.Orm/Core/MethodCacheBase.cs @@ -5,9 +5,6 @@ // Created: 2008.02.10 using System; -using System.Runtime.Serialization; -using System.Security; -using System.Security.Permissions; namespace Xtensive.Core @@ -16,8 +13,7 @@ namespace Xtensive.Core /// Base class for any method caching class. /// /// The type of . - [Serializable] - public abstract class MethodCacheBase: ISerializable + public abstract class MethodCacheBase where TImplementation: class { /// @@ -36,26 +32,5 @@ public MethodCacheBase(TImplementation implementation) { Implementation = implementation; } - - /// - /// Deserializes instance of this type. - /// - /// - /// - protected MethodCacheBase(SerializationInfo info, StreamingContext context) - { - Implementation = (TImplementation) info.GetValue("Implementation", typeof(TImplementation)); - } - - /// - /// Serializes instance of this type. - /// - /// - /// - [SecurityCritical] - public virtual void GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue("Implementation", Implementation, Implementation.GetType()); - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Core/Pair{TFirst,TSecond}.cs b/Orm/Xtensive.Orm/Core/Pair{TFirst,TSecond}.cs index af240475fb..b5b4b11458 100644 --- a/Orm/Xtensive.Orm/Core/Pair{TFirst,TSecond}.cs +++ b/Orm/Xtensive.Orm/Core/Pair{TFirst,TSecond}.cs @@ -15,7 +15,6 @@ namespace Xtensive.Core /// /// The of first value. /// The of second value. - [Serializable] [DebuggerDisplay("{First}, {Second}")] public readonly struct Pair : IComparable>, diff --git a/Orm/Xtensive.Orm/Core/Pair{T}.cs b/Orm/Xtensive.Orm/Core/Pair{T}.cs index 96a40c8524..d2219204d7 100644 --- a/Orm/Xtensive.Orm/Core/Pair{T}.cs +++ b/Orm/Xtensive.Orm/Core/Pair{T}.cs @@ -16,7 +16,6 @@ namespace Xtensive.Core /// A pair of two values of the same type. /// /// The type of both stored values. - [Serializable] [DebuggerDisplay("{First}, {Second}")] public readonly struct Pair : IEquatable>, diff --git a/Orm/Xtensive.Orm/Core/Segment.cs b/Orm/Xtensive.Orm/Core/Segment.cs index b2e976f257..bc01e1b554 100644 --- a/Orm/Xtensive.Orm/Core/Segment.cs +++ b/Orm/Xtensive.Orm/Core/Segment.cs @@ -17,7 +17,6 @@ namespace Xtensive.Core /// A definition of segment with boundaries of type . /// /// The type of segment boundaries. - [Serializable] [DebuggerDisplay("Offset = {Offset}, Length = {Length}")] public readonly struct Segment { @@ -36,11 +35,10 @@ public readonly struct Segment /// /// Gets + value. /// - public T EndOffset { + public T EndOffset + { [DebuggerStepThrough] - get { - return arithmetic.Add(Offset, Length); - } + get => arithmetic.Add(Offset, Length); } /// @@ -100,10 +98,7 @@ public override int GetHashCode() } /// - public override string ToString() - { - return string.Format(Strings.SegmentFormat, Offset, Length); - } + public override string ToString() => string.Format(Strings.SegmentFormat, Offset, Length); // Constructors diff --git a/Orm/Xtensive.Orm/IoC/Attributes/ServiceAttribute.cs b/Orm/Xtensive.Orm/IoC/Attributes/ServiceAttribute.cs index 8298e9f602..da349c8207 100644 --- a/Orm/Xtensive.Orm/IoC/Attributes/ServiceAttribute.cs +++ b/Orm/Xtensive.Orm/IoC/Attributes/ServiceAttribute.cs @@ -12,11 +12,9 @@ namespace Xtensive.IoC /// /// An attribute describing mapping of service implementation to service. /// - [Serializable] [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] public sealed class ServiceAttribute : Attribute { - private bool singleton = true; /// /// Gets or sets the type of the service. @@ -32,17 +30,13 @@ public sealed class ServiceAttribute : Attribute /// Gets or sets a value indicating whether this service is singleton. /// Default value is . /// - public bool Singleton - { - get { return singleton; } - set { singleton = value; } - } + public bool Singleton { get; set; } = true; /// /// Gets or sets a value indicating whether this is default service implementation or not. /// Default value is . /// - public bool Default { get; set; } + public bool Default { get; set; } = false; // Constructors diff --git a/Orm/Xtensive.Orm/IoC/Attributes/ServiceConstructorAttribute.cs b/Orm/Xtensive.Orm/IoC/Attributes/ServiceConstructorAttribute.cs index bb9cde2208..6189f52c6d 100644 --- a/Orm/Xtensive.Orm/IoC/Attributes/ServiceConstructorAttribute.cs +++ b/Orm/Xtensive.Orm/IoC/Attributes/ServiceConstructorAttribute.cs @@ -12,7 +12,6 @@ namespace Xtensive.IoC /// /// An attribute tagging default service constructor to use. /// - [Serializable] [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)] public sealed class ServiceConstructorAttribute : Attribute { diff --git a/Orm/Xtensive.Orm/IoC/Configuration/ContainerElement.cs b/Orm/Xtensive.Orm/IoC/Configuration/ContainerElement.cs index bb48be5535..9718b53c4f 100644 --- a/Orm/Xtensive.Orm/IoC/Configuration/ContainerElement.cs +++ b/Orm/Xtensive.Orm/IoC/Configuration/ContainerElement.cs @@ -14,7 +14,6 @@ namespace Xtensive.IoC.Configuration /// /// IoC container configuration element. /// - [Serializable] public class ContainerElement : ConfigurationCollectionElementBase { private const string NameElementName = "name"; @@ -33,27 +32,30 @@ public override object Identifier /// Gets or sets the name of the container. /// [ConfigurationProperty(NameElementName, IsRequired = false, DefaultValue = null)] - public string Name { - get { return (string) this[NameElementName]; } - set { this[NameElementName] = value; } + public string Name + { + get => (string) this[NameElementName]; + set => this[NameElementName] = value; } /// /// Gets or sets the type of the container. /// [ConfigurationProperty(TypeElementName, IsRequired = false, DefaultValue = null)] - public string Type { - get { return (string) this[TypeElementName]; } - set { this[TypeElementName] = value; } + public string Type + { + get => (string) this[TypeElementName]; + set => this[TypeElementName] = value; } /// /// Gets or sets the name of the parent container. /// [ConfigurationProperty(ParentElementName, IsRequired = false, DefaultValue = null)] - public string Parent { - get { return (string) this[ParentElementName]; } - set { this[ParentElementName] = value; } + public string Parent + { + get => (string) this[ParentElementName]; + set => this[ParentElementName] = value; } /// @@ -61,11 +63,8 @@ public string Parent { /// [ConfigurationProperty(ExplicitElementName, IsRequired = false, IsDefaultCollection = true)] [ConfigurationCollection(typeof(ConfigurationCollection), AddItemName = "add")] - public ConfigurationCollection Explicit { - get { - return (ConfigurationCollection) base[ExplicitElementName]; - } - } + public ConfigurationCollection Explicit + => (ConfigurationCollection) base[ExplicitElementName]; /// /// Gets the automatic . @@ -73,8 +72,7 @@ public ConfigurationCollection Explicit { /// The types. [ConfigurationProperty(AutoElementName, IsRequired = false, IsDefaultCollection = false)] [ConfigurationCollection(typeof (ConfigurationCollection), AddItemName = "add")] - public ConfigurationCollection Auto { - get { return (ConfigurationCollection) base[AutoElementName]; } - } + public ConfigurationCollection Auto + => (ConfigurationCollection) base[AutoElementName]; } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/IoC/ServiceContainer.cs b/Orm/Xtensive.Orm/IoC/ServiceContainer.cs index 02b2ee953e..896dce7da7 100644 --- a/Orm/Xtensive.Orm/IoC/ServiceContainer.cs +++ b/Orm/Xtensive.Orm/IoC/ServiceContainer.cs @@ -24,7 +24,6 @@ namespace Xtensive.IoC /// /// Default IoC (inversion of control) container implementation. /// - [Serializable] public class ServiceContainer : ServiceContainerBase { private static readonly Type iServiceContainerType = typeof(IServiceContainer); @@ -79,7 +78,7 @@ protected virtual object CreateInstance(ServiceRegistration serviceInfo) { var cachedInfo = constructorCache.GetOrAdd(serviceInfo, ConstructorFactory); var cInfo = cachedInfo.First; - if (cInfo == null) { + if (cInfo is null) { return null; } var pInfos = cachedInfo.Second; diff --git a/Orm/Xtensive.Orm/IoC/ServiceRegistration.cs b/Orm/Xtensive.Orm/IoC/ServiceRegistration.cs index 6ca671debf..90678da7a2 100644 --- a/Orm/Xtensive.Orm/IoC/ServiceRegistration.cs +++ b/Orm/Xtensive.Orm/IoC/ServiceRegistration.cs @@ -16,7 +16,6 @@ namespace Xtensive.IoC /// /// Describes single service mapping entry for . /// - [Serializable] public sealed class ServiceRegistration { private static readonly ConcurrentDictionary> serviceRegistrationsByType = @@ -27,27 +26,27 @@ public sealed class ServiceRegistration /// /// Gets the type of the service. /// - public Type Type { get; private set; } + public Type Type { get; } /// /// Gets the name of the service. /// - public string Name { get; private set; } + public string Name { get; } /// /// Gets the type it is mapped to. /// - public Type MappedType { get; private set; } + public Type MappedType { get; } /// /// Gets the instance it is mapped to. /// - public object MappedInstance { get; private set; } + public object MappedInstance { get; } /// /// Gets a value indicating whether this service is singleton. /// - public bool Singleton { get; private set; } + public bool Singleton { get; } // Static constructor-like methods diff --git a/Orm/Xtensive.Orm/Linq/Internals/ExpressionComparer.cs b/Orm/Xtensive.Orm/Linq/Internals/ExpressionComparer.cs index 23c597ae1a..42543624b8 100644 --- a/Orm/Xtensive.Orm/Linq/Internals/ExpressionComparer.cs +++ b/Orm/Xtensive.Orm/Linq/Internals/ExpressionComparer.cs @@ -35,85 +35,85 @@ private bool Visit(Expression x, Expression y) { if (ReferenceEquals(x, y)) return true; - if (x==null || y==null) + if (x == null || y == null) return false; - if (x.NodeType!=y.NodeType) + if (x.NodeType != y.NodeType) return false; - if (x.Type!=y.Type) + if (x.Type != y.Type) return false; switch (x.NodeType) { - case ExpressionType.Negate: - case ExpressionType.NegateChecked: - case ExpressionType.Not: - case ExpressionType.Convert: - case ExpressionType.ConvertChecked: - case ExpressionType.ArrayLength: - case ExpressionType.Quote: - case ExpressionType.TypeAs: - case ExpressionType.Decrement: - case ExpressionType.Increment: - case ExpressionType.IsFalse: - case ExpressionType.IsTrue: - case ExpressionType.OnesComplement: - return VisitUnary((UnaryExpression) x, (UnaryExpression) y); - case ExpressionType.Add: - case ExpressionType.AddChecked: - case ExpressionType.Subtract: - case ExpressionType.SubtractChecked: - case ExpressionType.Multiply: - case ExpressionType.MultiplyChecked: - case ExpressionType.Divide: - case ExpressionType.Modulo: - case ExpressionType.And: - case ExpressionType.AndAlso: - case ExpressionType.Or: - case ExpressionType.OrElse: - case ExpressionType.LessThan: - case ExpressionType.LessThanOrEqual: - case ExpressionType.GreaterThan: - case ExpressionType.GreaterThanOrEqual: - case ExpressionType.Equal: - case ExpressionType.NotEqual: - case ExpressionType.Coalesce: - case ExpressionType.ArrayIndex: - case ExpressionType.RightShift: - case ExpressionType.LeftShift: - case ExpressionType.ExclusiveOr: - case ExpressionType.Power: - case ExpressionType.Assign: - return VisitBinary((BinaryExpression) x, (BinaryExpression) y); - case ExpressionType.TypeIs: - return VisitTypeIs((TypeBinaryExpression) x, (TypeBinaryExpression) y); - case ExpressionType.TypeEqual: - return VisitTypeEqual((TypeBinaryExpression) x, (TypeBinaryExpression) y); - case ExpressionType.Conditional: - return VisitConditional((ConditionalExpression) x, (ConditionalExpression) y); - case ExpressionType.Constant: - return VisitConstant((ConstantExpression) x, (ConstantExpression) y); - case ExpressionType.Default: - return true; // types and references are already compared - case ExpressionType.Parameter: - return VisitParameter((ParameterExpression) x, (ParameterExpression) y); - case ExpressionType.MemberAccess: - return VisitMemberAccess((MemberExpression) x, (MemberExpression) y); - case ExpressionType.Call: - return VisitMethodCall((MethodCallExpression) x, (MethodCallExpression) y); - case ExpressionType.Lambda: - return VisitLambda((LambdaExpression) x, (LambdaExpression) y); - case ExpressionType.New: - return VisitNew((NewExpression) x, (NewExpression) y); - case ExpressionType.NewArrayInit: - case ExpressionType.NewArrayBounds: - return VisitNewArray((NewArrayExpression) x, (NewArrayExpression) y); - case ExpressionType.Invoke: - return VisitInvocation((InvocationExpression) x, (InvocationExpression) y); - case ExpressionType.MemberInit: - return VisitMemberInit((MemberInitExpression) x, (MemberInitExpression) y); - case ExpressionType.ListInit: - return VisitListInit((ListInitExpression) x, (ListInitExpression) y); - default: - return x.Equals(y); + case ExpressionType.Negate: + case ExpressionType.NegateChecked: + case ExpressionType.Not: + case ExpressionType.Convert: + case ExpressionType.ConvertChecked: + case ExpressionType.ArrayLength: + case ExpressionType.Quote: + case ExpressionType.TypeAs: + case ExpressionType.Decrement: + case ExpressionType.Increment: + case ExpressionType.IsFalse: + case ExpressionType.IsTrue: + case ExpressionType.OnesComplement: + return VisitUnary((UnaryExpression) x, (UnaryExpression) y); + case ExpressionType.Add: + case ExpressionType.AddChecked: + case ExpressionType.Subtract: + case ExpressionType.SubtractChecked: + case ExpressionType.Multiply: + case ExpressionType.MultiplyChecked: + case ExpressionType.Divide: + case ExpressionType.Modulo: + case ExpressionType.And: + case ExpressionType.AndAlso: + case ExpressionType.Or: + case ExpressionType.OrElse: + case ExpressionType.LessThan: + case ExpressionType.LessThanOrEqual: + case ExpressionType.GreaterThan: + case ExpressionType.GreaterThanOrEqual: + case ExpressionType.Equal: + case ExpressionType.NotEqual: + case ExpressionType.Coalesce: + case ExpressionType.ArrayIndex: + case ExpressionType.RightShift: + case ExpressionType.LeftShift: + case ExpressionType.ExclusiveOr: + case ExpressionType.Power: + case ExpressionType.Assign: + return VisitBinary((BinaryExpression) x, (BinaryExpression) y); + case ExpressionType.TypeIs: + return VisitTypeIs((TypeBinaryExpression) x, (TypeBinaryExpression) y); + case ExpressionType.TypeEqual: + return VisitTypeEqual((TypeBinaryExpression) x, (TypeBinaryExpression) y); + case ExpressionType.Conditional: + return VisitConditional((ConditionalExpression) x, (ConditionalExpression) y); + case ExpressionType.Constant: + return VisitConstant((ConstantExpression) x, (ConstantExpression) y); + case ExpressionType.Default: + return VisitDefault((DefaultExpression) x, (DefaultExpression) y); + case ExpressionType.Parameter: + return VisitParameter((ParameterExpression) x, (ParameterExpression) y); + case ExpressionType.MemberAccess: + return VisitMemberAccess((MemberExpression) x, (MemberExpression) y); + case ExpressionType.Call: + return VisitMethodCall((MethodCallExpression) x, (MethodCallExpression) y); + case ExpressionType.Lambda: + return VisitLambda((LambdaExpression) x, (LambdaExpression) y); + case ExpressionType.New: + return VisitNew((NewExpression) x, (NewExpression) y); + case ExpressionType.NewArrayInit: + case ExpressionType.NewArrayBounds: + return VisitNewArray((NewArrayExpression) x, (NewArrayExpression) y); + case ExpressionType.Invoke: + return VisitInvocation((InvocationExpression) x, (InvocationExpression) y); + case ExpressionType.MemberInit: + return VisitMemberInit((MemberInitExpression) x, (MemberInitExpression) y); + case ExpressionType.ListInit: + return VisitListInit((ListInitExpression) x, (ListInitExpression) y); + default: + return x.Equals(y); } } @@ -210,7 +210,9 @@ private bool VisitLambda(LambdaExpression x, LambdaExpression y) { leftParameters.AddRange(x.Parameters); rightParameters.AddRange(y.Parameters); - return CompareExpressionSequences(x.Parameters, y.Parameters) && Visit(x.Body, y.Body); + var areParametersEqual = CompareExpressionSequences(x.Parameters, y.Parameters); + var areBodiesEqual = Visit(x.Body, y.Body); + return areParametersEqual && areBodiesEqual; } private bool VisitMethodCall(MethodCallExpression x, MethodCallExpression y) @@ -237,6 +239,15 @@ private bool VisitConstant(ConstantExpression x, ConstantExpression y) return x.Value.Equals(y.Value); } + private bool VisitDefault(DefaultExpression x, DefaultExpression y) + { + if (ReferenceEquals(x, y)) + return true; + if (ReferenceEquals(x.Type, y.Type)) + return true; + return false; + } + private bool VisitConditional(ConditionalExpression x, ConditionalExpression y) { return Visit(x.Test, y.Test) && Visit(x.IfTrue, y.IfTrue) && Visit(x.IfFalse, y.IfFalse); diff --git a/Orm/Xtensive.Orm/Linq/QueryableMethodKind.cs b/Orm/Xtensive.Orm/Linq/QueryableMethodKind.cs index 806e6ec2e7..a596ec9542 100644 --- a/Orm/Xtensive.Orm/Linq/QueryableMethodKind.cs +++ b/Orm/Xtensive.Orm/Linq/QueryableMethodKind.cs @@ -12,7 +12,6 @@ namespace Xtensive.Linq /// /// Enumerates supported methods. /// - [Serializable] public enum QueryableMethodKind { #pragma warning disable 1591 diff --git a/Orm/Xtensive.Orm/Linq/QueryableVisitor.cs b/Orm/Xtensive.Orm/Linq/QueryableVisitor.cs index 726077af1b..06f1ff372f 100644 --- a/Orm/Xtensive.Orm/Linq/QueryableVisitor.cs +++ b/Orm/Xtensive.Orm/Linq/QueryableVisitor.cs @@ -15,7 +15,6 @@ namespace Xtensive.Linq /// /// Abstract base visitor that handles methods of and by calling . /// - [Serializable] public abstract class QueryableVisitor : ExpressionVisitor { /// @@ -26,7 +25,7 @@ protected override Expression VisitMethodCall(MethodCallExpression mc) } var method = GetQueryableMethod(mc); - if (method == null) { + if (method is null) { return base.VisitMethodCall(mc); } diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/Internals/ExpressionToSerializableExpressionConverter.cs b/Orm/Xtensive.Orm/Linq/SerializableExpressions/Internals/ExpressionToSerializableExpressionConverter.cs deleted file mode 100644 index fa2bf0b2ed..0000000000 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/Internals/ExpressionToSerializableExpressionConverter.cs +++ /dev/null @@ -1,247 +0,0 @@ -// Copyright (C) 2009-2023 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Denis Kryuchkov -// Created: 2009.05.13 - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using Xtensive.Core; - -namespace Xtensive.Linq.SerializableExpressions.Internals -{ - internal sealed class ExpressionToSerializableExpressionConverter - : ExpressionVisitor - { - private readonly Expression source; - - public SerializableExpression Convert() - { - return Visit(source); - } - - #region ExpressionVisitor - - protected override SerializableUnaryExpression VisitUnary(UnaryExpression u) - { - return new SerializableUnaryExpression - { - NodeType = u.NodeType, - Type = u.Type, - Method = u.Method, - Operand = Visit(u.Operand) - }; - } - - protected override SerializableBinaryExpression VisitBinary(BinaryExpression b) - { - return new SerializableBinaryExpression - { - NodeType = b.NodeType, - Type = b.Type, - Method = b.Method, - IsLiftedToNull = b.IsLiftedToNull, - Left = Visit(b.Left), - Right = Visit(b.Right) - }; - } - - protected override SerializableTypeBinaryExpression VisitTypeIs(TypeBinaryExpression tb) - { - return new SerializableTypeBinaryExpression - { - NodeType = tb.NodeType, - Type = tb.Type, - Expression = Visit(tb.Expression), - TypeOperand = tb.TypeOperand - }; - } - - protected override SerializableConstantExpression VisitConstant(ConstantExpression c) - { - return new SerializableConstantExpression - { - NodeType = c.NodeType, - Type = c.Type, - Value = c.Value - }; - } - - protected override SerializableDefaultExpression VisitDefault(DefaultExpression d) - { - return new SerializableDefaultExpression { - NodeType = d.NodeType, - Type = d.Type - }; - } - - protected override SerializableConditionalExpression VisitConditional(ConditionalExpression c) - { - return new SerializableConditionalExpression - { - NodeType = c.NodeType, - Type = c.Type, - Test = Visit(c.Test), - IfTrue = Visit(c.IfTrue), - IfFalse = Visit(c.IfFalse) - }; - } - - protected override SerializableParameterExpression VisitParameter(ParameterExpression p) - { - return new SerializableParameterExpression - { - NodeType = p.NodeType, - Type = p.Type, - Name = p.Name - }; - } - - protected override SerializableMemberExpression VisitMemberAccess(MemberExpression m) - { - return new SerializableMemberExpression - { - NodeType = m.NodeType, - Type = m.Type, - Expression = Visit(m.Expression), - Member = m.Member - }; - } - - protected override SerializableMethodCallExpression VisitMethodCall(MethodCallExpression mc) - { - return new SerializableMethodCallExpression - { - NodeType = mc.NodeType, - Type = mc.Type, - Method = mc.Method, - Arguments = VisitExpressionSequence(mc.Arguments), - Object = Visit(mc.Object) - }; - } - - protected override SerializableLambdaExpression VisitLambda(LambdaExpression l) - { - return new SerializableLambdaExpression - { - NodeType = l.NodeType, - Type = l.Type, - Body = Visit(l.Body), - Parameters = l.Parameters.Select(p => (SerializableParameterExpression) Visit(p)).ToArraySafely() - }; - } - - protected override SerializableNewExpression VisitNew(NewExpression n) - { - return new SerializableNewExpression - { - NodeType = n.NodeType, - Type = n.Type, - Constructor = n.Constructor, - Arguments = VisitExpressionSequence(n.Arguments), - Members = n.Members.ToArraySafely() - }; - } - - protected override SerializableMemberInitExpression VisitMemberInit(MemberInitExpression mi) - { - return new SerializableMemberInitExpression - { - NodeType = mi.NodeType, - Type = mi.Type, - Bindings = VisitMemberBindingSequence(mi.Bindings), - NewExpression = (SerializableNewExpression) Visit(mi.NewExpression) - }; - } - - protected override SerializableListInitExpression VisitListInit(ListInitExpression li) - { - return new SerializableListInitExpression - { - NodeType = li.NodeType, - Type = li.Type, - NewExpression = (SerializableNewExpression) Visit(li.NewExpression), - Initializers = VisitElementInitSequence(li.Initializers) - }; - } - - protected override SerializableNewArrayExpression VisitNewArray(NewArrayExpression na) - { - return new SerializableNewArrayExpression - { - NodeType = na.NodeType, - Type = na.Type, - Expressions = VisitExpressionSequence(na.Expressions) - }; - } - - protected override SerializableInvocationExpression VisitInvocation(InvocationExpression i) - { - return new SerializableInvocationExpression - { - NodeType = i.NodeType, - Type = i.Type, - Arguments = VisitExpressionSequence(i.Arguments), - Expression = Visit(i.Expression) - }; - } - - #endregion - - #region Private / internal methods - - private SerializableMemberBinding[] VisitMemberBindingSequence(IReadOnlyList bindings) - { - var arrayResult = new SerializableMemberBinding[bindings.Count]; - for (int i = 0, count = bindings.Count; i < count; i++) { - var binding = bindings[i]; - arrayResult[i] = binding.BindingType switch { - MemberBindingType.Assignment => new SerializableMemberAssignment() { - BindingType = MemberBindingType.Assignment, - Member = binding.Member, - Expression = Visit(((MemberAssignment) binding).Expression) - }, - MemberBindingType.ListBinding => new SerializableMemberListBinding { - BindingType = MemberBindingType.ListBinding, - Member = binding.Member, - Initializers = VisitElementInitSequence(((MemberListBinding) binding).Initializers) - }, - MemberBindingType.MemberBinding => new SerializableMemberMemberBinding { - BindingType = MemberBindingType.MemberBinding, - Member = binding.Member, - Bindings = VisitMemberBindingSequence(((MemberMemberBinding) binding).Bindings) - }, - _ => throw new ArgumentOutOfRangeException() - - }; - } - return arrayResult; - } - - private SerializableElementInit[] VisitElementInitSequence(IList initializers) - { - return initializers - .SelectToArray(initializer => new SerializableElementInit - { - AddMethod = initializer.AddMethod, - Arguments = VisitExpressionSequence(initializer.Arguments) - }); - } - - private SerializableExpression[] VisitExpressionSequence(IList expressions) - where T : Expression - { - return expressions.SelectToArray(e => Visit(e)); - } - - #endregion - - public ExpressionToSerializableExpressionConverter(Expression source) - : base(true) - { - this.source = source; - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/Internals/ReflectionExtensions.cs b/Orm/Xtensive.Orm/Linq/SerializableExpressions/Internals/ReflectionExtensions.cs deleted file mode 100644 index 5ea026f5b2..0000000000 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/Internals/ReflectionExtensions.cs +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright (C) 2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. -// Created by: Alexis Kochetov -// Created: 2010.02.25 - -using System; -using System.Linq; -using System.Reflection; -using System.Runtime.Serialization; -using Xtensive.Core; - -namespace Xtensive.Linq.SerializableExpressions.Internals -{ - internal static class ReflectionExtensions - { - public static string ToSerializableForm(this Type type) - => type?.AssemblyQualifiedName; - - public static Type GetTypeFromSerializableForm(this string serializedValue) - => serializedValue == null ? null : Type.GetType(serializedValue); - - public static string ToSerializableForm(this MethodInfo method) - { - if (method == null) - return null; - - var serializableName = method.DeclaringType.AssemblyQualifiedName + Environment.NewLine; - if (!method.IsGenericMethod) - serializableName += method.ToString(); - else - serializableName += method.GetGenericMethodDefinition() + Environment.NewLine + - string.Join(Environment.NewLine, - method.GetGenericArguments().Select(ty => ty.ToSerializableForm()).ToArray()); - return serializableName; - } - - public static MethodInfo GetMethodFromSerializableForm(this string serializedValue) - { - if (serializedValue == null) - return null; - - var fullName = SplitString(serializedValue); - var name = fullName[1]; - var type = Type.GetType(fullName[0]); - var publicMethods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); - var method = publicMethods.FirstOrDefault(m => m.ToString() == name); - if (method == null) { - var nonPublicMethods = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); - method = nonPublicMethods.First(m => m.ToString() == name); - } - - if (method.IsGenericMethod) - method = method.MakeGenericMethod(fullName.Skip(2).Select(s => GetTypeFromSerializableForm(s)).ToArray()); - return method; - } - - public static string ToSerializableForm(this MemberInfo member) - { - if (member == null) - return null; - - return member.DeclaringType.AssemblyQualifiedName + Environment.NewLine + member; - } - - public static MemberInfo GetMemberFromSerializableForm(this string serializedValue) - { - if (serializedValue == null) - return null; - - var fullName = SplitString(serializedValue); - var name = fullName[1]; - var type = Type.GetType(fullName[0]); - var publicMemberss = type.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); - var member = publicMemberss.FirstOrDefault(m => m.ToString() == name); - if (member == null) { - var nonPublicMembers = type.GetMembers(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); - member = nonPublicMembers.First(m => m.ToString() == name); - } - - return member; - } - - public static string ToSerializableForm(this ConstructorInfo obj) - { - if (obj == null) - return null; - return obj.DeclaringType.AssemblyQualifiedName + Environment.NewLine + obj; - } - - public static ConstructorInfo GetConstructorFromSerializableForm(this string serializedValue) - { - if (serializedValue == null) - return null; - var fullName = SplitString(serializedValue); - var name = fullName[1]; - var newObj = Type.GetType(fullName[0]).GetConstructors().First(m => m.ToString() == name); - return newObj; - } - - public static void AddArray(this SerializationInfo info, string key, T[] array) - { - ArgumentValidator.EnsureArgumentNotNullOrEmpty(key, nameof(key)); - ArgumentNullException.ThrowIfNull(array); - - info.AddValue($"{key}Count", array.Length); - for (int i = 0; i < array.Length; i++) - info.AddValue($"{key}_{i}", array[i]); - } - - public static T[] GetArrayFromSerializableForm(this SerializationInfo info, string key) - { - ArgumentValidator.EnsureArgumentNotNullOrEmpty(key, nameof(key)); - - var count = info.GetInt32($"{key}Count"); - var array = new T[count]; - for (int i = 0; i < count; i++) - array[i] = (T) info.GetValue($"{key}_{i}", typeof (T)); - - return array; - } - - private static string[] SplitString(string str) - { - return str.Split(str.Contains(Environment.NewLine) - ? new[] {Environment.NewLine} - : new[] {"\n"}, StringSplitOptions.None); - } - } -} diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableBinaryExpression.cs b/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableBinaryExpression.cs deleted file mode 100644 index cf68689ed5..0000000000 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableBinaryExpression.cs +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (C) 2009-2021 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Denis Krjuchkov -// Created: 2009.05.12 - -using System; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.Serialization; -using System.Security; -using Xtensive.Linq.SerializableExpressions.Internals; - -namespace Xtensive.Linq.SerializableExpressions -{ - /// - /// A serializable representation of . - /// - [Serializable] - public sealed class SerializableBinaryExpression : SerializableExpression - { - /// - /// - /// - public bool IsLiftedToNull; - /// - /// . - /// - public SerializableExpression Left; - /// - /// - /// - public SerializableExpression Right; - /// - /// - /// - public MethodInfo Method; - - [SecurityCritical] - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddValue("IsLiftedToNull", IsLiftedToNull); - info.AddValue("Left", Left); - info.AddValue("Right", Right); - info.AddValue("Method", Method.ToSerializableForm()); - } - - public SerializableBinaryExpression() - { - } - - public SerializableBinaryExpression(SerializationInfo info, StreamingContext context) - : base(info, context) - { - IsLiftedToNull = info.GetBoolean("IsLiftedToNull"); - Left = (SerializableExpression) info.GetValue("Left", typeof (SerializableExpression)); - Right = (SerializableExpression) info.GetValue("Right", typeof (SerializableExpression)); - Method = info.GetString("Method").GetMethodFromSerializableForm(); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableConditionalExpression.cs b/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableConditionalExpression.cs deleted file mode 100644 index 8b2d943090..0000000000 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableConditionalExpression.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (C) 2009-2021 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Denis Krjuchkov -// Created: 2009.05.12 - -using System; -using System.Linq.Expressions; -using System.Runtime.Serialization; -using System.Security; - -namespace Xtensive.Linq.SerializableExpressions -{ - /// - /// A serializable representation of . - /// - [Serializable] - public sealed class SerializableConditionalExpression : SerializableExpression - { - /// - /// - /// - public SerializableExpression Test; - /// - /// - /// - public SerializableExpression IfTrue; - /// - /// - /// - public SerializableExpression IfFalse; - - [SecurityCritical] - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddValue("Test", Test); - info.AddValue("IfTrue", IfTrue); - info.AddValue("IfFalse", IfFalse); - } - - public SerializableConditionalExpression() - { - } - - public SerializableConditionalExpression(SerializationInfo info, StreamingContext context) - : base(info, context) - { - Test = (SerializableExpression) info.GetValue("Test", typeof (SerializableExpression)); - IfTrue = (SerializableExpression) info.GetValue("IfTrue", typeof (SerializableExpression)); - IfFalse = (SerializableExpression) info.GetValue("IfFalse", typeof (SerializableExpression)); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableConstantExpression.cs b/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableConstantExpression.cs deleted file mode 100644 index 1f41359297..0000000000 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableConstantExpression.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (C) 2009-2021 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Denis Krjuchkov -// Created: 2009.05.12 - -using System; -using System.Linq.Expressions; -using System.Runtime.Serialization; -using System.Security; -using Xtensive.Reflection; - -namespace Xtensive.Linq.SerializableExpressions -{ - /// - /// A serializable representation of . - /// - [Serializable] - public sealed class SerializableConstantExpression : SerializableExpression - { - /// - /// - /// - public object Value; - - [SecurityCritical] - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddValue("Value", Value); - } - - - public SerializableConstantExpression() - { - } - - public SerializableConstantExpression(SerializationInfo info, StreamingContext context) - : base(info, context) - { - Value = info.GetValue("Value", WellKnownTypes.Object); - } - } -} diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableElementInit.cs b/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableElementInit.cs deleted file mode 100644 index dab5d0f28b..0000000000 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableElementInit.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (C) 2009-2021 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Denis Kryuchkov -// Created: 2009.05.14 - -using System; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.Serialization; -using System.Security; -using Xtensive.Linq.SerializableExpressions.Internals; - -namespace Xtensive.Linq.SerializableExpressions -{ - /// - /// A serializable representation of . - /// - [Serializable] - public sealed class SerializableElementInit : ISerializable - { - /// - /// - /// - public MethodInfo AddMethod; - /// - /// - /// - public SerializableExpression[] Arguments; - - [SecurityCritical] - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue("AddMethod", AddMethod.ToSerializableForm()); - info.AddArray("Arguments", Arguments); - } - - - public SerializableElementInit() - { - } - - public SerializableElementInit(SerializationInfo info, StreamingContext context) - { - AddMethod = info.GetString("AddMethod").GetMethodFromSerializableForm(); - Arguments = info.GetArrayFromSerializableForm("Arguments"); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableExpression.cs b/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableExpression.cs deleted file mode 100644 index 07338c6a3a..0000000000 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableExpression.cs +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (C) 2009-2021 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Denis Krjuchkov -// Created: 2009.05.12 - -using System; -using System.Linq.Expressions; -using System.Runtime.Serialization; -using System.Security; -using Xtensive.Linq.SerializableExpressions.Internals; - -namespace Xtensive.Linq.SerializableExpressions -{ - /// - /// A serializable representation of . - /// - [Serializable] - public abstract class SerializableExpression : ISerializable - { - /// - /// . - /// - public ExpressionType NodeType; - /// - /// . - /// - public Type Type; - - [SecurityCritical] - public virtual void GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue("NodeType", NodeType.ToString()); - info.AddValue("Type", Type.ToSerializableForm()); - } - - protected SerializableExpression() - { - } - - protected SerializableExpression(SerializationInfo info, StreamingContext context) - { - NodeType = (ExpressionType) Enum.Parse(typeof (ExpressionType), info.GetString("NodeType")); - Type = info.GetString("Type").GetTypeFromSerializableForm(); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableInvocationExpression.cs b/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableInvocationExpression.cs deleted file mode 100644 index 34f485bf6e..0000000000 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableInvocationExpression.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (C) 2009-2021 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Denis Krjuchkov -// Created: 2009.05.13 - -using System; -using System.Linq.Expressions; -using System.Runtime.Serialization; -using System.Security; -using Xtensive.Linq.SerializableExpressions.Internals; - -namespace Xtensive.Linq.SerializableExpressions -{ - /// - /// A serializable representation of . - /// - [Serializable] - public sealed class SerializableInvocationExpression : SerializableExpression - { - /// - /// - /// - public SerializableExpression Expression; - /// - /// - /// - public SerializableExpression[] Arguments; - - [SecurityCritical] - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddValue("Expression", Expression); - info.AddArray("Arguments", Arguments); - } - - public SerializableInvocationExpression() - { - } - - public SerializableInvocationExpression(SerializationInfo info, StreamingContext context) - : base(info, context) - { - Expression = (SerializableExpression) info.GetValue("Expression", typeof (SerializableExpression)); - Arguments = info.GetArrayFromSerializableForm("Arguments"); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableLambdaExpression.cs b/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableLambdaExpression.cs deleted file mode 100644 index badfb89c13..0000000000 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableLambdaExpression.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (C) 2009-2021 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Denis Krjuchkov -// Created: 2009.05.12 - -using System; -using System.Linq.Expressions; -using System.Runtime.Serialization; -using System.Security; -using Xtensive.Linq.SerializableExpressions.Internals; - -namespace Xtensive.Linq.SerializableExpressions -{ - /// - /// A serializable representation of . - /// - [Serializable] - public sealed class SerializableLambdaExpression : SerializableExpression - { - /// - /// . - /// - public SerializableExpression Body; - - /// - /// . - /// - public SerializableParameterExpression[] Parameters; - - [SecurityCritical] - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddValue("Body", Body); - info.AddArray("Parameters", Parameters); - } - - public SerializableLambdaExpression() - { - } - - public SerializableLambdaExpression(SerializationInfo info, StreamingContext context) - : base(info, context) - { - Body = (SerializableExpression) info.GetValue("Body", typeof (SerializableExpression)); - Parameters = info.GetArrayFromSerializableForm("Parameters"); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableListInitExpression.cs b/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableListInitExpression.cs deleted file mode 100644 index c0a36828de..0000000000 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableListInitExpression.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (C) 2009-2021 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Denis Krjuchkov -// Created: 2009.05.13 - -using System; -using System.Linq.Expressions; -using System.Runtime.Serialization; -using System.Security; -using Xtensive.Linq.SerializableExpressions.Internals; - -namespace Xtensive.Linq.SerializableExpressions -{ - /// - /// A serializable representation of . - /// - [Serializable] - public sealed class SerializableListInitExpression : SerializableExpression - { - /// - /// - /// - public SerializableNewExpression NewExpression; - /// - /// - /// - public SerializableElementInit[] Initializers; - - [SecurityCritical] - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddValue("NewExpression",NewExpression); - info.AddArray("Initializers", Initializers); - } - - public SerializableListInitExpression() - { - } - - public SerializableListInitExpression(SerializationInfo info, StreamingContext context) - : base(info, context) - { - NewExpression = (SerializableNewExpression) info.GetValue("NewExpression", typeof (SerializableNewExpression)); - Initializers = info.GetArrayFromSerializableForm("Initializers"); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableMemberAssignment.cs b/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableMemberAssignment.cs deleted file mode 100644 index 43a098252e..0000000000 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableMemberAssignment.cs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (C) 2009-2021 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Denis Krjuchkov -// Created: 2009.05.15 - -using System; -using System.Linq.Expressions; -using System.Runtime.Serialization; -using System.Security; - -namespace Xtensive.Linq.SerializableExpressions -{ - /// - /// A serializable representation of - /// - [Serializable] - public class SerializableMemberAssignment : SerializableMemberBinding - { - /// - /// - /// - public SerializableExpression Expression; - - [SecurityCritical] - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddValue("Expression", Expression); - } - - public SerializableMemberAssignment() - { - } - - public SerializableMemberAssignment(SerializationInfo info, StreamingContext context) - : base(info, context) - { - Expression = (SerializableExpression) info.GetValue("Expression", typeof (SerializableExpression)); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableMemberBinding.cs b/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableMemberBinding.cs deleted file mode 100644 index 0011a2f7ac..0000000000 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableMemberBinding.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (C) 2009-2021 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Denis Krjuchkov -// Created: 2009.05.15 - -using System; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.Serialization; -using System.Security; -using Xtensive.Linq.SerializableExpressions.Internals; - -namespace Xtensive.Linq.SerializableExpressions -{ - /// - /// A serializable representation of - /// - [Serializable] - public abstract class SerializableMemberBinding : ISerializable - { - /// - /// - /// - public MemberBindingType BindingType; - /// - /// - /// - public MemberInfo Member; - - [SecurityCritical] - public virtual void GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue("Member", Member.ToSerializableForm()); - info.AddValue("BindingType", BindingType.ToString()); - } - - - protected SerializableMemberBinding() - { - } - - protected SerializableMemberBinding(SerializationInfo info, StreamingContext context) - { - Member = info.GetString("Member").GetMemberFromSerializableForm(); - BindingType = (MemberBindingType) Enum.Parse(typeof(MemberBindingType), info.GetString("BindingType")); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableMemberExpression.cs b/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableMemberExpression.cs deleted file mode 100644 index 685f07be50..0000000000 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableMemberExpression.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (C) 2009-2021 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Denis Krjuchkov -// Created: 2009.05.12 - -using System; -using System.Collections.Generic; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.Serialization; -using System.Security; -using Xtensive.Linq.SerializableExpressions.Internals; - -namespace Xtensive.Linq.SerializableExpressions -{ - /// - /// A serializable representation of . - /// - [Serializable] - public sealed class SerializableMemberExpression : SerializableExpression - { - /// - /// - /// - public SerializableExpression Expression; - /// - /// - /// - public MemberInfo Member; - - [SecurityCritical] - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddValue("Expression", Expression); - info.AddValue("Member", Member.ToSerializableForm()); - } - - public SerializableMemberExpression() - { - } - - public SerializableMemberExpression(SerializationInfo info, StreamingContext context) - : base(info, context) - { - Expression = (SerializableExpression) info.GetValue("Expression", typeof (SerializableExpression)); - Member = info.GetString("Member").GetMemberFromSerializableForm(); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableMemberInitExpression.cs b/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableMemberInitExpression.cs deleted file mode 100644 index 682d6420dd..0000000000 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableMemberInitExpression.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (C) 2009-2021 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Denis Krjuchkov -// Created: 2009.05.13 - -using System; -using System.Linq.Expressions; -using System.Runtime.Serialization; -using System.Security; -using Xtensive.Linq.SerializableExpressions.Internals; - -namespace Xtensive.Linq.SerializableExpressions -{ - /// - /// A serializable representation of - /// - [Serializable] - public sealed class SerializableMemberInitExpression : SerializableExpression - { - /// - /// - /// - public SerializableNewExpression NewExpression; - /// - /// - /// - public SerializableMemberBinding[] Bindings; - - [SecurityCritical] - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddValue("NewExpression", NewExpression); - info.AddArray("Bindings", Bindings); - } - - public SerializableMemberInitExpression() - { - } - - public SerializableMemberInitExpression(SerializationInfo info, StreamingContext context) - : base(info, context) - { - NewExpression = (SerializableNewExpression) info.GetValue("NewExpression", typeof (SerializableNewExpression)); - Bindings = info.GetArrayFromSerializableForm("Bindings"); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableMemberListBinding.cs b/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableMemberListBinding.cs deleted file mode 100644 index d6c146555a..0000000000 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableMemberListBinding.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (C) 2009-2021 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Denis Kryuchkov -// Created: 2009.05.15 - -using System; -using System.Linq.Expressions; -using System.Runtime.Serialization; -using System.Security; -using Xtensive.Linq.SerializableExpressions.Internals; - -namespace Xtensive.Linq.SerializableExpressions -{ - /// - /// A serializable representation of . - /// - [Serializable] - public sealed class SerializableMemberListBinding : SerializableMemberBinding - { - /// - /// - /// - public SerializableElementInit[] Initializers; - - [SecurityCritical] - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddArray("Initializers", Initializers); - } - - public SerializableMemberListBinding() - { - } - - public SerializableMemberListBinding(SerializationInfo info, StreamingContext context) - : base(info, context) - { - Initializers = info.GetArrayFromSerializableForm("Initializers"); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableMemberMemberBinding.cs b/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableMemberMemberBinding.cs deleted file mode 100644 index edbd19808e..0000000000 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableMemberMemberBinding.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (C) 2009-2021 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Denis Krjuchkov -// Created: 2009.05.15 - -using System; -using System.Linq.Expressions; -using System.Runtime.Serialization; -using System.Security; -using Xtensive.Linq.SerializableExpressions.Internals; - -namespace Xtensive.Linq.SerializableExpressions -{ - /// - /// A serializable representation of . - /// - [Serializable] - public sealed class SerializableMemberMemberBinding : SerializableMemberBinding - { - /// - /// - /// - public SerializableMemberBinding[] Bindings; - - [SecurityCritical] - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddArray("Bindings", Bindings); - } - - public SerializableMemberMemberBinding() - { - } - - public SerializableMemberMemberBinding(SerializationInfo info, StreamingContext context) - : base(info, context) - { - Bindings = info.GetArrayFromSerializableForm("Bindings"); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableMethodCallExpression.cs b/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableMethodCallExpression.cs deleted file mode 100644 index e5002b074c..0000000000 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableMethodCallExpression.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (C) 2009-2021 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Denis Krjuchkov -// Created: 2009.05.12 - -using System; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.Serialization; -using System.Security; -using Xtensive.Linq.SerializableExpressions.Internals; - -namespace Xtensive.Linq.SerializableExpressions -{ - /// - /// A serializable representation of . - /// - [Serializable] - public sealed class SerializableMethodCallExpression : SerializableExpression - { - /// - /// - /// - public SerializableExpression[] Arguments; - /// - /// - /// - public MethodInfo Method; - - /// - /// - /// - public SerializableExpression Object; - - [SecurityCritical] - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddArray("Arguments", Arguments); - info.AddValue("Method", Method.ToSerializableForm()); - info.AddValue("Object", Object); - } - - public SerializableMethodCallExpression() - { - } - - public SerializableMethodCallExpression(SerializationInfo info, StreamingContext context) - : base(info, context) - { - Arguments = info.GetArrayFromSerializableForm("Arguments"); - Method = info.GetString("Method").GetMethodFromSerializableForm(); - Object = (SerializableExpression) info.GetValue("Object", typeof (SerializableExpression)); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableNewArrayExpression.cs b/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableNewArrayExpression.cs deleted file mode 100644 index 2930e7ec1b..0000000000 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableNewArrayExpression.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (C) 2009-2021 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Denis Krjuchkov -// Created: 2009.05.13 - -using System; -using System.Linq.Expressions; -using System.Runtime.Serialization; -using System.Security; -using Xtensive.Linq.SerializableExpressions.Internals; - -namespace Xtensive.Linq.SerializableExpressions -{ - /// - /// A serializable representation of - /// - [Serializable] - public sealed class SerializableNewArrayExpression : SerializableExpression - { - /// - /// - /// - public SerializableExpression[] Expressions; - - [SecurityCritical] - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddArray("Expressions", Expressions); - } - - public SerializableNewArrayExpression() - { - } - - public SerializableNewArrayExpression(SerializationInfo info, StreamingContext context) - : base(info, context) - { - Expressions = info.GetArrayFromSerializableForm("Expressions"); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableNewExpression.cs b/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableNewExpression.cs deleted file mode 100644 index 98ba732f52..0000000000 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableNewExpression.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (C) 2009-2021 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Denis Krjuchkov -// Created: 2009.05.12 - -using System; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.Serialization; -using System.Security; -using Xtensive.Linq.SerializableExpressions.Internals; - -namespace Xtensive.Linq.SerializableExpressions -{ - /// - /// A serializable representation of - /// - [Serializable] - public sealed class SerializableNewExpression : SerializableExpression - { - /// - /// - /// - public SerializableExpression[] Arguments; - /// - /// - /// - public ConstructorInfo Constructor; - /// - /// - /// - public MemberInfo[] Members; - - [SecurityCritical] - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddArray("Arguments", Arguments); - info.AddValue("Ctor", Constructor.ToSerializableForm()); - var memberNames = new string[Members.Length]; - for (int i = 0; i < memberNames.Length; i++) - memberNames[i] = Members[i].ToSerializableForm(); - info.AddArray("Members", memberNames); - } - - public SerializableNewExpression() - { - } - - public SerializableNewExpression(SerializationInfo info, StreamingContext context) - : base(info, context) - { - Arguments = info.GetArrayFromSerializableForm("Arguments"); - Constructor = info.GetString("Ctor").GetConstructorFromSerializableForm(); - var memberNames = info.GetArrayFromSerializableForm("Members"); - Members = new MemberInfo[memberNames.Length]; - for (int i = 0; i < memberNames.Length; i++) - Members[i] = memberNames[i].GetMemberFromSerializableForm(); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableTypeBinaryExpression.cs b/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableTypeBinaryExpression.cs deleted file mode 100644 index 2ae414725f..0000000000 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableTypeBinaryExpression.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (C) 2009-2021 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Denis Krjuchkov -// Created: 2009.05.12 - -using System; -using System.Linq.Expressions; -using System.Runtime.Serialization; -using System.Security; -using Xtensive.Linq.SerializableExpressions.Internals; -using ExpressionFactory = System.Linq.Expressions.Expression; - -namespace Xtensive.Linq.SerializableExpressions -{ - /// - /// A serializable representation of . - /// - [Serializable] - public sealed class SerializableTypeBinaryExpression : SerializableExpression - { - /// - /// - /// - public SerializableExpression Expression; - /// - /// - /// - public Type TypeOperand; - - [SecurityCritical] - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddValue("Expression", Expression); - info.AddValue("TypeOperand", TypeOperand.ToSerializableForm()); - } - - public SerializableTypeBinaryExpression() - { - } - - public SerializableTypeBinaryExpression(SerializationInfo info, StreamingContext context) - : base(info, context) - { - Expression = (SerializableExpression) info.GetValue("Expression", typeof (SerializableExpression)); - TypeOperand = info.GetString("TypeOperand").GetTypeFromSerializableForm(); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableUnaryExpression.cs b/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableUnaryExpression.cs deleted file mode 100644 index 73b403fd97..0000000000 --- a/Orm/Xtensive.Orm/Linq/SerializableExpressions/SerializableUnaryExpression.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (C) 2009-2021 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Denis Krjuchkov -// Created: 2009.05.12 - -using System; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.Serialization; -using System.Security; -using Xtensive.Linq.SerializableExpressions.Internals; - -namespace Xtensive.Linq.SerializableExpressions -{ - /// - /// A serializable representation of . - /// - [Serializable] - public sealed class SerializableUnaryExpression : SerializableExpression - { - /// - /// - /// - public SerializableExpression Operand; - /// - /// - /// - public MethodInfo Method; - - [SecurityCritical] - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddValue("Operand", Operand); - info.AddValue("Method", Method.ToSerializableForm()); - } - - public SerializableUnaryExpression() - { - } - - public SerializableUnaryExpression(SerializationInfo info, StreamingContext context) - : base(info, context) - { - Operand = (SerializableExpression) info.GetValue("Operand", typeof (SerializableExpression)); - Method = info.GetString("Method").GetMethodFromSerializableForm(); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Modelling/Actions/ActionHandler.cs b/Orm/Xtensive.Orm/Modelling/Actions/ActionHandler.cs index 5c6e38ef1f..82ff3834f8 100644 --- a/Orm/Xtensive.Orm/Modelling/Actions/ActionHandler.cs +++ b/Orm/Xtensive.Orm/Modelling/Actions/ActionHandler.cs @@ -13,16 +13,13 @@ namespace Xtensive.Modelling.Actions /// /// An abstract base class for any implementor. /// - [Serializable] public abstract class ActionHandler : IActionHandler, IContext { /// /// Gets the current . /// - public static ActionHandler Current { - get { return ActionHandlerScope.CurrentHandler; } - } + public static ActionHandler Current => ActionHandlerScope.CurrentHandler; /// public abstract void Execute(NodeAction action); @@ -30,21 +27,13 @@ public static ActionHandler Current { #region IContext<...> implementation /// - public bool IsActive { - get { return ActionHandlerScope.CurrentHandler==this; } - } + public bool IsActive => ActionHandlerScope.CurrentHandler == this; /// - public ActionHandlerScope Activate() - { - return new ActionHandlerScope(this); - } + public ActionHandlerScope Activate() => new ActionHandlerScope(this); /// - IDisposable IContext.Activate() - { - return Activate(); - } + IDisposable IContext.Activate() => Activate(); #endregion } diff --git a/Orm/Xtensive.Orm/Modelling/Actions/ActionSequence.cs b/Orm/Xtensive.Orm/Modelling/Actions/ActionSequence.cs index b03a8b0d52..9948b67934 100644 --- a/Orm/Xtensive.Orm/Modelling/Actions/ActionSequence.cs +++ b/Orm/Xtensive.Orm/Modelling/Actions/ActionSequence.cs @@ -16,24 +16,20 @@ namespace Xtensive.Modelling.Actions /// /// sequence implementation. /// - [Serializable] public class ActionSequence : LockableBase, IActionSequence { private readonly List actions = new List(); - [NonSerialized] private ActionScope currentScope; /// - public ActionScope CurrentScope { - get { return currentScope; } - } + public ActionScope CurrentScope => currentScope; /// public ActionScope LogAction() { var newScope = new ActionScope(this); - if (currentScope==null) + if (currentScope is null) currentScope = newScope; return newScope; } @@ -44,12 +40,10 @@ public void Add(NodeAction action) ArgumentNullException.ThrowIfNull(action); EnsureNotLocked(); // Only locked actions can be added - var ca = action as PropertyChangeAction; - if (ca!=null && actions.Count!=0) { + if (action is PropertyChangeAction ca && actions.Count != 0) { // Let's try to join two change actions var lastIndex = actions.Count - 1; - var last = actions[lastIndex] as PropertyChangeAction; - if (last!=null && ca.Path==last.Path) { + if (actions[lastIndex] is PropertyChangeAction last && ca.Path == last.Path) { foreach (var pair in last.Properties) { _ = ca.Properties.TryAdd(pair.Key, pair.Value); } @@ -79,8 +73,7 @@ public void Apply(IModel model) public IEnumerable Flatten() { foreach (var action in actions) { - var gna = action as GroupingNodeAction; - if (gna!=null) + if (action is GroupingNodeAction gna) foreach (var nestedAction in gna.Flatten()) yield return nestedAction; else @@ -125,8 +118,9 @@ IEnumerator IEnumerable.GetEnumerator() public override string ToString() { var sb = new StringBuilder(); - foreach (var action in actions) - sb.AppendLine(action.ToString()); + foreach (var action in actions) { + _ = sb.AppendLine(action.ToString()); + } return sb.ToString(); } diff --git a/Orm/Xtensive.Orm/Modelling/Actions/CreateNodeAction.cs b/Orm/Xtensive.Orm/Modelling/Actions/CreateNodeAction.cs index 69a6a56a59..b34349422e 100644 --- a/Orm/Xtensive.Orm/Modelling/Actions/CreateNodeAction.cs +++ b/Orm/Xtensive.Orm/Modelling/Actions/CreateNodeAction.cs @@ -17,7 +17,6 @@ namespace Xtensive.Modelling.Actions /// /// Describes node creation. /// - [Serializable] public class CreateNodeAction : NodeAction { private Type type; @@ -68,7 +67,7 @@ public object[] Parameters { get { if (!IsLocked) return parameters; - return parameters==null ? null : (object[]) parameters.Clone(); + return parameters is null ? null : (object[]) parameters.Clone(); } set { EnsureNotLocked(); @@ -83,9 +82,9 @@ protected override void PerformExecute(IModel model, IPathNode item) ArgumentNullException.ThrowIfNull(item); var parent = (Node) item; var node = TryConstructor(model, parent, name); // Regular node - if (node==null) + if (node is null) node = TryConstructor(model, parent); // Unnamed node - if (node==null) + if (node is null) throw new InvalidOperationException(string.Format( Strings.ExCannotFindConstructorToExecuteX, this)); if (index.HasValue) @@ -105,7 +104,7 @@ protected Node TryConstructor(IModel model, params object[] arguments) arguments = arguments.Concat(parameters.Select(p => PathNodeReference.Resolve(model, p))).ToArray(arguments.Length + parameters.Length); var argTypes = arguments.SelectToArray(a => a.GetType()); var ci = type.GetConstructor(argTypes); - if (ci==null) + if (ci is null) return null; return (Node) ci.Invoke(arguments); } @@ -114,12 +113,12 @@ protected Node TryConstructor(IModel model, params object[] arguments) protected override void GetParameters(List> parameters) { base.GetParameters(parameters); - parameters.Add(new Pair("Type", type.GetShortName())); - parameters.Add(new Pair("Name", name)); + parameters.Add(new Pair(nameof(Type), type.GetShortName())); + parameters.Add(new Pair(nameof(Name), name)); if (index.HasValue) - parameters.Add(new Pair("Index", index.ToString())); - if (this.parameters!=null) - parameters.Add(new Pair("Parameters", this.parameters.ToCommaDelimitedString())); + parameters.Add(new Pair(nameof(Index), index.ToString())); + if (this.parameters is not null) + parameters.Add(new Pair(nameof(Parameters), this.parameters.ToCommaDelimitedString())); } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Modelling/Actions/DataAction.cs b/Orm/Xtensive.Orm/Modelling/Actions/DataAction.cs index e3e50cdcb7..1a2e34bf58 100644 --- a/Orm/Xtensive.Orm/Modelling/Actions/DataAction.cs +++ b/Orm/Xtensive.Orm/Modelling/Actions/DataAction.cs @@ -13,7 +13,6 @@ namespace Xtensive.Modelling.Actions /// /// Change data action. /// - [Serializable] public class DataAction : NodeAction { private DataHint dataHint; diff --git a/Orm/Xtensive.Orm/Modelling/Actions/GroupingNodeAction.cs b/Orm/Xtensive.Orm/Modelling/Actions/GroupingNodeAction.cs index 6af85d2c38..21b5ae920d 100644 --- a/Orm/Xtensive.Orm/Modelling/Actions/GroupingNodeAction.cs +++ b/Orm/Xtensive.Orm/Modelling/Actions/GroupingNodeAction.cs @@ -15,7 +15,6 @@ namespace Xtensive.Modelling.Actions /// /// A grouping node action. /// - [Serializable] public class GroupingNodeAction : NodeAction { private string comment; @@ -35,9 +34,7 @@ public string Comment { /// /// Gets the list of nested actions. /// - public IList Actions { - get { return actions; } - } + public IList Actions => actions; /// /// Adds the specified action to the sequence. @@ -48,12 +45,10 @@ public void Add(NodeAction action) ArgumentNullException.ThrowIfNull(action); EnsureNotLocked(); // Only locked actions can be added - var ca = action as PropertyChangeAction; - if (ca!=null && actions.Count!=0) { + if (action is PropertyChangeAction ca && actions.Count != 0) { // Let's try to join two change actions var lastIndex = actions.Count - 1; - var last = actions[lastIndex] as PropertyChangeAction; - if (last!=null && ca.Path==last.Path) { + if (actions[lastIndex] is PropertyChangeAction last && ca.Path == last.Path) { foreach (var pair in last.Properties) { _ = ca.Properties.TryAdd(pair.Key, pair.Value); } @@ -70,8 +65,7 @@ public void Add(NodeAction action) public IEnumerable Flatten() { foreach (var action in actions) { - var gna = action as GroupingNodeAction; - if (gna!=null) + if (action is GroupingNodeAction gna) foreach (var nestedAction in gna.Flatten()) yield return nestedAction; else diff --git a/Orm/Xtensive.Orm/Modelling/Actions/MoveNodeAction.cs b/Orm/Xtensive.Orm/Modelling/Actions/MoveNodeAction.cs index 45bf2e5478..e362ac389a 100644 --- a/Orm/Xtensive.Orm/Modelling/Actions/MoveNodeAction.cs +++ b/Orm/Xtensive.Orm/Modelling/Actions/MoveNodeAction.cs @@ -17,7 +17,6 @@ namespace Xtensive.Modelling.Actions /// /// Any kinds of node movement (parent changed, name changed or index changed). /// - [Serializable] public class MoveNodeAction : NodeAction { private string parent; @@ -76,7 +75,7 @@ protected override void PerformExecute(IModel model, IPathNode item) { ArgumentNullException.ThrowIfNull(item); var node = (Node) item; - var newParent = parent==null ? node.Parent : (Node) model.Resolve(parent, true); + var newParent = parent is null ? node.Parent : (Node) model.Resolve(parent, true); if ((node is IModel) && (newParent is IModel)) newParent = null; var newName = name ?? node.Name; @@ -88,9 +87,9 @@ protected override void PerformExecute(IModel model, IPathNode item) protected override void GetParameters(List> parameters) { base.GetParameters(parameters); - if (parent!=null) + if (parent is not null) parameters.Add(new Pair("Parent", parent)); - if (name!=null) + if (name is not null) parameters.Add(new Pair("Name", name)); if (index.HasValue) parameters.Add(new Pair("Index", index.ToString())); diff --git a/Orm/Xtensive.Orm/Modelling/Actions/NodeAction.cs b/Orm/Xtensive.Orm/Modelling/Actions/NodeAction.cs index 35c91cc2da..1f19ac3381 100644 --- a/Orm/Xtensive.Orm/Modelling/Actions/NodeAction.cs +++ b/Orm/Xtensive.Orm/Modelling/Actions/NodeAction.cs @@ -7,10 +7,7 @@ using System; using System.Collections.Generic; using System.Text; -using Xtensive.Collections; using Xtensive.Core; - -using Xtensive.Reflection; using Xtensive.Modelling.Comparison; using System.Linq; @@ -19,7 +16,6 @@ namespace Xtensive.Modelling.Actions /// /// Abstract base class for any node action. /// - [Serializable] public abstract class NodeAction : LockableBase, INodeAction { @@ -71,10 +67,7 @@ public virtual void Execute(IModel model) /// /// The name to escape. /// Escaped name. - protected static string EscapeName(string name) - { - return new[] {name}.RevertibleJoin(Node.PathEscape, Node.PathDelimiter); - } + protected static string EscapeName(string name) => new[] { name }.RevertibleJoin(Node.PathEscape, Node.PathDelimiter); #endregion @@ -85,17 +78,17 @@ public override string ToString() { var sb = new StringBuilder(); if (this is GroupingNodeAction) - sb.Append("["); - sb.Append(GetActionName()); + _ = sb.Append("["); + _ = sb.Append(GetActionName()); var parameters = new List>(); GetParameters(parameters); foreach (var kvp in parameters) - sb.AppendFormat($", {kvp.First}={kvp.Second}"); + _ = sb.AppendFormat($", {kvp.First}={kvp.Second}"); if (this is GroupingNodeAction) - sb.Append("]"); + _ = sb.Append("]"); var nestedActions = GetNestedActions(); foreach (var action in nestedActions) - sb.AppendLine().Append(action.ToString().Indent(2)); + _ = sb.AppendLine().Append(action.ToString().Indent(2)); return sb.ToString(); } @@ -114,7 +107,7 @@ protected virtual string GetActionName() /// The sequence of parameters. protected virtual void GetParameters(List> parameters) { - if (path!=null) + if (path is not null) parameters.Add(new Pair("Path", path)); } @@ -122,10 +115,7 @@ protected virtual void GetParameters(List> parameters) /// Gets the sequence of nested actions for formatting, if any. /// /// The sequence of nested actions. - protected virtual IEnumerable GetNestedActions() - { - return Enumerable.Empty(); - } + protected virtual IEnumerable GetNestedActions() => Enumerable.Empty(); #endregion diff --git a/Orm/Xtensive.Orm/Modelling/Actions/NullActionHandler.cs b/Orm/Xtensive.Orm/Modelling/Actions/NullActionHandler.cs index 9c77e14a0d..c1cc2c505a 100644 --- a/Orm/Xtensive.Orm/Modelling/Actions/NullActionHandler.cs +++ b/Orm/Xtensive.Orm/Modelling/Actions/NullActionHandler.cs @@ -11,7 +11,6 @@ namespace Xtensive.Modelling.Actions /// /// An that does nothing. /// - [Serializable] public class NullActionHandler : ActionHandler { private static readonly NullActionHandler instance = new NullActionHandler(); @@ -19,9 +18,7 @@ public class NullActionHandler : ActionHandler /// /// Gets the only instance of this class. /// - public static NullActionHandler Instance { - get { return instance; } - } + public static NullActionHandler Instance => instance; /// public override void Execute(NodeAction action) diff --git a/Orm/Xtensive.Orm/Modelling/Actions/PathNodeReference.cs b/Orm/Xtensive.Orm/Modelling/Actions/PathNodeReference.cs index d91fb30bae..8e482b78df 100644 --- a/Orm/Xtensive.Orm/Modelling/Actions/PathNodeReference.cs +++ b/Orm/Xtensive.Orm/Modelling/Actions/PathNodeReference.cs @@ -10,7 +10,6 @@ namespace Xtensive.Modelling.Actions /// /// Path node reference. /// - [Serializable] public readonly struct PathNodeReference : IEquatable { @@ -19,9 +18,7 @@ namespace Xtensive.Modelling.Actions /// /// Gets the path to the node. /// - public string Path { - get { return path; } - } + public string Path => path; /// /// Gets the to the specified source, @@ -35,7 +32,7 @@ public string Path { public static object Get(object source) { var pathNode = source as IPathNode; - if (pathNode==null) + if (pathNode is null) return source; return new PathNodeReference(pathNode.Path); } @@ -67,17 +64,20 @@ public static object Resolve(IModel model, object source) /// public override int GetHashCode() => path != null ? path.GetHashCode() : 0; - public static bool operator ==(PathNodeReference left, PathNodeReference right) => left.Equals(right); + public static bool operator ==(PathNodeReference left, PathNodeReference right) + { + return left.Equals(right); + } - public static bool operator !=(PathNodeReference left, PathNodeReference right) => !left.Equals(right); + public static bool operator !=(PathNodeReference left, PathNodeReference right) + { + return !left.Equals(right); + } #endregion /// - public override string ToString() - { - return path; - } + public override string ToString() => path; // Constructors diff --git a/Orm/Xtensive.Orm/Modelling/Actions/PropertyChangeAction.cs b/Orm/Xtensive.Orm/Modelling/Actions/PropertyChangeAction.cs index 038c30116d..b5986b5fc0 100644 --- a/Orm/Xtensive.Orm/Modelling/Actions/PropertyChangeAction.cs +++ b/Orm/Xtensive.Orm/Modelling/Actions/PropertyChangeAction.cs @@ -14,7 +14,6 @@ namespace Xtensive.Modelling.Actions /// /// Property change action. /// - [Serializable] public class PropertyChangeAction : NodeAction { private IDictionary properties = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -22,15 +21,12 @@ public class PropertyChangeAction : NodeAction /// /// Gets or sets the properties. /// - public IDictionary Properties { - get { return properties; } - } + public IDictionary Properties => properties; /// protected override void PerformExecute(IModel model, IPathNode item) { - ArgumentNullException.ThrowIfNull(item); - var node = (Node) item; + var node = (Node) (item ?? throw new ArgumentNullException(nameof(item))); foreach (var pair in properties) node.SetProperty(pair.Key, PathNodeReference.Resolve(model, pair.Value)); } @@ -40,7 +36,7 @@ protected override void GetParameters(List> parameters) { base.GetParameters(parameters); foreach (var pair in properties) - parameters.Add(new Pair(pair.Key, pair.Value==null ? null : pair.Value.ToString())); + parameters.Add(new Pair(pair.Key, pair.Value is null ? null : pair.Value.ToString())); } /// diff --git a/Orm/Xtensive.Orm/Modelling/Actions/RemoveNodeAction.cs b/Orm/Xtensive.Orm/Modelling/Actions/RemoveNodeAction.cs index bf26aa6858..8b134c7983 100644 --- a/Orm/Xtensive.Orm/Modelling/Actions/RemoveNodeAction.cs +++ b/Orm/Xtensive.Orm/Modelling/Actions/RemoveNodeAction.cs @@ -13,14 +13,12 @@ namespace Xtensive.Modelling.Actions /// /// Describes node removal. /// - [Serializable] public class RemoveNodeAction : NodeAction { /// protected override void PerformExecute(IModel model, IPathNode item) { - ArgumentNullException.ThrowIfNull(item); - var node = (Node) item; + var node = (Node) (item ?? throw new ArgumentNullException(nameof(item))); node.Remove(); } } diff --git a/Orm/Xtensive.Orm/Modelling/Attributes/DataDependentAttribute.cs b/Orm/Xtensive.Orm/Modelling/Attributes/DataDependentAttribute.cs index 24ba4ba498..16642e17d9 100644 --- a/Orm/Xtensive.Orm/Modelling/Attributes/DataDependentAttribute.cs +++ b/Orm/Xtensive.Orm/Modelling/Attributes/DataDependentAttribute.cs @@ -11,7 +11,6 @@ namespace Xtensive.Modelling.Attributes /// /// Data dependent node marker. /// - [Serializable] [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public sealed class DataDependentAttribute : Attribute { diff --git a/Orm/Xtensive.Orm/Modelling/Attributes/PropertyAttribute.cs b/Orm/Xtensive.Orm/Modelling/Attributes/PropertyAttribute.cs index d6982fe8a5..b8a3642793 100644 --- a/Orm/Xtensive.Orm/Modelling/Attributes/PropertyAttribute.cs +++ b/Orm/Xtensive.Orm/Modelling/Attributes/PropertyAttribute.cs @@ -11,7 +11,6 @@ namespace Xtensive.Modelling.Attributes /// /// Node property marker. /// - [Serializable] [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public sealed class PropertyAttribute : Attribute { diff --git a/Orm/Xtensive.Orm/Modelling/Attributes/SystemPropertyAttribute.cs b/Orm/Xtensive.Orm/Modelling/Attributes/SystemPropertyAttribute.cs index 794299de77..17cf67069c 100644 --- a/Orm/Xtensive.Orm/Modelling/Attributes/SystemPropertyAttribute.cs +++ b/Orm/Xtensive.Orm/Modelling/Attributes/SystemPropertyAttribute.cs @@ -14,7 +14,6 @@ namespace Xtensive.Modelling.Attributes /// System property marker. /// [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] - [Serializable] internal sealed class SystemPropertyAttribute : Attribute { /// diff --git a/Orm/Xtensive.Orm/Modelling/CloningContext.cs b/Orm/Xtensive.Orm/Modelling/CloningContext.cs index cb8aef7dbe..f26057daf0 100644 --- a/Orm/Xtensive.Orm/Modelling/CloningContext.cs +++ b/Orm/Xtensive.Orm/Modelling/CloningContext.cs @@ -17,28 +17,25 @@ namespace Xtensive.Modelling /// /// cloning context. /// - [Serializable] public class CloningContext : IContext { private List fixups; + /// + /// Gets the current validation context. + /// + public static CloningContext Current => CloningScope.CurrentContext; + /// /// Gets all the added fixups. /// - public IEnumerable Fixups { - get { return fixups ?? Enumerable.Empty(); } - } + public IEnumerable Fixups => fixups ?? Enumerable.Empty(); /// /// Adds the new fixup to fixups sequence. /// /// The fixup to add. - public void AddFixup(Action fixup) - { - if (fixups==null) - fixups = new List(); - fixups.Add(fixup); - } + public void AddFixup(Action fixup) => (fixups ??= new List()).Add(fixup); /// /// Clears all the fixups. @@ -53,35 +50,20 @@ public void ClearFixups() /// public void ApplyFixups() { - if (fixups==null) + if (fixups is null) return; foreach (var fixup in fixups) fixup.Invoke(); fixups = null; } - /// - /// Gets the current validation context. - /// - public static CloningContext Current { - get { - return CloningScope.CurrentContext; - } - } - #region IContext<...> methods /// - public CloningScope Activate() - { - return new CloningScope(this); - } + public CloningScope Activate() => new CloningScope(this); /// - public bool IsActive - { - get { return Current==this; } - } + public bool IsActive => Current == this; /// IDisposable IContext.Activate() diff --git a/Orm/Xtensive.Orm/Modelling/Comparison/Difference.cs b/Orm/Xtensive.Orm/Modelling/Comparison/Difference.cs index c0f420e996..c28c4979f9 100644 --- a/Orm/Xtensive.Orm/Modelling/Comparison/Difference.cs +++ b/Orm/Xtensive.Orm/Modelling/Comparison/Difference.cs @@ -18,7 +18,6 @@ namespace Xtensive.Modelling.Comparison /// /// Base comparison result. /// - [Serializable] public abstract class Difference : IDifference { /// @@ -27,13 +26,13 @@ public abstract class Difference : IDifference protected static readonly int ToString_IndentSize = 2; /// - public object Source { get; private set; } + public object Source { get; } /// - public object Target { get; private set; } + public object Target { get; } /// - public Difference Parent { get; private set; } + public Difference Parent { get; } /// public abstract bool HasChanges { get; } @@ -72,7 +71,7 @@ protected Difference(object source, object target) Source = source; Target = target; var any = source ?? target; - if (any==null) + if (any is null) throw new InvalidOperationException(Strings.ExBothSourceAndTargetAreNull); Parent = Comparer.Current.Context.Difference; } diff --git a/Orm/Xtensive.Orm/Modelling/Comparison/Hints/CopyDataHint.cs b/Orm/Xtensive.Orm/Modelling/Comparison/Hints/CopyDataHint.cs index d3dfd718fe..1e8bb4fd1a 100644 --- a/Orm/Xtensive.Orm/Modelling/Comparison/Hints/CopyDataHint.cs +++ b/Orm/Xtensive.Orm/Modelling/Comparison/Hints/CopyDataHint.cs @@ -16,7 +16,6 @@ namespace Xtensive.Modelling.Comparison.Hints /// /// Hint for copy data operation. /// - [Serializable] public sealed class CopyDataHint : DataHint { /// @@ -61,14 +60,11 @@ public override string ToString() /// /// Initializes new instance of this type. /// - public CopyDataHint(string sourceTablePath, IList identities, + public CopyDataHint(string sourceTablePath, IList identities, IList> copiedColumns) : base(sourceTablePath, identities) { - ArgumentNullException.ThrowIfNull(copiedColumns); - CopiedColumns = new ReadOnlyCollection>(copiedColumns); + CopiedColumns = new ReadOnlyCollection>(copiedColumns ?? throw new ArgumentNullException(nameof(copiedColumns))); } - - } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Modelling/Comparison/Hints/DataHint.cs b/Orm/Xtensive.Orm/Modelling/Comparison/Hints/DataHint.cs index 071301eb5a..9336efc32c 100644 --- a/Orm/Xtensive.Orm/Modelling/Comparison/Hints/DataHint.cs +++ b/Orm/Xtensive.Orm/Modelling/Comparison/Hints/DataHint.cs @@ -15,18 +15,17 @@ namespace Xtensive.Modelling.Comparison.Hints /// /// An abstract base class for all data hints. /// - [Serializable] public abstract class DataHint : Hint { /// /// Gets the source table path. /// - public string SourceTablePath { get; private set; } + public string SourceTablePath { get; } /// /// Gets the identities for data operation. /// - public IReadOnlyList Identities { get; private set; } + public IReadOnlyList Identities { get; } /// public override IEnumerable GetTargets() @@ -47,7 +46,7 @@ public override IEnumerable GetTargets() /// /// Initializes new instance of this type. /// - protected DataHint(string sourceTablePath, IList identities) + protected DataHint(string sourceTablePath, IList identities) { ArgumentValidator.EnsureArgumentNotNullOrEmpty(sourceTablePath, nameof(sourceTablePath)); ArgumentNullException.ThrowIfNull(identities); diff --git a/Orm/Xtensive.Orm/Modelling/Comparison/Hints/DeleteDataHint.cs b/Orm/Xtensive.Orm/Modelling/Comparison/Hints/DeleteDataHint.cs index 1afc129a2e..b88f1da593 100644 --- a/Orm/Xtensive.Orm/Modelling/Comparison/Hints/DeleteDataHint.cs +++ b/Orm/Xtensive.Orm/Modelling/Comparison/Hints/DeleteDataHint.cs @@ -14,7 +14,6 @@ namespace Xtensive.Modelling.Comparison.Hints /// /// Hint for delete data operation. /// - [Serializable] public class DeleteDataHint : DataHint { [Flags] diff --git a/Orm/Xtensive.Orm/Modelling/Comparison/Hints/Hint.cs b/Orm/Xtensive.Orm/Modelling/Comparison/Hints/Hint.cs index 6cbf03730d..249ed33b7f 100644 --- a/Orm/Xtensive.Orm/Modelling/Comparison/Hints/Hint.cs +++ b/Orm/Xtensive.Orm/Modelling/Comparison/Hints/Hint.cs @@ -12,7 +12,6 @@ namespace Xtensive.Modelling.Comparison.Hints /// /// An abstract base for comparison hint implementation. /// - [Serializable] public abstract class Hint : IHint { /// diff --git a/Orm/Xtensive.Orm/Modelling/Comparison/Hints/HintSet.cs b/Orm/Xtensive.Orm/Modelling/Comparison/Hints/HintSet.cs index 41ff6c14b7..a0f92b03c0 100644 --- a/Orm/Xtensive.Orm/Modelling/Comparison/Hints/HintSet.cs +++ b/Orm/Xtensive.Orm/Modelling/Comparison/Hints/HintSet.cs @@ -18,31 +18,26 @@ namespace Xtensive.Modelling.Comparison.Hints /// /// set. /// - [Serializable] [DebuggerDisplay("Count = {Count}")] public class HintSet : LockableBase, IHintSet { [DebuggerBrowsable(DebuggerBrowsableState.Never)] - private static Lazy cachedEmpty = new Lazy(() => { - var hs = new HintSet(); - hs.Lock(true); - return hs; + private static Lazy cachedEmpty = new (() => { + return new HintSet(); // locked }); /// /// Gets the empty . /// - public static HintSet Empty { - get { - return cachedEmpty.Value; - } - } + public static HintSet Empty => cachedEmpty.Value; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - private readonly List list = new List(); + private readonly List list = new(); + [DebuggerBrowsable(DebuggerBrowsableState.Never)] - private readonly HashSet set = new HashSet(); + private readonly HashSet set = new(); + [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly Dictionary> hintMap = new Dictionary>(); @@ -51,15 +46,15 @@ public static HintSet Empty { /// Gets the number of elements contained in a collection. /// /// - public int Count { - get { return set.Count; } - } + public int Count => set.Count; /// - public IModel SourceModel { get; private set; } + public IModel SourceModel { get; } /// - public IModel TargetModel { get; private set; } + public IModel TargetModel { get; } + + public Dictionary> HintMap => hintMap; /// /// One of paths returned by @@ -105,7 +100,7 @@ public void Add(Hint hint) Add(oldHint); throw; } - set.Add(hint); + _ = set.Add(hint); list.Add(hint); } @@ -114,7 +109,7 @@ public void Clear() { set.Clear(); list.Clear(); - hintMap.Clear(); + HintMap.Clear(); } /// @@ -167,8 +162,8 @@ private Dictionary GetNodeHints(Node node) { ArgumentNullException.ThrowIfNull(node); - if (!hintMap.TryGetValue(node, out var nodeHintMap)) { - hintMap.Add(node, nodeHintMap = new Dictionary()); + if (!HintMap.TryGetValue(node, out var nodeHintMap)) { + HintMap.Add(node, nodeHintMap = new Dictionary()); } return nodeHintMap; } @@ -212,6 +207,7 @@ public HintSet(IModel sourceModel, IModel targetModel) private HintSet() { + this.Lock(); } } } diff --git a/Orm/Xtensive.Orm/Modelling/Comparison/Hints/HintTarget.cs b/Orm/Xtensive.Orm/Modelling/Comparison/Hints/HintTarget.cs index 210cb4d28d..31fe673a96 100644 --- a/Orm/Xtensive.Orm/Modelling/Comparison/Hints/HintTarget.cs +++ b/Orm/Xtensive.Orm/Modelling/Comparison/Hints/HintTarget.cs @@ -12,32 +12,24 @@ namespace Xtensive.Modelling.Comparison.Hints /// /// Hint target reference. /// - [Serializable] public struct HintTarget : IEquatable { - private ModelType model; - private string path; - /// /// Gets the model this hint target points to. /// - public ModelType Model { - get { return model; } - } + public ModelType Model { get; } /// /// Gets the node path this hint target points to. /// - public string Path { - get { return path; } - } + public string Path { get; } #region Equality members /// public bool Equals(HintTarget obj) { - return obj.model==model && obj.path==path; + return obj.Model==Model && obj.Path==Path; } /// @@ -50,7 +42,7 @@ public override bool Equals(object obj) public override int GetHashCode() { unchecked { - return (model.GetHashCode() * 397) ^ (path!=null ? path.GetHashCode() : 0); + return (Model.GetHashCode() * 397) ^ (Path!=null ? Path.GetHashCode() : 0); } } @@ -88,8 +80,8 @@ public override int GetHashCode() /// The path. public HintTarget(ModelType model, string path) { - this.model = model; - this.path = path; + Model = model; + Path = path; } } } diff --git a/Orm/Xtensive.Orm/Modelling/Comparison/Hints/IdentityPair.cs b/Orm/Xtensive.Orm/Modelling/Comparison/Hints/IdentityPair.cs index 32e39e89c2..20ead0f18f 100644 --- a/Orm/Xtensive.Orm/Modelling/Comparison/Hints/IdentityPair.cs +++ b/Orm/Xtensive.Orm/Modelling/Comparison/Hints/IdentityPair.cs @@ -13,24 +13,23 @@ namespace Xtensive.Modelling.Comparison.Hints /// /// Pair of node paths or node path and constant. /// - [Serializable] [DebuggerDisplay("{Source} == {Target}")] public class IdentityPair { /// /// Gets the source node path. /// - public string Source { get; private set; } + public string Source { get; } /// /// Gets the target node path or constant. /// - public string Target { get; private set; } + public string Target { get; } /// /// Gets a value indicating whether this value is constant. /// - public bool IsIdentifiedByConstant { get; private set; } + public bool IsIdentifiedByConstant { get; } /// public override string ToString() diff --git a/Orm/Xtensive.Orm/Modelling/Comparison/Hints/IgnoreHint.cs b/Orm/Xtensive.Orm/Modelling/Comparison/Hints/IgnoreHint.cs index 6b079cfb9e..a87568d7a0 100644 --- a/Orm/Xtensive.Orm/Modelling/Comparison/Hints/IgnoreHint.cs +++ b/Orm/Xtensive.Orm/Modelling/Comparison/Hints/IgnoreHint.cs @@ -17,13 +17,12 @@ namespace Xtensive.Modelling.Comparison.Hints /// Ignore node hint. /// Add possibilities to ignore specified node in comparison. /// - [Serializable] public class IgnoreHint : Hint { /// /// Gets ignored node path. /// - public string Path { get; private set; } + public string Path { get; } /// public override IEnumerable GetTargets() diff --git a/Orm/Xtensive.Orm/Modelling/Comparison/Hints/RenameHint.cs b/Orm/Xtensive.Orm/Modelling/Comparison/Hints/RenameHint.cs index 5de36f2b12..5e6de8abd9 100644 --- a/Orm/Xtensive.Orm/Modelling/Comparison/Hints/RenameHint.cs +++ b/Orm/Xtensive.Orm/Modelling/Comparison/Hints/RenameHint.cs @@ -14,7 +14,6 @@ namespace Xtensive.Modelling.Comparison.Hints /// /// Rename hint. /// - [Serializable] public class RenameHint : Hint { /// diff --git a/Orm/Xtensive.Orm/Modelling/Comparison/Hints/UpdateDataHint.cs b/Orm/Xtensive.Orm/Modelling/Comparison/Hints/UpdateDataHint.cs index 9dbcd33b76..cfaef1bbf9 100644 --- a/Orm/Xtensive.Orm/Modelling/Comparison/Hints/UpdateDataHint.cs +++ b/Orm/Xtensive.Orm/Modelling/Comparison/Hints/UpdateDataHint.cs @@ -16,14 +16,13 @@ namespace Xtensive.Modelling.Comparison.Hints /// /// Hint for update data operation. /// - [Serializable] public class UpdateDataHint : DataHint { /// /// Gets the update parameter. The first is updated column path, /// the second is new value or null (default value). /// - public IReadOnlyList> UpdateParameter { get; private set; } + public IReadOnlyList> UpdateParameter { get; } /// public override IEnumerable GetTargets() @@ -60,8 +59,7 @@ public UpdateDataHint( IList> updateParameters) : base(sourceTablePath, identities) { - ArgumentNullException.ThrowIfNull(updateParameters); - UpdateParameter = new ReadOnlyCollection>(updateParameters); + UpdateParameter = new ReadOnlyCollection>(updateParameters ?? throw new ArgumentNullException(nameof(updateParameters))); } } diff --git a/Orm/Xtensive.Orm/Modelling/Comparison/NodeCollectionDifference.cs b/Orm/Xtensive.Orm/Modelling/Comparison/NodeCollectionDifference.cs index cde27ee9ce..e986c0dd51 100644 --- a/Orm/Xtensive.Orm/Modelling/Comparison/NodeCollectionDifference.cs +++ b/Orm/Xtensive.Orm/Modelling/Comparison/NodeCollectionDifference.cs @@ -10,45 +10,36 @@ using System.Text; using Xtensive.Core; -using Xtensive.Modelling.Actions; - namespace Xtensive.Modelling.Comparison { /// /// comparison result. /// - [Serializable] public class NodeCollectionDifference : Difference, IDifference { /// - public new NodeCollection Source { - get { return (NodeCollection) base.Source; } - } + public new NodeCollection Source => (NodeCollection) base.Source; /// - public new NodeCollection Target { - get { return (NodeCollection) base.Target; } - } + public new NodeCollection Target => (NodeCollection) base.Target; /// /// Gets the item changes. /// - public List ItemChanges { get; private set; } + public List ItemChanges { get; } /// - public override bool HasChanges { - get { return ItemChanges.Count!=0; } - } + public override bool HasChanges => ItemChanges.Count != 0; /// protected override string ParametersToString() { var sb = new StringBuilder(); - sb.AppendFormat(Strings.ItemChangeCountFormat, ItemChanges.Count); + _ = sb.AppendFormat(Strings.ItemChangeCountFormat, ItemChanges.Count); foreach (var difference in ItemChanges) - sb.AppendLine().AppendFormat(Strings.ItemChangeFormat, difference); + _ = sb.AppendLine().AppendFormat(Strings.ItemChangeFormat, difference); return sb.ToString().Indent(ToString_IndentSize, false); } diff --git a/Orm/Xtensive.Orm/Modelling/Comparison/ValueDifference.cs b/Orm/Xtensive.Orm/Modelling/Comparison/ValueDifference.cs index 0051af00da..07ba4e50b5 100644 --- a/Orm/Xtensive.Orm/Modelling/Comparison/ValueDifference.cs +++ b/Orm/Xtensive.Orm/Modelling/Comparison/ValueDifference.cs @@ -15,19 +15,13 @@ namespace Xtensive.Modelling.Comparison /// /// Simple value comparison result. /// - [Serializable] public class ValueDifference : Difference { /// - public override bool HasChanges { - get { return true; } - } + public override bool HasChanges => true; /// - protected override string ParametersToString() - { - return "values differ"; - } + protected override string ParametersToString() => "values differ"; // Constructors diff --git a/Orm/Xtensive.Orm/Modelling/Nesting.cs b/Orm/Xtensive.Orm/Modelling/Nesting.cs index f88d817708..414fdbe804 100644 --- a/Orm/Xtensive.Orm/Modelling/Nesting.cs +++ b/Orm/Xtensive.Orm/Modelling/Nesting.cs @@ -7,11 +7,8 @@ using System; using System.Diagnostics; using System.Reflection; -using System.Runtime.Serialization; using Xtensive.Core; -using Xtensive.Reflection; - namespace Xtensive.Modelling { diff --git a/Orm/Xtensive.Orm/Modelling/Nesting{TNode, TParent, TProperty}.cs b/Orm/Xtensive.Orm/Modelling/Nesting{TNode, TParent, TProperty}.cs index f5aa7687db..cc660ea870 100644 --- a/Orm/Xtensive.Orm/Modelling/Nesting{TNode, TParent, TProperty}.cs +++ b/Orm/Xtensive.Orm/Modelling/Nesting{TNode, TParent, TProperty}.cs @@ -20,19 +20,14 @@ namespace Xtensive.Modelling /// The type of the node. /// The type of the parent. /// The type of the property. - [Serializable] public sealed class Nesting : Nesting where TNode: Node where TParent: Node where TProperty: IPathNode { - [NonSerialized] private PropertyInfo propertyInfo; - [NonSerialized] private bool isNestedToCollection; - [NonSerialized] private Func propertyGetter; - [NonSerialized] private Action propertySetter; /// @@ -71,7 +66,7 @@ internal override void Initialize() var tProperty = typeof (TProperty); propertyInfo = tParent.GetProperty(PropertyName); - if (propertyInfo==null) + if (propertyInfo is null) throw new InvalidOperationException(string.Format( Strings.ExBindingFailedForX, tParent.GetShortName()+"."+PropertyName)); if (propertyInfo.PropertyType!=tProperty) @@ -82,7 +77,7 @@ internal override void Initialize() // Getter var typedGetter = DelegateHelper.CreateGetMemberDelegate(PropertyName); - if (typedGetter==null) + if (typedGetter is null) throw new InvalidOperationException(string.Format( Strings.ExBindingFailedForX, propertyInfo.GetShortName(true))); propertyGetter = @@ -90,7 +85,7 @@ internal override void Initialize() // Setter var typedSetter = DelegateHelper.CreateSetMemberDelegate(PropertyName); - if (typedSetter==null) + if (typedSetter is null) throw new InvalidOperationException(string.Format( Strings.ExBindingFailedForX, propertyInfo.GetShortName(true))); propertySetter = diff --git a/Orm/Xtensive.Orm/Modelling/Node.cs b/Orm/Xtensive.Orm/Modelling/Node.cs index b19e46bbe3..3263ea3648 100644 --- a/Orm/Xtensive.Orm/Modelling/Node.cs +++ b/Orm/Xtensive.Orm/Modelling/Node.cs @@ -10,7 +10,6 @@ using System.ComponentModel; using System.Diagnostics; using System.Reflection; -using System.Runtime.Serialization; using Xtensive.Core; using Xtensive.Modelling.Actions; using Xtensive.Modelling.Attributes; @@ -24,37 +23,29 @@ namespace Xtensive.Modelling /// /// An abstract base class for model node. /// - [Serializable] [DebuggerDisplay("{Name}")] public abstract class Node : LockableBase, - INode, - IDeserializationCallback + INode { /// /// Path delimiter character. /// public static readonly char PathDelimiter = '/'; + /// + /// Same as but string. + /// public static readonly string PathDelimiterString = PathDelimiter.ToString(); /// /// Path escape character. /// public static readonly char PathEscape = '\\'; - [NonSerialized] - private static readonly ConcurrentDictionary> CachedPropertyAccessors = - new ConcurrentDictionary>(); - [NonSerialized] - private Node model; - [NonSerialized] - private string cachedPath; - [NonSerialized] - private Nesting nesting; - [NonSerialized] - private PropertyAccessorDictionary propertyAccessors; + private static readonly ConcurrentDictionary> CachedPropertyAccessors = new(); + internal Node parent; + private string cachedPath; private string name; private string escapedName; - private NodeState state; private int index; #region Properties @@ -77,10 +68,7 @@ public Node Parent { } /// - public Node Model { - [DebuggerStepThrough] - get { return model; } - } + public Node Model { get; private set; } /// [SystemProperty] @@ -89,26 +77,17 @@ public string Name [DebuggerStepThrough] get { return name; } [DebuggerStepThrough] - set { - Move(Parent, value, Index); - } + set => Move(Parent, value, Index); } /// public string EscapedName - { - [DebuggerStepThrough] - get { - if (escapedName==null) - escapedName = new[] {Name}.RevertibleJoin(PathEscape, PathDelimiter); - return escapedName; - } + { [DebuggerStepThrough] + get => escapedName ??= new[] { Name }.RevertibleJoin(PathEscape, PathDelimiter); } /// - public NodeState State { - get { return state; } - } + public NodeState State { get; private set; } /// [SystemProperty] @@ -125,13 +104,13 @@ public int Index /// public Nesting Nesting { [DebuggerStepThrough] - get { return nesting; } + get; private set; } /// public PropertyAccessorDictionary PropertyAccessors { [DebuggerStepThrough] - get { return propertyAccessors; } + get; private set; } /// @@ -166,7 +145,7 @@ public IPathNode GetNestedProperty(string propertyName) /// public IEnumerable> GetPathNodes(bool nestedOnly) { - foreach (var pair in propertyAccessors) { + foreach (var pair in PropertyAccessors) { string propertyName = pair.Key; var accessor = pair.Value; if (accessor.PropertyInfo.GetAttribute( @@ -347,15 +326,15 @@ public virtual Node Clone(Node newParent, string newName) var model = isModel ? null : (IModel) newParent.Model; Node node; if (isModel) { - node = TryConstructor(null, newName); + node = TryConstructor(newName); } else { - node = TryConstructor(model, newParent, newName); // Regular node - if (node == null) { - node = TryConstructor(model, newParent); // Unnamed node - } + //node = TryConstructor(currentType, newParent, newName, out var newParentType) // Regular node + // ?? TryConstructor(currentType, newParent, newParentType); // Unnamed node + // first Regular node and then Unnamed one as fallback + node = TryConstructor(newParent, newName); } - if (node==null) { + if (node is null) { throw new InvalidOperationException(string.Format( Strings.ExCannotFindConstructorToExecuteX, this)); } @@ -383,15 +362,15 @@ protected virtual void CopyPropertyValue(Node target, PropertyAccessor accessor) { var propertyName = accessor.PropertyInfo.Name; var nested = GetNestedProperty(propertyName); - if (nested!=null) { + if (nested is not null) { if (nested is NodeCollection collection) { foreach (Node newNode in collection) { - newNode.Clone(target, newNode.Name); + _ = newNode.Clone(target, newNode.Name); } } else { var newNode = (Node) nested; - newNode.Clone(target, newNode.Name); + _ = newNode.Clone(target, newNode.Name); } } else if (accessor.HasSetter) { @@ -509,7 +488,7 @@ protected virtual void PerformCreate() } } - state = NodeState.Live; + State = NodeState.Live; } /// @@ -659,7 +638,7 @@ protected virtual void PerformShift(int offset) /// protected virtual void PerformRemove(Node source) { - state = NodeState.Removed; + State = NodeState.Removed; if (source == this) { // Updating parents if (!Nesting.IsNestedToCollection) { @@ -785,7 +764,6 @@ protected void EnsureIsEditable() #region INotifyPropertyChanged methods /// - [field : NonSerialized] public event PropertyChangedEventHandler PropertyChanged; /// @@ -794,9 +772,7 @@ protected void EnsureIsEditable() /// Name of the property. protected virtual void OnPropertyChanged(string name) { - if (PropertyChanged != null) { - PropertyChanged.Invoke(this, new PropertyChangedEventArgs(name)); - } + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } /// @@ -812,7 +788,7 @@ protected void ChangeProperty(string name, T value, Action setter) EnsureIsEditable(); var pathNode = value as IPathNode; var model = Model; - if (pathNode!=null && model!=null && pathNode.Model!=model) { + if (pathNode is not null && model is not null && pathNode.Model!=model) { throw new ArgumentOutOfRangeException(nameof(value), Strings.ExPropertyValueMustBelongToTheSameModel); } @@ -845,7 +821,7 @@ public override void Lock(bool recursive) private void UpdateModel() { var p = Parent; - model = p == null ? (Node) (this as IModel) : p.Model; + Model = p == null ? (Node) (this as IModel) : p.Model; } private static PropertyAccessorDictionary GetPropertyAccessors(Type type) @@ -865,7 +841,7 @@ static Lazy PropertyAccessorExtractor(Type entityTyp const BindingFlags propertyBindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly; foreach (var p in entityType.GetProperties(propertyBindingFlags)) { - if (p.GetAttribute(AttributeSearchOptions.InheritNone) != null) { + if (p.GetAttribute(AttributeSearchOptions.InheritNone) is not null) { d.Add(p.Name, new PropertyAccessor(p)); } } @@ -877,11 +853,21 @@ static Lazy PropertyAccessorExtractor(Type entityTyp return CachedPropertyAccessors.GetOrAdd(type, PropertyAccessorExtractor).Value; } - private Node TryConstructor(IModel model, params object[] args) + private Node TryConstructor(string nameAsParameter) { - var argTypes = args.Select(a => a.GetType()).ToArray(); - var ci = GetType().GetConstructor(argTypes); - return ci == null ? null : (Node) ci.Invoke(args); + var ci = GetType().GetConstructor([WellKnownTypes.String]); + return ci is null ? null : (Node) ci.Invoke([nameAsParameter]); + } + + private Node TryConstructor(Node node, string nameAsParameter) + { + var instanceType = GetType(); + var nodeType = node.GetType(); + var ci = instanceType.GetConstructor([nodeType, WellKnownTypes.String]); + if (ci is not null) + return (Node) ci.Invoke([node, nameAsParameter]); + ci = instanceType.GetConstructor([nodeType]); + return ci is null ? null : (Node) ci.Invoke([node]); } #endregion @@ -900,12 +886,12 @@ private Node TryConstructor(IModel model, params object[] args) /// has returned . protected virtual void Initialize() { - nesting = CreateNesting(); - if (nesting == null) { + Nesting = CreateNesting(); + if (Nesting is null) { throw new InvalidOperationException(Strings.ExNoNesting); } - propertyAccessors = GetPropertyAccessors(GetType()); + PropertyAccessors = GetPropertyAccessors(GetType()); } #endregion @@ -941,7 +927,7 @@ public virtual void Dump() } // Everything else - foreach (var pair in propertyAccessors) { + foreach (var pair in PropertyAccessors) { var propertyName = pair.Key; var accessor = pair.Value; if (accessor.PropertyInfo.GetAttribute( @@ -955,7 +941,7 @@ public virtual void Dump() } var propertyType = - (propertyValue == null ? accessor.PropertyInfo.PropertyType : propertyValue.GetType()) + (propertyValue is null ? accessor.PropertyInfo.PropertyType : propertyValue.GetType()) .GetShortName(); var nested = GetNestedProperty(propertyName); if (nested != null) { @@ -982,7 +968,7 @@ public override string ToString() { var m = Model; var fullName = Path; - if (m != null) { + if (m is not null) { fullName = string.Concat(m.EscapedName, PathDelimiterString, fullName); } @@ -1021,25 +1007,5 @@ protected Node(Node parent, string name) Move(parent, name, ((NodeCollection) Nesting.PropertyGetter(parent)).Count); } } - - // Deserialization - - /// - void IDeserializationCallback.OnDeserialization(object sender) - { - if (nesting!=null) { - return; // Protects from multiple calls - } - - Initialize(); - if (Parent is IDeserializationCallback p) { - p.OnDeserialization(sender); - } - - UpdateModel(); - if (IsLocked) { - cachedPath = Path; - } - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Modelling/NodeCollection.cs b/Orm/Xtensive.Orm/Modelling/NodeCollection.cs index d5821197da..90114b9893 100644 --- a/Orm/Xtensive.Orm/Modelling/NodeCollection.cs +++ b/Orm/Xtensive.Orm/Modelling/NodeCollection.cs @@ -9,7 +9,6 @@ using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; -using System.Runtime.Serialization; using Xtensive.Core; namespace Xtensive.Modelling @@ -17,21 +16,16 @@ namespace Xtensive.Modelling /// /// An abstract base class for collection of nodes in model. /// - [Serializable] public abstract class NodeCollection : LockableBase, - INodeCollection, - IDeserializationCallback + INodeCollection { - [NonSerialized] - private string escapedName; - [NonSerialized] - private string cachedPath; - private Node parent; - private string name; - [NonSerialized] - private Dictionary nameIndex = new Dictionary(StringComparer.OrdinalIgnoreCase); - private readonly List list = new List(); + private readonly string escapedName; + private readonly Node parent; + private readonly string name; + private readonly Dictionary nameIndex = new(StringComparer.OrdinalIgnoreCase); + private readonly List list = new(); + private string cachedPath; #region Properties @@ -40,11 +34,9 @@ public abstract class NodeCollection : LockableBase, public string Name { [DebuggerStepThrough] - get { return name; } + get => name; [DebuggerStepThrough] - set { - throw Exceptions.AlreadyInitialized("Name"); - } + set => throw Exceptions.AlreadyInitialized("Name"); } /// @@ -69,7 +61,7 @@ public Node Parent /// public Node Model { [DebuggerStepThrough] - get { return Parent.Model; } + get => Parent.Model; } /// @@ -90,7 +82,7 @@ public string Path { /// public int Count { [DebuggerStepThrough] - get { return list.Count; } + get => list.Count; } #endregion @@ -98,9 +90,7 @@ public int Count { /// public Node this[int index] { [DebuggerStepThrough] - get { - return list[index]; - } + get => list[index]; } /// @@ -108,34 +98,26 @@ public Node this[int index] { public Node this[string name] { [DebuggerStepThrough] get { - Node result; - if (!TryGetValue(name, out result)) - throw new ArgumentException(String.Format(String.Format( - Strings.ExItemWithNameXIsNotFound, name))); - return result; + return TryGetValue(name, out var result) + ? result + : throw new ArgumentException(string.Format(Strings.ExItemWithNameXIsNotFound, name)); } } /// [DebuggerStepThrough] public bool TryGetValue(string name, out Node value) - { - return nameIndex.TryGetValue(name, out value); - } + => nameIndex.TryGetValue(name, out value); /// [DebuggerStepThrough] public bool Contains(string name) - { - return nameIndex.ContainsKey(name); - } + => nameIndex.ContainsKey(name); /// [DebuggerStepThrough] public virtual string GetTemporaryName() - { - return Guid.NewGuid().ToString(); - } + => Guid.NewGuid().ToString(); /// public IPathNode Resolve(string path) @@ -143,10 +125,9 @@ public IPathNode Resolve(string path) if (path.IsNullOrEmpty()) return this; var parts = path.RevertibleSplitFirstAndTail(Node.PathEscape, Node.PathDelimiter); - Node next; - if (!TryGetValue(parts.First, out next)) + if (!TryGetValue(parts.First, out var next)) return null; - if (parts.Second==null) + if (parts.Second is null) return next; return next.Resolve(parts.Second); } @@ -173,7 +154,6 @@ public void Clear() #region INotifyCollectionChanged, INotifyPropertyChanged members /// - [field : NonSerialized] public event NotifyCollectionChangedEventHandler CollectionChanged; /// @@ -182,10 +162,7 @@ public void Clear() /// The /// instance containing the event data. protected void OnCollectionChanged(NotifyCollectionChangedEventArgs args) - { - if (CollectionChanged!=null) - CollectionChanged.Invoke(this, args); - } + => CollectionChanged?.Invoke(this, args); #endregion @@ -193,10 +170,7 @@ protected void OnCollectionChanged(NotifyCollectionChangedEventArgs args) /// [DebuggerStepThrough] - public IEnumerator GetEnumerator() - { - return list.GetEnumerator(); - } + public IEnumerator GetEnumerator() => list.GetEnumerator(); #endregion @@ -236,7 +210,7 @@ internal void Add(Node node) if (list.Count > count) list.RemoveAt(count); if (nameIndex.Count > count) - nameIndex.Remove(name); + _ = nameIndex.Remove(name); throw; } } @@ -251,7 +225,7 @@ internal void Remove(Node node) string name = node.Name; try { list.RemoveAt(index); - nameIndex.Remove(name); + _ = nameIndex.Remove(name); OnCollectionChanged(new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Remove, index)); } @@ -300,7 +274,7 @@ internal void RemoveName(Node node) string name = node.Name; if (nameIndex[name]!=node) throw Exceptions.InternalError("Wrong NodeCollection.RemoveName arguments: nameIndex[node.Name]!=node!", CoreLog.Instance); - nameIndex.Remove(name); + _ = nameIndex.Remove(name); } /// Internal error. @@ -342,7 +316,7 @@ public override string ToString() { var m = Model; string fullName = Path; - if (m!=null) + if (m is not null) fullName = string.Concat(m.EscapedName, Node.PathDelimiterString, fullName); return string.Format(Strings.NodeInfoFormat, fullName, Count); } @@ -355,9 +329,6 @@ public override string ToString() /// is not initialized yet. protected virtual void Initialize() { - if (Name.IsNullOrEmpty()) - throw Exceptions.NotInitialized("Name"); - escapedName = new[] {Name}.RevertibleJoin(Node.PathEscape, Node.PathDelimiter); } @@ -373,23 +344,9 @@ protected NodeCollection(Node parent, string name) ArgumentValidator.EnsureArgumentNotNullOrEmpty(name, "name"); this.name = name; this.parent = parent ?? throw new ArgumentNullException(nameof(parent)); + escapedName = new[] { this.name }.RevertibleJoin(Node.PathEscape, Node.PathDelimiter); Initialize(); } - - // Deserialization - - /// - void IDeserializationCallback.OnDeserialization(object sender) - { - if (nameIndex!=null) - return; // Protects from multiple calls - Initialize(); - nameIndex = new Dictionary(Count, StringComparer.OrdinalIgnoreCase); - foreach (var node in list) - nameIndex.Add(node.Name, node); - if (IsLocked) - cachedPath = Path; - } } } diff --git a/Orm/Xtensive.Orm/Modelling/NodeCollection{TNode, TParent, TModel}.cs b/Orm/Xtensive.Orm/Modelling/NodeCollection{TNode, TParent, TModel}.cs index 23e93bb9a7..c7c4ff0022 100644 --- a/Orm/Xtensive.Orm/Modelling/NodeCollection{TNode, TParent, TModel}.cs +++ b/Orm/Xtensive.Orm/Modelling/NodeCollection{TNode, TParent, TModel}.cs @@ -17,7 +17,6 @@ namespace Xtensive.Modelling /// The type of the node. /// The type of the parent. /// The type of the model. - [Serializable] public abstract class NodeCollection : NodeCollection, INodeCollection where TNode : Node diff --git a/Orm/Xtensive.Orm/Modelling/Node{TParent, TModel}.cs b/Orm/Xtensive.Orm/Modelling/Node{TParent, TModel}.cs index e81bdc3b52..0071a352a0 100644 --- a/Orm/Xtensive.Orm/Modelling/Node{TParent, TModel}.cs +++ b/Orm/Xtensive.Orm/Modelling/Node{TParent, TModel}.cs @@ -16,7 +16,6 @@ namespace Xtensive.Modelling /// /// The type of the parent. /// The type of the model. - [Serializable] public abstract class Node : Node, INode where TParent : Node diff --git a/Orm/Xtensive.Orm/Modelling/PropertyAccessor.cs b/Orm/Xtensive.Orm/Modelling/PropertyAccessor.cs index 3d67db34ff..25fb86920e 100644 --- a/Orm/Xtensive.Orm/Modelling/PropertyAccessor.cs +++ b/Orm/Xtensive.Orm/Modelling/PropertyAccessor.cs @@ -22,21 +22,13 @@ public sealed class PropertyAccessor private Func getter; private Action setter; - [NonSerialized] private bool isSystem; - [NonSerialized] private int priority; - [NonSerialized] private bool ignoreInComparison; - [NonSerialized] private bool compareCaseInsensitive; - [NonSerialized] private bool isImmutable; - [NonSerialized] private bool isVolatile; - [NonSerialized] private bool recreateParent; - [NonSerialized] private Type dependencyRootType; /// @@ -140,7 +132,7 @@ public Action Setter { /// public IPathNode GetDependencyRoot(IPathNode source) { - if (source==null) + if (source is null) return null; if (DependencyRootType.IsAssignableFrom(source.GetType())) return source; @@ -160,12 +152,12 @@ private void Initialize() var tType = propertyInfo.DeclaringType; var tProperty = propertyInfo.PropertyType; var sa = propertyInfo.GetAttribute(AttributeSearchOptions.InheritNone); - isSystem = sa!=null; + isSystem = sa is not null; ignoreInComparison = isSystem; isVolatile = isSystem; isImmutable = false; var pa = propertyInfo.GetAttribute(AttributeSearchOptions.InheritNone); - if (pa!=null) { + if (pa is not null) { priority = pa.Priority; ignoreInComparison |= pa.IgnoreInComparison; isVolatile |= pa.IsVolatile; @@ -181,14 +173,14 @@ private void InnerInitialize() { Default = default(TProperty); var propertyInfo = PropertyInfo; - if (propertyInfo.GetGetMethod()!=null) { + if (propertyInfo.GetGetMethod() is not null) { var d = DelegateHelper.CreateGetMemberDelegate(PropertyInfo.Name); - if (d!=null) + if (d is not null) getter = o => d((TType) o); } if (propertyInfo.GetSetMethod()!=null) { var d = DelegateHelper.CreateSetMemberDelegate(PropertyInfo.Name); - if (d!=null) + if (d is not null) setter = (o,v) => d((TType) o, (TProperty) v); } } diff --git a/Orm/Xtensive.Orm/Modelling/PropertyAccessorDictionary.cs b/Orm/Xtensive.Orm/Modelling/PropertyAccessorDictionary.cs index 8e0d646394..8d10bf8b13 100644 --- a/Orm/Xtensive.Orm/Modelling/PropertyAccessorDictionary.cs +++ b/Orm/Xtensive.Orm/Modelling/PropertyAccessorDictionary.cs @@ -16,7 +16,6 @@ namespace Xtensive.Modelling /// Read-only dictionary. /// Items returned by its enumerator are ordered by item . /// - [Serializable] public sealed class PropertyAccessorDictionary : IReadOnlyDictionary { private readonly IReadOnlyDictionary items; diff --git a/Orm/Xtensive.Orm/Modelling/Validation/ValidationContext.cs b/Orm/Xtensive.Orm/Modelling/Validation/ValidationContext.cs index 2f51f66df2..1da7c4af6d 100644 --- a/Orm/Xtensive.Orm/Modelling/Validation/ValidationContext.cs +++ b/Orm/Xtensive.Orm/Modelling/Validation/ValidationContext.cs @@ -15,7 +15,6 @@ namespace Xtensive.Modelling.Validation /// /// Model validation context. /// - [Serializable] internal class ValidationContext : IContext { private readonly HashSet validated = new HashSet(); diff --git a/Orm/Xtensive.Orm/Orm/Attributes/AssociationAttribute.cs b/Orm/Xtensive.Orm/Orm/Attributes/AssociationAttribute.cs index 2332e4da47..7f0e82318e 100644 --- a/Orm/Xtensive.Orm/Orm/Attributes/AssociationAttribute.cs +++ b/Orm/Xtensive.Orm/Orm/Attributes/AssociationAttribute.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm /// Provides additional properties to association. /// This attribute can be applied on persistent properties of or type. /// - [Serializable] [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public sealed class AssociationAttribute : StorageAttribute { @@ -26,8 +25,8 @@ public sealed class AssociationAttribute : StorageAttribute /// public OnRemoveAction OnTargetRemove { - get { return onTargetRemove.HasValue ? onTargetRemove.Value : OnRemoveAction.Default; } - set { onTargetRemove = value; } + get => onTargetRemove ?? OnRemoveAction.Default; + set => onTargetRemove = value; } /// @@ -36,8 +35,8 @@ public OnRemoveAction OnTargetRemove /// public OnRemoveAction OnOwnerRemove { - get { return onOwnerRemove.HasValue ? onOwnerRemove.Value : OnRemoveAction.Default; } - set { onOwnerRemove = value; } + get => onOwnerRemove ?? OnRemoveAction.Default; + set => onOwnerRemove = value; } /// diff --git a/Orm/Xtensive.Orm/Orm/Attributes/CompilerAttribute.cs b/Orm/Xtensive.Orm/Orm/Attributes/CompilerAttribute.cs index 28eee111f9..939924d791 100644 --- a/Orm/Xtensive.Orm/Orm/Attributes/CompilerAttribute.cs +++ b/Orm/Xtensive.Orm/Orm/Attributes/CompilerAttribute.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2003-2010 Xtensive LLC. +// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Denis Krjuchkov @@ -14,7 +14,6 @@ namespace Xtensive.Orm /// Attribute for specifying method which acts as compiler /// for desired of type with specified . /// - [Serializable] [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] [MeansImplicitUse] public sealed class CompilerAttribute : Attribute diff --git a/Orm/Xtensive.Orm/Orm/Attributes/CompilerContainerAttribute.cs b/Orm/Xtensive.Orm/Orm/Attributes/CompilerContainerAttribute.cs index 9430593fdb..12cf5afd7c 100644 --- a/Orm/Xtensive.Orm/Orm/Attributes/CompilerContainerAttribute.cs +++ b/Orm/Xtensive.Orm/Orm/Attributes/CompilerContainerAttribute.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm /// /// Attribute for specifying user defined extension type. /// - [Serializable] [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] [MeansImplicitUse] public sealed class CompilerContainerAttribute : Attribute diff --git a/Orm/Xtensive.Orm/Orm/Attributes/FieldAttribute.cs b/Orm/Xtensive.Orm/Orm/Attributes/FieldAttribute.cs index e6ec16bfb2..b02480499c 100644 --- a/Orm/Xtensive.Orm/Orm/Attributes/FieldAttribute.cs +++ b/Orm/Xtensive.Orm/Orm/Attributes/FieldAttribute.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm /// Indicates that property is persistent field /// and defines its persistence-related properties. /// - [Serializable] [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public sealed class FieldAttribute : StorageAttribute { @@ -29,8 +28,8 @@ public sealed class FieldAttribute : StorageAttribute /// public bool Indexed { - get { return indexed ?? false; } - set { indexed = value; } + get => indexed ?? false; + set => indexed = value; } /// @@ -41,8 +40,8 @@ public bool Indexed /// public int Length { - get { return length ?? 0; } - set { length = value; } + get => length ?? 0; + set => length = value; } /// @@ -53,8 +52,8 @@ public int Length /// public int Scale { - get { return scale ?? 0; } - set { scale = value; } + get => scale ?? 0; + set => scale = value; } /// @@ -65,8 +64,8 @@ public int Scale /// public int Precision { - get { return precision ?? 0; } - set { precision = value; } + get => precision ?? 0; + set => precision = value; } /// @@ -81,8 +80,8 @@ public int Precision /// public bool Nullable { - get { return nullable ?? false; } - set { nullable = value; } + get => nullable ?? false; + set => nullable = value; } /// @@ -90,8 +89,8 @@ public bool Nullable /// public bool NullableOnUpgrade { - get { return nullableOnUpgrade ?? false; } - set { nullableOnUpgrade = value; } + get => nullableOnUpgrade ?? false; + set => nullableOnUpgrade = value; } /// @@ -116,8 +115,8 @@ public bool NullableOnUpgrade /// public bool LazyLoad { - get { return lazyLoad ?? false; } - set { lazyLoad = value; } + get => lazyLoad ?? false; + set => lazyLoad = value; } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Attributes/FieldMappingAttribute.cs b/Orm/Xtensive.Orm/Orm/Attributes/FieldMappingAttribute.cs index 28e0ed91f4..06f4d83b2f 100644 --- a/Orm/Xtensive.Orm/Orm/Attributes/FieldMappingAttribute.cs +++ b/Orm/Xtensive.Orm/Orm/Attributes/FieldMappingAttribute.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm /// /// Field mapping attribute. /// - [Serializable] [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public sealed class FieldMappingAttribute : StorageAttribute { diff --git a/Orm/Xtensive.Orm/Orm/Attributes/FullTextAttribute.cs b/Orm/Xtensive.Orm/Orm/Attributes/FullTextAttribute.cs index c348cdaa3f..e67d255f45 100644 --- a/Orm/Xtensive.Orm/Orm/Attributes/FullTextAttribute.cs +++ b/Orm/Xtensive.Orm/Orm/Attributes/FullTextAttribute.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm /// /// Indicates that persistent property must be included into full-text index. /// - [Serializable] [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public sealed class FullTextAttribute : StorageAttribute { diff --git a/Orm/Xtensive.Orm/Orm/Attributes/HierarchyRootAttribute.cs b/Orm/Xtensive.Orm/Orm/Attributes/HierarchyRootAttribute.cs index 0499da40fc..e2193bb014 100644 --- a/Orm/Xtensive.Orm/Orm/Attributes/HierarchyRootAttribute.cs +++ b/Orm/Xtensive.Orm/Orm/Attributes/HierarchyRootAttribute.cs @@ -37,7 +37,6 @@ namespace Xtensive.Orm /// public class Invoice : Document { ... } /// /// - [Serializable] [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] [BaseTypeRequired(typeof (Entity))] public sealed class HierarchyRootAttribute : StorageAttribute diff --git a/Orm/Xtensive.Orm/Orm/Attributes/IndexAttribute.cs b/Orm/Xtensive.Orm/Orm/Attributes/IndexAttribute.cs index c5fe78df5f..9a1ef44325 100644 --- a/Orm/Xtensive.Orm/Orm/Attributes/IndexAttribute.cs +++ b/Orm/Xtensive.Orm/Orm/Attributes/IndexAttribute.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm /// /// /// - [Serializable] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] public sealed class IndexAttribute : StorageAttribute { @@ -43,8 +42,8 @@ public sealed class IndexAttribute : StorageAttribute /// public double FillFactor { - get { return fillFactor ?? 0; } - set { fillFactor = value; } + get => fillFactor ?? 0; + set => fillFactor = value; } /// @@ -52,8 +51,8 @@ public double FillFactor /// public bool Unique { - get { return unique ?? false; } - set { unique = value; } + get => unique ?? false; + set => unique = value; } /// diff --git a/Orm/Xtensive.Orm/Orm/Attributes/KeyAttribute.cs b/Orm/Xtensive.Orm/Orm/Attributes/KeyAttribute.cs index 75373077e5..7fb22ef8cc 100644 --- a/Orm/Xtensive.Orm/Orm/Attributes/KeyAttribute.cs +++ b/Orm/Xtensive.Orm/Orm/Attributes/KeyAttribute.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm /// Marks persistent property as a part of primary key and /// specifies and of the field in key. /// - [Serializable] [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public sealed class KeyAttribute : StorageAttribute { diff --git a/Orm/Xtensive.Orm/Orm/Attributes/KeyGeneratorAttribute.cs b/Orm/Xtensive.Orm/Orm/Attributes/KeyGeneratorAttribute.cs index 92adb8eda5..5471d1ae29 100644 --- a/Orm/Xtensive.Orm/Orm/Attributes/KeyGeneratorAttribute.cs +++ b/Orm/Xtensive.Orm/Orm/Attributes/KeyGeneratorAttribute.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm /// /// Configures key generator for the hierarchy. /// - [Serializable] [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public sealed class KeyGeneratorAttribute : StorageAttribute { @@ -46,7 +45,7 @@ public KeyGeneratorAttribute() /// can be null. public KeyGeneratorAttribute(Type type) { - if (type==null) + if (type is null) Kind = KeyGeneratorKind.None; else { Kind = KeyGeneratorKind.Custom; diff --git a/Orm/Xtensive.Orm/Orm/Attributes/MaterializedViewAttribute.cs b/Orm/Xtensive.Orm/Orm/Attributes/MaterializedViewAttribute.cs index 2ca7dd548b..7a551230f7 100644 --- a/Orm/Xtensive.Orm/Orm/Attributes/MaterializedViewAttribute.cs +++ b/Orm/Xtensive.Orm/Orm/Attributes/MaterializedViewAttribute.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm /// Indicates that materialized view should be created for /// the interface type it is applied on. /// - [Serializable] [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = false)] public sealed class MaterializedViewAttribute : StorageAttribute { diff --git a/Orm/Xtensive.Orm/Orm/Attributes/StorageAttribute.cs b/Orm/Xtensive.Orm/Orm/Attributes/StorageAttribute.cs index 168b586543..bae2ae446b 100644 --- a/Orm/Xtensive.Orm/Orm/Attributes/StorageAttribute.cs +++ b/Orm/Xtensive.Orm/Orm/Attributes/StorageAttribute.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm /// /// Base class for all storage-related attributes. /// - [Serializable] public abstract class StorageAttribute: Attribute { } diff --git a/Orm/Xtensive.Orm/Orm/Attributes/TableMappingAttribute.cs b/Orm/Xtensive.Orm/Orm/Attributes/TableMappingAttribute.cs index d977b6773d..03daf2aa75 100644 --- a/Orm/Xtensive.Orm/Orm/Attributes/TableMappingAttribute.cs +++ b/Orm/Xtensive.Orm/Orm/Attributes/TableMappingAttribute.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm /// /// Table mapping attribute. /// - [Serializable] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public sealed class TableMappingAttribute : StorageAttribute diff --git a/Orm/Xtensive.Orm/Orm/Attributes/TypeAttribute.cs b/Orm/Xtensive.Orm/Orm/Attributes/TypeAttribute.cs index b382a6109b..559275c77d 100644 --- a/Orm/Xtensive.Orm/Orm/Attributes/TypeAttribute.cs +++ b/Orm/Xtensive.Orm/Orm/Attributes/TypeAttribute.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2003-2010 Xtensive LLC. +// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Denis Krjuchkov @@ -13,7 +13,6 @@ namespace Xtensive.Orm /// Attribute for specifying parameter types of compiled method. /// See for details. /// - [Serializable] [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = false, Inherited = false)] public sealed class TypeAttribute : Attribute { diff --git a/Orm/Xtensive.Orm/Orm/Attributes/TypeDiscriminatorAttribute.cs b/Orm/Xtensive.Orm/Orm/Attributes/TypeDiscriminatorAttribute.cs index 2b37aabed7..975c342372 100644 --- a/Orm/Xtensive.Orm/Orm/Attributes/TypeDiscriminatorAttribute.cs +++ b/Orm/Xtensive.Orm/Orm/Attributes/TypeDiscriminatorAttribute.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm /// /// Marks persistent property as type discriminator. /// - [Serializable] [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public sealed class TypeDiscriminatorAttribute : StorageAttribute { diff --git a/Orm/Xtensive.Orm/Orm/Attributes/TypeDiscriminatorValueAttribute.cs b/Orm/Xtensive.Orm/Orm/Attributes/TypeDiscriminatorValueAttribute.cs index 1bcbee06e6..6c6ea50f6b 100644 --- a/Orm/Xtensive.Orm/Orm/Attributes/TypeDiscriminatorValueAttribute.cs +++ b/Orm/Xtensive.Orm/Orm/Attributes/TypeDiscriminatorValueAttribute.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm /// /// Specifies value of type discriminator for the entity type it is applied to. /// - [Serializable] [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public sealed class TypeDiscriminatorValueAttribute : StorageAttribute { diff --git a/Orm/Xtensive.Orm/Orm/Attributes/VersionAttribute.cs b/Orm/Xtensive.Orm/Orm/Attributes/VersionAttribute.cs index 4e1dea0dbd..d399075aba 100644 --- a/Orm/Xtensive.Orm/Orm/Attributes/VersionAttribute.cs +++ b/Orm/Xtensive.Orm/Orm/Attributes/VersionAttribute.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm /// /// Marks persistent property as a part of version. /// - [Serializable] [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public sealed class VersionAttribute : StorageAttribute { diff --git a/Orm/Xtensive.Orm/Orm/Attributes/VersionMode.cs b/Orm/Xtensive.Orm/Orm/Attributes/VersionMode.cs index edaa0c8fcf..5a8a37ffeb 100644 --- a/Orm/Xtensive.Orm/Orm/Attributes/VersionMode.cs +++ b/Orm/Xtensive.Orm/Orm/Attributes/VersionMode.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm /// /// Specifies version check mode for particular persistent property. Applied via . /// - [Serializable] public enum VersionMode { /// diff --git a/Orm/Xtensive.Orm/Orm/Building/Definitions/DomainModelDef.cs b/Orm/Xtensive.Orm/Orm/Building/Definitions/DomainModelDef.cs index f3c20abc14..aafe1050fb 100644 --- a/Orm/Xtensive.Orm/Orm/Building/Definitions/DomainModelDef.cs +++ b/Orm/Xtensive.Orm/Orm/Building/Definitions/DomainModelDef.cs @@ -20,7 +20,6 @@ namespace Xtensive.Orm.Building.Definitions /// Defines the whole model. /// The root definition. /// - [Serializable] public sealed class DomainModelDef : Node { private readonly ModelDefBuilder builder; @@ -31,7 +30,7 @@ public sealed class DomainModelDef : Node /// /// Gets the instances contained in this instance. /// - public TypeDefCollection Types { get { return types; } } + public TypeDefCollection Types => types; /// /// Gets the collection of instances contained in this instance. @@ -41,7 +40,7 @@ public sealed class DomainModelDef : Node /// /// Gets the collection of instances contained in this instance. /// - public FullTextIndexDefCollection FullTextIndexes { get { return fullTextIndexes; } } + public FullTextIndexDefCollection FullTextIndexes => fullTextIndexes; /// /// Defines new and adds it to instance. @@ -81,8 +80,8 @@ private void OnTypesCleared(object sender, TypeDefCollectionClearedEventArgs e) private void OnTypeRemoved(object sender, TypeDefCollectionChangedEventArgs e) { - HierarchyDef hd = Hierarchies.TryGetValue(e.Item); - if (hd != null) + var hd = Hierarchies.TryGetValue(e.Item); + if (hd is not null) Hierarchies.Remove(hd); } diff --git a/Orm/Xtensive.Orm/Orm/Building/Definitions/FieldDef.cs b/Orm/Xtensive.Orm/Orm/Building/Definitions/FieldDef.cs index 3fb5d381fd..57f001016f 100644 --- a/Orm/Xtensive.Orm/Orm/Building/Definitions/FieldDef.cs +++ b/Orm/Xtensive.Orm/Orm/Building/Definitions/FieldDef.cs @@ -21,10 +21,10 @@ namespace Xtensive.Orm.Building.Definitions /// Defines a signle persistent field. /// [DebuggerDisplay("{Name}; Attributes = {Attributes}")] - [Serializable] public class FieldDef : MappedNode { private readonly PropertyInfo underlyingProperty; + private readonly Validator validator; private FieldAttributes attributes; private OnRemoveAction? onTargetRemove; private OnRemoveAction? onOwnerRemove; @@ -34,7 +34,6 @@ public class FieldDef : MappedNode private int? precision; private object defaultValue; private string defaultSqlExpression; - private Validator validator; /// /// Gets or sets the maximal length of the field. diff --git a/Orm/Xtensive.Orm/Orm/Building/Definitions/FullTextFieldDef.cs b/Orm/Xtensive.Orm/Orm/Building/Definitions/FullTextFieldDef.cs index 6addafb995..3eb3ff1912 100644 --- a/Orm/Xtensive.Orm/Orm/Building/Definitions/FullTextFieldDef.cs +++ b/Orm/Xtensive.Orm/Orm/Building/Definitions/FullTextFieldDef.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Building.Definitions /// /// Defines a single field inside full-text index. /// - [Serializable] [DebuggerDisplay("{Name}")] public class FullTextFieldDef : Node { diff --git a/Orm/Xtensive.Orm/Orm/Building/Definitions/FullTextIndexDef.cs b/Orm/Xtensive.Orm/Orm/Building/Definitions/FullTextIndexDef.cs index b00088b151..319640bf05 100644 --- a/Orm/Xtensive.Orm/Orm/Building/Definitions/FullTextIndexDef.cs +++ b/Orm/Xtensive.Orm/Orm/Building/Definitions/FullTextIndexDef.cs @@ -15,11 +15,10 @@ namespace Xtensive.Orm.Building.Definitions /// /// Defines full-text index. /// - [Serializable] public sealed class FullTextIndexDef : Node { - public TypeDef Type { get; private set; } - public List Fields { get; private set; } + public TypeDef Type { get; } + public List Fields { get; } // Constructors diff --git a/Orm/Xtensive.Orm/Orm/Building/Definitions/FullTextIndexDefCollection.cs b/Orm/Xtensive.Orm/Orm/Building/Definitions/FullTextIndexDefCollection.cs index 83039a4964..64c0dcca71 100644 --- a/Orm/Xtensive.Orm/Orm/Building/Definitions/FullTextIndexDefCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Building/Definitions/FullTextIndexDefCollection.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Building.Definitions /// /// A collection of items. /// - [Serializable] public class FullTextIndexDefCollection : CollectionBaseSlim { /// diff --git a/Orm/Xtensive.Orm/Orm/Building/Definitions/HierarchyDef.cs b/Orm/Xtensive.Orm/Orm/Building/Definitions/HierarchyDef.cs index fe0ce9dfb8..552e67b056 100644 --- a/Orm/Xtensive.Orm/Orm/Building/Definitions/HierarchyDef.cs +++ b/Orm/Xtensive.Orm/Orm/Building/Definitions/HierarchyDef.cs @@ -14,18 +14,17 @@ namespace Xtensive.Orm.Building.Definitions /// /// Defines a signle persistent type hierarchy. /// - [Serializable] public sealed class HierarchyDef : Node { /// /// Gets the root of the hierarchy. /// - public TypeDef Root { get; private set; } + public TypeDef Root { get; } /// /// Gets the fields that are included in the key for this hierarchy. /// - public List KeyFields { get; private set; } + public List KeyFields { get; } /// /// Gets the for this hierarchy. diff --git a/Orm/Xtensive.Orm/Orm/Building/Definitions/IndexDef.cs b/Orm/Xtensive.Orm/Orm/Building/Definitions/IndexDef.cs index aaa0d485e2..a129bacd42 100644 --- a/Orm/Xtensive.Orm/Orm/Building/Definitions/IndexDef.cs +++ b/Orm/Xtensive.Orm/Orm/Building/Definitions/IndexDef.cs @@ -19,7 +19,6 @@ namespace Xtensive.Orm.Building.Definitions /// Defines a single index. /// [DebuggerDisplay("{Name}; Attributes = {Attributes}.")] - [Serializable] public sealed class IndexDef : MappedNode { /// @@ -27,12 +26,13 @@ public sealed class IndexDef : MappedNode /// public const double DefaultFillFactor = 0.8; + private readonly DirectionCollection keyFields = new(); + private readonly Collection includedFields = new(); + private readonly Validator validator; + private IndexAttributes attributes; private LambdaExpression filterExpression; private double fillFactor = DefaultFillFactor; - private readonly DirectionCollection keyFields = new DirectionCollection(); - private Collection includedFields = new Collection(); - private readonly Validator validator; /// /// Gets that this index is bound to. diff --git a/Orm/Xtensive.Orm/Orm/Building/Definitions/TypeDef.cs b/Orm/Xtensive.Orm/Orm/Building/Definitions/TypeDef.cs index ddac1f5651..95e5ef61f5 100644 --- a/Orm/Xtensive.Orm/Orm/Building/Definitions/TypeDef.cs +++ b/Orm/Xtensive.Orm/Orm/Building/Definitions/TypeDef.cs @@ -22,7 +22,6 @@ namespace Xtensive.Orm.Building.Definitions /// Defines a single persistent type. /// [DebuggerDisplay("{UnderlyingType}")] - [Serializable] public sealed class TypeDef : SchemaMappedNode { private readonly ModelDefBuilder builder; diff --git a/Orm/Xtensive.Orm/Orm/Building/DependencyGraph/Edge.cs b/Orm/Xtensive.Orm/Orm/Building/DependencyGraph/Edge.cs index 530e76fc4f..a59fe027f4 100644 --- a/Orm/Xtensive.Orm/Orm/Building/DependencyGraph/Edge.cs +++ b/Orm/Xtensive.Orm/Orm/Building/DependencyGraph/Edge.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Building.DependencyGraph { - [Serializable] internal readonly struct Edge : IEquatable> { public Node Tail { get; } @@ -36,10 +35,16 @@ public override bool Equals(object obj) => obj is Edge other && Equals(other); /// - public static bool operator ==(Edge left, Edge right) => left.Equals(right); + public static bool operator ==(Edge left, Edge right) + { + return left.Equals(right); + } /// - public static bool operator !=(Edge left, Edge right) => !left.Equals(right); + public static bool operator !=(Edge left, Edge right) + { + return !left.Equals(right); + } /// public override string ToString() diff --git a/Orm/Xtensive.Orm/Orm/Building/DependencyGraph/EdgeKind.cs b/Orm/Xtensive.Orm/Orm/Building/DependencyGraph/EdgeKind.cs index 7b5797dd55..8e6585b73a 100644 --- a/Orm/Xtensive.Orm/Orm/Building/DependencyGraph/EdgeKind.cs +++ b/Orm/Xtensive.Orm/Orm/Building/DependencyGraph/EdgeKind.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Building.DependencyGraph { - [Serializable] internal enum EdgeKind { Default = Reference, diff --git a/Orm/Xtensive.Orm/Orm/Building/DependencyGraph/EdgeWeight.cs b/Orm/Xtensive.Orm/Orm/Building/DependencyGraph/EdgeWeight.cs index b0b36f33bf..491a987eb6 100644 --- a/Orm/Xtensive.Orm/Orm/Building/DependencyGraph/EdgeWeight.cs +++ b/Orm/Xtensive.Orm/Orm/Building/DependencyGraph/EdgeWeight.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Building.DependencyGraph { - [Serializable] internal enum EdgeWeight { Default = Normal, diff --git a/Orm/Xtensive.Orm/Orm/Building/DependencyGraph/Graph.cs b/Orm/Xtensive.Orm/Orm/Building/DependencyGraph/Graph.cs index 64f3665322..dfc3b6ae48 100644 --- a/Orm/Xtensive.Orm/Orm/Building/DependencyGraph/Graph.cs +++ b/Orm/Xtensive.Orm/Orm/Building/DependencyGraph/Graph.cs @@ -9,19 +9,15 @@ namespace Xtensive.Orm.Building.DependencyGraph { - [Serializable] internal class Graph { private readonly Dictionary> nodeTable = new Dictionary>(); - public IEnumerable> Nodes { - get { return nodeTable.Values; } - } + public IEnumerable> Nodes => nodeTable.Values; public Node TryGetNode(TValue value) { - Node result; - if (!nodeTable.TryGetValue(value, out result)) + if (!nodeTable.TryGetValue(value, out var result)) return null; return result; } @@ -41,8 +37,8 @@ public Edge AddEdge(TValue tail, TValue head, EdgeKind kind, EdgeWeight var tailNode = GetNode(tail); var headNode = GetNode(head); var edge = new Edge(tailNode, headNode, kind, weight); - tailNode.OutgoingEdges.Add(edge); - headNode.IncomingEdges.Add(edge); + _ = tailNode.OutgoingEdges.Add(edge); + _ = headNode.IncomingEdges.Add(edge); return edge; } @@ -53,13 +49,13 @@ public void RemoveNode(TValue value) return; foreach (var edge in node.IncomingEdges) - edge.Tail.OutgoingEdges.Remove(edge); + _ = edge.Tail.OutgoingEdges.Remove(edge); foreach (var edge in node.OutgoingEdges) - edge.Head.IncomingEdges.Remove(edge); + _ = edge.Head.IncomingEdges.Remove(edge); node.IncomingEdges.Clear(); node.OutgoingEdges.Clear(); - nodeTable.Remove(value); + _ = nodeTable.Remove(value); } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Building/DependencyGraph/Node.cs b/Orm/Xtensive.Orm/Orm/Building/DependencyGraph/Node.cs index dffe663e6a..16894c7fc5 100644 --- a/Orm/Xtensive.Orm/Orm/Building/DependencyGraph/Node.cs +++ b/Orm/Xtensive.Orm/Orm/Building/DependencyGraph/Node.cs @@ -9,14 +9,13 @@ namespace Xtensive.Orm.Building.DependencyGraph { - [Serializable] internal class Node { - public TValue Value { get; private set; } + public TValue Value { get; } - public HashSet> OutgoingEdges { get; private set; } + public HashSet> OutgoingEdges { get; } - public HashSet> IncomingEdges { get; private set; } + public HashSet> IncomingEdges { get; } /// public override string ToString() diff --git a/Orm/Xtensive.Orm/Orm/Building/PrefetchActionContainer.cs b/Orm/Xtensive.Orm/Orm/Building/PrefetchActionContainer.cs index 324b31a94b..a8655222ad 100644 --- a/Orm/Xtensive.Orm/Orm/Building/PrefetchActionContainer.cs +++ b/Orm/Xtensive.Orm/Orm/Building/PrefetchActionContainer.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Building { - [Serializable] internal sealed class PrefetchActionContainer { private readonly TypeInfo type; @@ -32,7 +31,7 @@ public Action> BuildPrefetchAction(IEnumerable< private void Prefetch(SessionHandler sh, IEnumerable keys) { foreach (var key in keys) - sh.Prefetch(key, type, fields); + _ = sh.Prefetch(key, type, fields); } public PrefetchActionContainer(TypeInfo type) diff --git a/Orm/Xtensive.Orm/Orm/Configuration/ConfigurationBase.cs b/Orm/Xtensive.Orm/Orm/Configuration/ConfigurationBase.cs index 8b10852968..58c3e2fcb4 100644 --- a/Orm/Xtensive.Orm/Orm/Configuration/ConfigurationBase.cs +++ b/Orm/Xtensive.Orm/Orm/Configuration/ConfigurationBase.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Configuration /// /// Base class for configuration. /// - [Serializable] public abstract class ConfigurationBase: LockableBase, ICloneable { /// diff --git a/Orm/Xtensive.Orm/Orm/Configuration/DomainConfiguration.cs b/Orm/Xtensive.Orm/Orm/Configuration/DomainConfiguration.cs index 9b13404aef..d877bf42d8 100644 --- a/Orm/Xtensive.Orm/Orm/Configuration/DomainConfiguration.cs +++ b/Orm/Xtensive.Orm/Orm/Configuration/DomainConfiguration.cs @@ -18,7 +18,6 @@ namespace Xtensive.Orm.Configuration /// /// The configuration of the . /// - [Serializable] public class DomainConfiguration : ConfigurationBase { #region Defaults diff --git a/Orm/Xtensive.Orm/Orm/Configuration/DomainTypeRegistry.cs b/Orm/Xtensive.Orm/Orm/Configuration/DomainTypeRegistry.cs index 5040c96157..bcb8ccde6e 100644 --- a/Orm/Xtensive.Orm/Orm/Configuration/DomainTypeRegistry.cs +++ b/Orm/Xtensive.Orm/Orm/Configuration/DomainTypeRegistry.cs @@ -18,7 +18,6 @@ namespace Xtensive.Orm.Configuration /// An implementation of /// used by the . /// - [Serializable] public class DomainTypeRegistry : TypeRegistry { private readonly static Type iDomainServiceType = typeof(IDomainService); diff --git a/Orm/Xtensive.Orm/Orm/Configuration/ExtensionConfigurationCollection.cs b/Orm/Xtensive.Orm/Orm/Configuration/ExtensionConfigurationCollection.cs index d14b3af2e0..02cf1070f8 100644 --- a/Orm/Xtensive.Orm/Orm/Configuration/ExtensionConfigurationCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Configuration/ExtensionConfigurationCollection.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Configuration /// /// Collection of configurations of extensions. /// - [Serializable] public sealed class ExtensionConfigurationCollection : LockableBase, IEnumerable { diff --git a/Orm/Xtensive.Orm/Orm/Configuration/LetterCasePolicy.cs b/Orm/Xtensive.Orm/Orm/Configuration/LetterCasePolicy.cs index b8c3757da0..f87bc20131 100644 --- a/Orm/Xtensive.Orm/Orm/Configuration/LetterCasePolicy.cs +++ b/Orm/Xtensive.Orm/Orm/Configuration/LetterCasePolicy.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Configuration /// /// Enumerates all possible modification types to names. /// - [Serializable] public enum LetterCasePolicy { /// diff --git a/Orm/Xtensive.Orm/Orm/Configuration/NameMappingCollection.cs b/Orm/Xtensive.Orm/Orm/Configuration/NameMappingCollection.cs index 2b96cb0308..1859279d16 100644 --- a/Orm/Xtensive.Orm/Orm/Configuration/NameMappingCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Configuration/NameMappingCollection.cs @@ -15,20 +15,19 @@ namespace Xtensive.Orm.Configuration /// /// Name mapping collection. /// - [Serializable] public class NameMappingCollection : LockableBase, IEnumerable>, ICloneable { /// /// Gets empty . /// - public static readonly NameMappingCollection Empty = new NameMappingCollection(); + public static readonly NameMappingCollection Empty = new(); - private readonly Dictionary items = new Dictionary(); + private readonly Dictionary items = new(); /// /// Gets number of elements in this collection. /// - public int Count { get { return items.Count; } } + public int Count => items.Count; /// /// Adds mapping between @@ -62,8 +61,7 @@ public bool Remove([NotNull] string originalName) public string Apply([NotNull] string name) { ArgumentValidator.EnsureArgumentNotNullOrEmpty(name, "name"); - string result; - if (items.TryGetValue(name, out result)) + if (items.TryGetValue(name, out var result)) return result; return name; } @@ -81,19 +79,13 @@ public void Clear() /// Returns an enumerator that iterates through the collection. /// /// A that can be used to iterate through the collection. - public IEnumerator> GetEnumerator() - { - return items.GetEnumerator(); - } + public IEnumerator> GetEnumerator() => items.GetEnumerator(); /// /// Returns an enumerator that iterates through a collection. /// /// An object that can be used to iterate through the collection. - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); /// /// Creates clone of this instance. diff --git a/Orm/Xtensive.Orm/Orm/Configuration/NamespacePolicy.cs b/Orm/Xtensive.Orm/Orm/Configuration/NamespacePolicy.cs index d05d6a9d5b..ab68cd5dcd 100644 --- a/Orm/Xtensive.Orm/Orm/Configuration/NamespacePolicy.cs +++ b/Orm/Xtensive.Orm/Orm/Configuration/NamespacePolicy.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Configuration /// /// Enumerates all possible namespace treatment options in naming policy. /// - [Serializable] public enum NamespacePolicy { /// diff --git a/Orm/Xtensive.Orm/Orm/Configuration/NamingConvention.cs b/Orm/Xtensive.Orm/Orm/Configuration/NamingConvention.cs index 8929073ee1..b3ce7a1f75 100644 --- a/Orm/Xtensive.Orm/Orm/Configuration/NamingConvention.cs +++ b/Orm/Xtensive.Orm/Orm/Configuration/NamingConvention.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Configuration /// /// A set of rules for model definition objects naming. /// - [Serializable] public class NamingConvention : LockableBase, ICloneable { diff --git a/Orm/Xtensive.Orm/Orm/Configuration/NamingRules.cs b/Orm/Xtensive.Orm/Orm/Configuration/NamingRules.cs index b7e3651ed1..c2d6eac938 100644 --- a/Orm/Xtensive.Orm/Orm/Configuration/NamingRules.cs +++ b/Orm/Xtensive.Orm/Orm/Configuration/NamingRules.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Configuration /// Miscellaneous naming policy rules. /// [Flags] - [Serializable] public enum NamingRules { /// diff --git a/Orm/Xtensive.Orm/Orm/Configuration/NodeConfiguration.cs b/Orm/Xtensive.Orm/Orm/Configuration/NodeConfiguration.cs index 617146e66e..01af3b916d 100644 --- a/Orm/Xtensive.Orm/Orm/Configuration/NodeConfiguration.cs +++ b/Orm/Xtensive.Orm/Orm/Configuration/NodeConfiguration.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Configuration /// /// Storage node configuration. /// - [Serializable] public class NodeConfiguration : LockableBase, ICloneable { private string nodeId; diff --git a/Orm/Xtensive.Orm/Orm/Configuration/ReaderPreloadingPolicy.cs b/Orm/Xtensive.Orm/Orm/Configuration/ReaderPreloadingPolicy.cs index d8057d9f15..4c62feb7d3 100644 --- a/Orm/Xtensive.Orm/Orm/Configuration/ReaderPreloadingPolicy.cs +++ b/Orm/Xtensive.Orm/Orm/Configuration/ReaderPreloadingPolicy.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Configuration /// /// A policy for dealing with database readers. /// - [Serializable] public enum ReaderPreloadingPolicy { /// diff --git a/Orm/Xtensive.Orm/Orm/Configuration/SessionConfiguration.cs b/Orm/Xtensive.Orm/Orm/Configuration/SessionConfiguration.cs index a191a6bc6f..750e661774 100644 --- a/Orm/Xtensive.Orm/Orm/Configuration/SessionConfiguration.cs +++ b/Orm/Xtensive.Orm/Orm/Configuration/SessionConfiguration.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Configuration /// /// configuration. /// - [Serializable] public class SessionConfiguration : ConfigurationBase { #region Defaults diff --git a/Orm/Xtensive.Orm/Orm/Configuration/SessionConfigurationCollection.cs b/Orm/Xtensive.Orm/Orm/Configuration/SessionConfigurationCollection.cs index b9d22dfc56..0385900f9c 100644 --- a/Orm/Xtensive.Orm/Orm/Configuration/SessionConfigurationCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Configuration/SessionConfigurationCollection.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Configuration /// /// collection. /// - [Serializable] public class SessionConfigurationCollection : CollectionBaseSlim, ICloneable { @@ -29,34 +28,22 @@ public class SessionConfigurationCollection : CollectionBaseSlim /// Gets the default session configuration. /// - public SessionConfiguration Default - { - get { return GetConfiguration(WellKnown.Sessions.Default, @default); } - } + public SessionConfiguration Default => GetConfiguration(WellKnown.Sessions.Default, @default); /// /// Gets the system session configuration. /// - public SessionConfiguration System - { - get { return GetConfiguration(WellKnown.Sessions.System, system); } - } + public SessionConfiguration System => GetConfiguration(WellKnown.Sessions.System, system); /// /// Gets the service session configuration. /// - public SessionConfiguration Service - { - get { return GetConfiguration(WellKnown.Sessions.Service, service); } - } + public SessionConfiguration Service => GetConfiguration(WellKnown.Sessions.Service, service); /// /// Gets the key generator session configuration. /// - public SessionConfiguration KeyGenerator - { - get { return GetConfiguration(WellKnown.Sessions.KeyGenerator, keyGenerator); } - } + public SessionConfiguration KeyGenerator => GetConfiguration(WellKnown.Sessions.KeyGenerator, keyGenerator); /// /// Gets the element with the specified name. @@ -93,7 +80,7 @@ private void EnsureItemIsValid(SessionConfiguration item) { ArgumentValidator.EnsureArgumentNotNullOrEmpty(item.Name, "SessionConfiguration.Name"); var current = this[item.Name]; - if (current != null) + if (current is not null) throw new InvalidOperationException(string.Format(Strings.ExConfigurationWithXNameAlreadyRegistered, current.Name)); } @@ -165,14 +152,12 @@ public SessionConfigurationCollection Clone() } private SessionConfiguration GetConfiguration(string name, SessionConfiguration fallback) - { - return !IsLocked ? this[name] : fallback; - } + => !IsLocked ? this[name] : fallback; private SessionConfiguration BuildConfiguration(string name) { var result = this[name]; - if (result!=null) + if (result is not null) return result; result = new SessionConfiguration(name); diff --git a/Orm/Xtensive.Orm/Orm/ConnectionInfo.cs b/Orm/Xtensive.Orm/Orm/ConnectionInfo.cs index 5ddbde3087..961f10db41 100644 --- a/Orm/Xtensive.Orm/Orm/ConnectionInfo.cs +++ b/Orm/Xtensive.Orm/Orm/ConnectionInfo.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm /// A wrapper representing connection information. /// Connection can be specified by either or . /// - [Serializable] public sealed class ConnectionInfo : IEquatable { private const string ToStringFormat = "[{0}] {1}"; @@ -37,7 +36,7 @@ public sealed class ConnectionInfo : IEquatable /// public override string ToString() { - return ConnectionUrl!=null + return ConnectionUrl is not null ? ConnectionUrl.ToString() : string.Format(ToStringFormat, Provider, ConnectionString); } diff --git a/Orm/Xtensive.Orm/Orm/DelayedQuery.cs b/Orm/Xtensive.Orm/Orm/DelayedQuery.cs index ffcd65f8d8..c1b1c3c7b5 100644 --- a/Orm/Xtensive.Orm/Orm/DelayedQuery.cs +++ b/Orm/Xtensive.Orm/Orm/DelayedQuery.cs @@ -17,7 +17,6 @@ namespace Xtensive.Orm.Internals /// /// Abstract base for both sequence and scalar delayed queries. /// - [Serializable] public abstract class DelayedQuery { private readonly ParameterContext parameterContext; @@ -51,8 +50,8 @@ protected QueryResult Materialize() throw new InvalidOperationException(Strings.ExThisInstanceIsExpiredDueToTransactionBoundaries); } - if (Task.Result==null) { - Session.ExecuteUserDefinedDelayedQueries(false); + if (Task.Result is null) { + _ = Session.ExecuteUserDefinedDelayedQueries(false); } return materializer.Invoke(RecordSetReader.Create(Task.Result), Session, parameterContext); @@ -72,8 +71,8 @@ protected async ValueTask> MaterializeAsync(CancellationToken throw new InvalidOperationException(Strings.ExThisInstanceIsExpiredDueToTransactionBoundaries); } - if (Task.Result==null) { - await Session.ExecuteUserDefinedDelayedQueriesAsync(false, token).ConfigureAwait(false); + if (Task.Result is null) { + _ = await Session.ExecuteUserDefinedDelayedQueriesAsync(false, token).ConfigureAwait(false); } return materializer.Invoke(RecordSetReader.Create(Task.Result), Session, parameterContext); diff --git a/Orm/Xtensive.Orm/Orm/DelayedQuery{T}.cs b/Orm/Xtensive.Orm/Orm/DelayedQuery{T}.cs index f800ba3f73..60a85b747a 100644 --- a/Orm/Xtensive.Orm/Orm/DelayedQuery{T}.cs +++ b/Orm/Xtensive.Orm/Orm/DelayedQuery{T}.cs @@ -19,7 +19,6 @@ namespace Xtensive.Orm /// Represents a delayed sequence query (query where result can be enumerated after an execution). /// /// The type of the element in a resulting sequence. - [Serializable] public sealed class DelayedQuery : DelayedQuery, IEnumerable { /// diff --git a/Orm/Xtensive.Orm/Orm/DelayedScalarQuery{T}.cs b/Orm/Xtensive.Orm/Orm/DelayedScalarQuery{T}.cs index e4e4fe7b5a..f96d727e74 100644 --- a/Orm/Xtensive.Orm/Orm/DelayedScalarQuery{T}.cs +++ b/Orm/Xtensive.Orm/Orm/DelayedScalarQuery{T}.cs @@ -18,7 +18,6 @@ namespace Xtensive.Orm /// Future returning a scalar result. /// /// The type of the result. - [Serializable] public sealed class DelayedScalarQuery : DelayedQuery { private readonly ResultAccessMethod resultAccessMethod; diff --git a/Orm/Xtensive.Orm/Orm/Entity.cs b/Orm/Xtensive.Orm/Orm/Entity.cs index ab46981b3a..82fefdadf8 100644 --- a/Orm/Xtensive.Orm/Orm/Entity.cs +++ b/Orm/Xtensive.Orm/Orm/Entity.cs @@ -9,8 +9,6 @@ using System.ComponentModel; using System.Diagnostics; using System.Linq; -using System.Runtime.Serialization; -using System.Security; using Xtensive.Caching; using Xtensive.Collections; using Xtensive.Core; @@ -20,7 +18,7 @@ using Xtensive.Orm.Operations; using Xtensive.Orm.Rse; using Xtensive.Orm.Rse.Providers; -using Xtensive.Orm.Serialization; +using Xtensive.Orm.Providers; using Xtensive.Orm.Validation; using Xtensive.Reflection; using Xtensive.Tuples; @@ -58,13 +56,10 @@ namespace Xtensive.Orm /// /// Structure class /// EntitySet class - [Serializable] [SystemType] [DebuggerDisplay("{Key}")] public abstract class Entity : Persistent, - IEntity, - ISerializable, - IDeserializationCallback + IEntity { private static readonly Func<(TypeInfo typeInfo, LockMode lockMode, LockBehavior lockBehavior), Session, ExecutableProvider> ExecutableProviderGenerator = ((TypeInfo typeInfo, LockMode lockMode, LockBehavior lockBehavior) t, Session session) => session.Compile(t.typeInfo.Indexes.PrimaryIndex.GetQuery() @@ -143,8 +138,8 @@ public VersionInfo VersionInfo { } } if (columnsToPrefetch!=null) { - Session.Handler.Prefetch(Key, TypeInfo, columnsToPrefetch); - Session.Handler.ExecutePrefetchTasks(true); + _ = Session.Handler.Prefetch(Key, TypeInfo, columnsToPrefetch); + _ = Session.Handler.ExecutePrefetchTasks(true); } var versionTuple = TypeInfo.VersionExtractor.Apply(TupleTransformType.Tuple, State.Tuple); return new VersionInfo(versionTuple); @@ -272,7 +267,7 @@ public void Lock(LockMode lockMode, LockBehavior lockBehavior) parameterContext.SetValue(keyParameter, Key.Value); var source = Session.StorageNode.EntityLockProviderCache.GetOrAdd((TypeInfo, lockMode, lockBehavior), ExecutableProviderGenerator, Session); using var recordSetReader = source.GetRecordSetReader(Session, parameterContext); - recordSetReader.MoveNext(); + _ = recordSetReader.MoveNext(); } /// @@ -551,19 +546,19 @@ internal override sealed void SystemBeforeInitialize(bool materialize) Session.SystemEvents.NotifyEntityCreated(this); Session.Events.NotifyEntityCreated(this); - var operations = Session.Operations; + var (operations, operationsFactory, allowRegistration) = Session.GetOperationsContext(); // Operation 1: using (var scope = operations.BeginRegistration(OperationType.System)) { - if (operations.CanRegisterOperation) - operations.RegisterOperation(new KeyGenerateOperation(Key), true); - scope.Complete(); + if (allowRegistration && operations.CanRegisterOperation) + operations.RegisterOperation(operationsFactory.KeyGenerateOperation(Key), true); + scope?.Complete(); } // Operation 2: using (var scope = operations.BeginRegistration(OperationType.System)) { - if (operations.CanRegisterOperation) - operations.RegisterOperation(new EntityCreateOperation(Key), true); + if (allowRegistration && operations.CanRegisterOperation) + operations.RegisterOperation(operationsFactory.EntityCreationOperation(Key), true); IdentifyAs(EntityIdentifierType.Auto); - scope.Complete(); + scope?.Complete(); } var subscriptionInfo = GetSubscription(EntityEventBroker.InitializingPersistentEventKey); @@ -679,7 +674,7 @@ internal override sealed void SystemSetValueAttempt(FieldInfo field, object valu throw new NotSupportedException(string.Format(Strings.ExUnableToSetKeyFieldXExplicitly, field.Name)); if (changeVersionOnSetAttempt) - UpdateVersionInfo(this, field); + _ = UpdateVersionInfo(this, field); Session.SystemEvents.NotifyFieldValueSettingAttempt(this, field, value); using (Session.Operations.EnableSystemOperationRegistration()) { @@ -701,7 +696,7 @@ internal override sealed void SystemBeforeSetValue(FieldInfo field, object value EnsureNotRemoved(); if (!changeVersionOnSetAttempt) - UpdateVersionInfo(this, field); + _ = UpdateVersionInfo(this, field); Session.SystemEvents.NotifyFieldValueSetting(this, field, value); @@ -781,25 +776,6 @@ protected override sealed Pair GetSubscription(object eventKey) #endregion - #region Serialization-related methods - - [SecurityCritical] - void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) - { - using (Session.OpenSystemLogicOnlyRegion()) { - SerializationContext.Demand().GetEntityData(this, info, context); - } - } - - void IDeserializationCallback.OnDeserialization(object sender) - { - using (Session.OpenSystemLogicOnlyRegion()) { - DeserializationContext.Demand().OnDeserialization(); - } - } - - #endregion - /// public override string ToString() { @@ -896,10 +872,12 @@ protected Entity(params object[] values) State = Session.CreateEntityState(key, true); changeVersionOnSetAttempt = ShouldChangeOnSetAttempt(); RegisterKeyFieldsOfEntityTypeForRemap(key, values); - var operations = Session.Operations; + + var (operations, operationsFactory, allowRegistration) = Session.GetOperationsContext(); + using (operations.BeginRegistration(OperationType.System)) { - if (operations.CanRegisterOperation) - operations.RegisterOperation(new EntityInitializeOperation(key), true); + if (allowRegistration && operations.CanRegisterOperation) + operations.RegisterOperation(operationsFactory.EntityInitializeOperation(key), true); var references = TypeInfo.Key.Fields.Where(f => f.IsEntity && f.Associations.Any(a => a.IsPaired)).ToList(); if (references.Count > 0) { using (Session.DisableSaveChanges(this)) { @@ -948,10 +926,12 @@ protected Entity(Session session, params object[] values) State = Session.CreateEntityState(key, true); changeVersionOnSetAttempt = ShouldChangeOnSetAttempt(); RegisterKeyFieldsOfEntityTypeForRemap(key, values); - var operations = Session.Operations; + + var (operations, operationsFactory, allowRegistration) = Session.GetOperationsContext(); + using (operations.BeginRegistration(OperationType.System)) { - if (operations.CanRegisterOperation) - operations.RegisterOperation(new EntityInitializeOperation(key), true); + if (allowRegistration && operations.CanRegisterOperation) + operations.RegisterOperation(operationsFactory.EntityInitializeOperation(key), true); var references = TypeInfo.Key.Fields.Where(f => f.IsEntity && f.Associations.Any(a => a.IsPaired)).ToList(); if (references.Count > 0) { using (Session.DisableSaveChanges(this)) { @@ -1025,18 +1005,5 @@ protected Entity(Session session, EntityState state) IsMaterializing = false; } } - - /// - /// Initializes a new instance of this class. - /// - /// The . - /// The . - protected Entity(SerializationInfo info, StreamingContext context) - { - using (Session.OpenSystemLogicOnlyRegion()) { - changeVersionOnSetAttempt = ShouldChangeOnSetAttempt(); - DeserializationContext.Demand().SetObjectData(this, info, context); - } - } } } diff --git a/Orm/Xtensive.Orm/Orm/EntitySetBase.cs b/Orm/Xtensive.Orm/Orm/EntitySetBase.cs index 6f52fa050d..79996a0e20 100644 --- a/Orm/Xtensive.Orm/Orm/EntitySetBase.cs +++ b/Orm/Xtensive.Orm/Orm/EntitySetBase.cs @@ -9,12 +9,12 @@ using System.Collections.Specialized; using System.ComponentModel; using System.Linq; -using System.Runtime.Serialization; +using Xtensive.Collections; using Xtensive.Core; using Xtensive.Orm.Internals; using Xtensive.Orm.Model; -using Xtensive.Orm.Operations; using Xtensive.Orm.PairIntegrity; +using Xtensive.Orm.Providers; using Xtensive.Orm.ReferentialIntegrity; using Xtensive.Orm.Rse; using Xtensive.Reflection; @@ -560,12 +560,11 @@ internal bool Add(Entity item, SyncContext syncContext, RemovalContext removalCo } try { - var operations = Session.Operations; + var (operations, operationsFactory, allowRegistration) = Session.GetOperationsContext(); using (var scope = operations.BeginRegistration(Operations.OperationType.System)) { var itemKey = item.Key; - if (operations.CanRegisterOperation) { - operations.RegisterOperation(new EntitySetItemAddOperation(Owner.Key, Field, itemKey)); - } + if (allowRegistration && operations.CanRegisterOperation) + operations.RegisterOperation(operationsFactory.EntitySetItemAddOperation(Owner.Key, Field, itemKey)); SystemBeforeAdd(item); @@ -596,7 +595,8 @@ internal bool Add(Entity item, SyncContext syncContext, RemovalContext removalCo index = GetItemIndex(state, itemKey); }; - operations.NotifyOperationStarting(); + if (allowRegistration && operations.CanRegisterOperation) + operations.NotifyOperationStarting(); if (association.IsPaired) { Session.PairSyncManager.ProcessRecursively(syncContext, removalContext, OperationType.Add, association, Owner, item, finalizer); @@ -614,7 +614,7 @@ internal bool Add(Entity item, SyncContext syncContext, RemovalContext removalCo SystemAdd(item, index); SystemAddCompleted(item, null); - scope.Complete(); + scope?.Complete(); return true; } } @@ -633,13 +633,12 @@ internal bool Remove(Entity item, SyncContext syncContext, RemovalContext remova } try { - var operations = Session.Operations; + var (operations, operationsFactory, allowRegistration) = Session.GetOperationsContext(); var scope = operations.BeginRegistration(Operations.OperationType.System); try { var itemKey = item.Key; - if (operations.CanRegisterOperation) { - operations.RegisterOperation(new EntitySetItemRemoveOperation(Owner.Key, Field, itemKey)); - } + if (allowRegistration && operations.CanRegisterOperation) + operations.RegisterOperation(operationsFactory.EntitySetItemRemoveOperation(Owner.Key, Field, itemKey)); SystemBeforeRemove(item); @@ -669,7 +668,8 @@ internal bool Remove(Entity item, SyncContext syncContext, RemovalContext remova Session.EntitySetChangeRegistry.Register(state); }; - operations.NotifyOperationStarting(); + if (allowRegistration && operations.CanRegisterOperation) + operations.NotifyOperationStarting(); if (association.IsPaired) { Session.PairSyncManager.ProcessRecursively(syncContext, removalContext, OperationType.Remove, association, Owner, item, finalizer); @@ -690,7 +690,7 @@ internal bool Remove(Entity item, SyncContext syncContext, RemovalContext remova SystemRemove(item, index); SystemRemoveCompleted(item, null); - scope.Complete(); + scope?.Complete(); } finally { scope.DisposeSafely(); @@ -710,7 +710,7 @@ internal bool Remove(Entity item, SyncContext syncContext, RemovalContext remova SystemRemove(item, index); SystemRemoveCompleted(item, null); - scope.Complete(); + scope?.Complete(); return true; } finally { @@ -732,14 +732,14 @@ public void Clear() { EnsureOwnerIsNotRemoved(); try { - var operations = Session.Operations; + var (operations, operationsFactory, allowRegistration) = Session.GetOperationsContext(); using (var scope = operations.BeginRegistration(Operations.OperationType.System)) { - if (operations.CanRegisterOperation) { - operations.RegisterOperation(new EntitySetClearOperation(Owner.Key, Field)); - } + if (allowRegistration && operations.CanRegisterOperation) + operations.RegisterOperation(operationsFactory.EntitySetClearOperation(Owner.Key, Field)); SystemBeforeClear(); - operations.NotifyOperationStarting(); + if (allowRegistration && operations.CanRegisterOperation) + operations.NotifyOperationStarting(); foreach (var entity in Entities.ToList()) { _ = Remove(entity); @@ -747,7 +747,7 @@ public void Clear() SystemClear(); SystemClearCompleted(null); - scope.Complete(); + scope?.Complete(); } } catch (Exception e) { @@ -1065,15 +1065,5 @@ protected EntitySetBase(Entity owner, FieldInfo field) Initialize(WellKnownOrmTypes.EntitySetBase); } - - /// - /// Initializes a new instance of this class. - /// - /// The . - /// The . - protected EntitySetBase(SerializationInfo info, StreamingContext context) - { - throw new NotImplementedException(); - } } } diff --git a/Orm/Xtensive.Orm/Orm/EntitySet{T}.cs b/Orm/Xtensive.Orm/Orm/EntitySet{T}.cs index 561a15fb55..d9410f187f 100644 --- a/Orm/Xtensive.Orm/Orm/EntitySet{T}.cs +++ b/Orm/Xtensive.Orm/Orm/EntitySet{T}.cs @@ -10,7 +10,6 @@ using System.Diagnostics; using System.Linq; using System.Linq.Expressions; -using System.Runtime.Serialization; using Xtensive.Core; using Xtensive.Orm.Internals; using Xtensive.Orm.Linq; @@ -254,16 +253,5 @@ protected EntitySet(Entity owner, FieldInfo field) : base(owner, field) { } - - /// - /// Initializes a new instance of this class. - /// - /// The . - /// The . - protected EntitySet(SerializationInfo info, StreamingContext context) - : base(info, context) - { - throw new NotImplementedException(); - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Exceptions/CheckConstraintViolationException.cs b/Orm/Xtensive.Orm/Orm/Exceptions/CheckConstraintViolationException.cs index ce31836f86..e82d8d0786 100644 --- a/Orm/Xtensive.Orm/Orm/Exceptions/CheckConstraintViolationException.cs +++ b/Orm/Xtensive.Orm/Orm/Exceptions/CheckConstraintViolationException.cs @@ -5,8 +5,6 @@ // Created: 2010.02.08 using System; -using System.Runtime.Serialization; - namespace Xtensive.Orm { @@ -14,7 +12,6 @@ namespace Xtensive.Orm /// An exception that is thrown when a CHECK constraint violation is detected. /// This also includes violations of a NOT NULL constraints. /// - [Serializable] public sealed class CheckConstraintViolationException : ConstraintViolationException { // Constructors @@ -37,22 +34,5 @@ public CheckConstraintViolationException(string message, Exception innerExceptio : base(message, innerException) { } - - // Serialization - - /// - /// Initializes a new instance of the class. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// The class name is null or is zero (0). -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - private CheckConstraintViolationException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Exceptions/ConnectionErrorException.cs b/Orm/Xtensive.Orm/Orm/Exceptions/ConnectionErrorException.cs index fbd20ed55a..42d85f5e1e 100644 --- a/Orm/Xtensive.Orm/Orm/Exceptions/ConnectionErrorException.cs +++ b/Orm/Xtensive.Orm/Orm/Exceptions/ConnectionErrorException.cs @@ -5,7 +5,6 @@ // Created: 2010.02.08 using System; -using System.Runtime.Serialization; namespace Xtensive.Orm @@ -13,7 +12,6 @@ namespace Xtensive.Orm /// /// An exception that is thrown when a connection error occured. /// - [Serializable] public sealed class ConnectionErrorException : StorageException { // Constructors @@ -36,22 +34,5 @@ public ConnectionErrorException(string message, Exception innerException) : base(message, innerException) { } - - // Serialization - - /// - /// Initializes a new instance of the class. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// The class name is null or is zero (0). -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - private ConnectionErrorException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Exceptions/ConstraintViolationException.cs b/Orm/Xtensive.Orm/Orm/Exceptions/ConstraintViolationException.cs index a9cc643374..c9b5725a4f 100644 --- a/Orm/Xtensive.Orm/Orm/Exceptions/ConstraintViolationException.cs +++ b/Orm/Xtensive.Orm/Orm/Exceptions/ConstraintViolationException.cs @@ -5,7 +5,6 @@ // Created: 2010.02.08 using System; -using System.Runtime.Serialization; namespace Xtensive.Orm @@ -16,7 +15,6 @@ namespace Xtensive.Orm /// /// /// - [Serializable] public abstract class ConstraintViolationException : StorageException { // Constructors @@ -39,22 +37,5 @@ public ConstraintViolationException(string message, Exception innerException) : base(message, innerException) { } - - // Serialization - - /// - /// Initializes a new instance of the class. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// The class name is null or is zero (0). -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - protected ConstraintViolationException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Exceptions/DeadlockException.cs b/Orm/Xtensive.Orm/Orm/Exceptions/DeadlockException.cs index d6a2f139e5..6cfe038885 100644 --- a/Orm/Xtensive.Orm/Orm/Exceptions/DeadlockException.cs +++ b/Orm/Xtensive.Orm/Orm/Exceptions/DeadlockException.cs @@ -5,7 +5,6 @@ // Created: 2010.02.08 using System; -using System.Runtime.Serialization; namespace Xtensive.Orm @@ -13,7 +12,6 @@ namespace Xtensive.Orm /// /// An exception that is thrown when deadlock is detected by RDBMS. /// - [Serializable] public sealed class DeadlockException : ReprocessableException { // Constructors @@ -36,22 +34,5 @@ public DeadlockException(string message, Exception innerException) : base(message, innerException) { } - - // Serialization - - /// - /// Initializes a new instance of the class. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// The class name is null or is zero (0). -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - private DeadlockException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Exceptions/DomainBuilderException.cs b/Orm/Xtensive.Orm/Orm/Exceptions/DomainBuilderException.cs index 9914d961bb..eab56809ea 100644 --- a/Orm/Xtensive.Orm/Orm/Exceptions/DomainBuilderException.cs +++ b/Orm/Xtensive.Orm/Orm/Exceptions/DomainBuilderException.cs @@ -5,7 +5,6 @@ // Created: 2007.09.18 using System; -using System.Runtime.Serialization; namespace Xtensive.Orm @@ -13,7 +12,6 @@ namespace Xtensive.Orm /// /// Describes various errors detected during . execution. /// - [Serializable] public sealed class DomainBuilderException : StorageException { // Constructors @@ -36,22 +34,5 @@ public DomainBuilderException(string message, Exception innerException) : base(message, innerException) { } - - // Serialization - - /// - /// Initializes a new instance of the class. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// The class name is null or is zero (0). -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - private DomainBuilderException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Exceptions/OperationTimeoutException.cs b/Orm/Xtensive.Orm/Orm/Exceptions/OperationTimeoutException.cs index 54c0c353fc..c3a55086db 100644 --- a/Orm/Xtensive.Orm/Orm/Exceptions/OperationTimeoutException.cs +++ b/Orm/Xtensive.Orm/Orm/Exceptions/OperationTimeoutException.cs @@ -5,7 +5,6 @@ // Created: 2010.02.09 using System; -using System.Runtime.Serialization; namespace Xtensive.Orm @@ -14,7 +13,6 @@ namespace Xtensive.Orm /// An exception that is thrown when currently executing operation /// is timed out. /// - [Serializable] public sealed class OperationTimeoutException : StorageException { // Constructors @@ -37,22 +35,5 @@ public OperationTimeoutException(string message, Exception innerException) : base(message, innerException) { } - - // Serialization - - /// - /// Initializes a new instance of the class. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// The class name is null or is zero (0). -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - private OperationTimeoutException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Exceptions/ParametersLimitExceededException.cs b/Orm/Xtensive.Orm/Orm/Exceptions/ParametersLimitExceededException.cs index bdd886c412..6cc5645b23 100644 --- a/Orm/Xtensive.Orm/Orm/Exceptions/ParametersLimitExceededException.cs +++ b/Orm/Xtensive.Orm/Orm/Exceptions/ParametersLimitExceededException.cs @@ -11,18 +11,17 @@ namespace Xtensive.Orm /// /// An exception that is throws when number of parameters in exeeded maximum value for the storage. /// - [Serializable] public sealed class ParametersLimitExceededException : StorageException { /// /// Current number of parameters in which caused exception. /// - public int CurrentParameterCount { get; private set; } + public int CurrentParameterCount { get; } /// /// Maximum number of parameters declared for which is allowed. /// - public int MaxParameterCount { get; private set; } + public int MaxParameterCount { get; } public ParametersLimitExceededException(int currentParameterCount, int maxParameterCount) : base(string.Format(Strings.ExQueryHasTooManyParametersMaxCountOfParametersIsX, maxParameterCount), null) diff --git a/Orm/Xtensive.Orm/Orm/Exceptions/QueryTranslationException.cs b/Orm/Xtensive.Orm/Orm/Exceptions/QueryTranslationException.cs index d41df25d79..f446b47a53 100644 --- a/Orm/Xtensive.Orm/Orm/Exceptions/QueryTranslationException.cs +++ b/Orm/Xtensive.Orm/Orm/Exceptions/QueryTranslationException.cs @@ -5,7 +5,6 @@ // Created: 2009.12.07 using System; -using System.Runtime.Serialization; namespace Xtensive.Orm @@ -14,7 +13,6 @@ namespace Xtensive.Orm /// LINQ query translation exception. /// Describes various errors that occurs during query compilation. /// - [Serializable] public sealed class QueryTranslationException : StorageException { // Constructors @@ -37,22 +35,5 @@ public QueryTranslationException(string message, Exception innerException) : base(message, innerException) { } - - // Serialization - - /// - /// Initializes a new instance of the class. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// The class name is null or is zero (0). -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - private QueryTranslationException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Exceptions/ReferentialConstraintViolationException.cs b/Orm/Xtensive.Orm/Orm/Exceptions/ReferentialConstraintViolationException.cs index 4575034b4c..d1681e7367 100644 --- a/Orm/Xtensive.Orm/Orm/Exceptions/ReferentialConstraintViolationException.cs +++ b/Orm/Xtensive.Orm/Orm/Exceptions/ReferentialConstraintViolationException.cs @@ -5,7 +5,6 @@ // Created: 2010.02.08 using System; -using System.Runtime.Serialization; namespace Xtensive.Orm @@ -17,7 +16,6 @@ namespace Xtensive.Orm /// is thrown when internal referential integrity /// mechanism detects a violation. /// - [Serializable] public sealed class ReferentialConstraintViolationException : ConstraintViolationException { // Constructors @@ -40,22 +38,5 @@ public ReferentialConstraintViolationException(string message, Exception innerEx : base(message, innerException) { } - - // Serialization - - /// - /// Initializes a new instance of the class. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// The class name is null or is zero (0). -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - private ReferentialConstraintViolationException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Exceptions/ReferentialIntegrityException.cs b/Orm/Xtensive.Orm/Orm/Exceptions/ReferentialIntegrityException.cs index 12c3a10e89..ed6c0a8f5b 100644 --- a/Orm/Xtensive.Orm/Orm/Exceptions/ReferentialIntegrityException.cs +++ b/Orm/Xtensive.Orm/Orm/Exceptions/ReferentialIntegrityException.cs @@ -5,7 +5,6 @@ // Created: 2008.07.01 using System; -using System.Runtime.Serialization; using Xtensive.Core; using Xtensive.Reflection; @@ -19,28 +18,27 @@ namespace Xtensive.Orm /// reference with /// option pointing to it. /// - [Serializable] public sealed class ReferentialIntegrityException : StorageException { /// /// Gets the association. /// - public AssociationInfo Association { get; private set; } + public AssociationInfo Association { get; } /// /// Gets the of the initiator of removing action. /// - public Key Initiator { get; private set; } + public Key Initiator { get; } /// /// Gets the of the referencing object. /// - public Key ReferencingObject { get; private set; } + public Key ReferencingObject { get; } /// /// Gets the of the referenced object. /// - public Key ReferencedObject { get; private set; } + public Key ReferencedObject { get; } // Constructors @@ -62,23 +60,5 @@ public ReferentialIntegrityException(AssociationInfo association, ReferencingObject = referencingObject.Key; ReferencedObject = referencedObject.Key; } - - // Serialization - - /// - /// Initializes a new instance of the class. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// The class name is null or is zero (0). -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - private ReferentialIntegrityException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - // We can't serialize any of members declared in this type - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Exceptions/ReprocessableException.cs b/Orm/Xtensive.Orm/Orm/Exceptions/ReprocessableException.cs index eaf24ee309..cacc0f631a 100644 --- a/Orm/Xtensive.Orm/Orm/Exceptions/ReprocessableException.cs +++ b/Orm/Xtensive.Orm/Orm/Exceptions/ReprocessableException.cs @@ -5,7 +5,6 @@ // Created: 2009.08.17 using System; -using System.Runtime.Serialization; namespace Xtensive.Orm @@ -15,7 +14,6 @@ namespace Xtensive.Orm /// that can be recovered by rolling back active transaction /// and reprocessing all actions in a new one. /// - [Serializable] public abstract class ReprocessableException : StorageException { // Constructors @@ -38,23 +36,5 @@ public ReprocessableException(string message, Exception innerException) : base(message, innerException) { } - - // Serialization - - /// - /// Initializes a new instance of the class. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// - /// The class name is null or is zero (0). -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - protected ReprocessableException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Exceptions/SchemaSynchronizationException.cs b/Orm/Xtensive.Orm/Orm/Exceptions/SchemaSynchronizationException.cs index e99948ba29..f625a6047b 100644 --- a/Orm/Xtensive.Orm/Orm/Exceptions/SchemaSynchronizationException.cs +++ b/Orm/Xtensive.Orm/Orm/Exceptions/SchemaSynchronizationException.cs @@ -5,8 +5,6 @@ // Created: 2007.09.18 using System; -using System.Runtime.Serialization; -using Xtensive.Core; using Xtensive.Orm.Upgrade; @@ -16,13 +14,12 @@ namespace Xtensive.Orm /// Describes schema synchronization errors /// detected during . execution. /// - [Serializable] public sealed class SchemaSynchronizationException : StorageException { /// /// Gets or sets the schema comparison result. /// - public SchemaComparisonResult ComparisonResult { get; private set; } + public SchemaComparisonResult ComparisonResult { get; } // Constructors @@ -54,22 +51,5 @@ public SchemaSynchronizationException(string message, Exception innerException) : base(message, innerException) { } - - // Serialization - - /// - /// Initializes a new instance of the class. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// The class name is null or is zero (0). -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - private SchemaSynchronizationException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Exceptions/StorageException.cs b/Orm/Xtensive.Orm/Orm/Exceptions/StorageException.cs index b877594220..9da3b3cec9 100644 --- a/Orm/Xtensive.Orm/Orm/Exceptions/StorageException.cs +++ b/Orm/Xtensive.Orm/Orm/Exceptions/StorageException.cs @@ -5,31 +5,18 @@ // Created: 2009.08.17 using System; -using System.Runtime.Serialization; - - namespace Xtensive.Orm { /// /// Base class for any storage-level exception. /// - [Serializable] public class StorageException : Exception { - private StorageExceptionInfo info; - /// /// Context information about occurred error. /// - public StorageExceptionInfo Info { - get { return info; } - set { - if (info!=null) - throw new InvalidOperationException(Strings.ExValueIsAlreadyAssigned); - info = value; - } - } + public StorageExceptionInfo Info { get; init; } // Constructors @@ -51,23 +38,5 @@ public StorageException(string message, Exception innerException) : base(message, innerException) { } - - // Serialization - - /// - /// Initializes a new instance of the class. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// - /// The class name is null or is zero (0). -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - protected StorageException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Exceptions/StorageExceptionInfo.cs b/Orm/Xtensive.Orm/Orm/Exceptions/StorageExceptionInfo.cs index 4879b0d990..e1a8c61de0 100644 --- a/Orm/Xtensive.Orm/Orm/Exceptions/StorageExceptionInfo.cs +++ b/Orm/Xtensive.Orm/Orm/Exceptions/StorageExceptionInfo.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2011 Xtensive LLC. +// Copyright (C) 2011 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Denis Krjuchkov @@ -6,7 +6,6 @@ using System; using System.Text; - using Xtensive.Orm.Model; @@ -16,34 +15,33 @@ namespace Xtensive.Orm /// Extended information about . /// All fields are optional. /// - [Serializable] public class StorageExceptionInfo { /// /// Type in which error occured (if any). /// - public TypeInfo Type { get; private set; } + public TypeInfo Type { get; } /// /// Field in which error occured (if any). /// - public FieldInfo Field { get; private set; } + public FieldInfo Field { get; } /// /// Value that caused error (if any). /// - public string Value { get; private set; } + public string Value { get; } /// /// Constraint that was violated (if any). /// - public string Constraint { get; private set; } + public string Constraint { get; } /// public override string ToString() { var builder = new StringBuilder(); if (Type!=null) - builder.AppendFormat(Strings.EntityX, Type); + _ = builder.AppendFormat(Strings.EntityX, Type); if (Field!=null) - builder.AppendFormat(Strings.FieldX, Field); + _ = builder.AppendFormat(Strings.FieldX, Field); // Do not write Value & Constraint values, those are directly taken from SqlExceptionInfo. // They will be provided by its ToString() method. return builder.ToString(); diff --git a/Orm/Xtensive.Orm/Orm/Exceptions/SyntaxErrorException.cs b/Orm/Xtensive.Orm/Orm/Exceptions/SyntaxErrorException.cs index 4706a68fcc..30744cfe4c 100644 --- a/Orm/Xtensive.Orm/Orm/Exceptions/SyntaxErrorException.cs +++ b/Orm/Xtensive.Orm/Orm/Exceptions/SyntaxErrorException.cs @@ -5,7 +5,6 @@ // Created: 2010.02.08 using System; -using System.Runtime.Serialization; namespace Xtensive.Orm @@ -15,7 +14,6 @@ namespace Xtensive.Orm /// When you've got this exception, you either did not configured access permissions /// in your RDBMS, or you've found an error in DataObjects.Net. /// - [Serializable] public class SyntaxErrorException : StorageException { // Constructors @@ -38,22 +36,5 @@ public SyntaxErrorException(string message, Exception innerException) : base(message, innerException) { } - - // Serialization - - /// - /// Initializes a new instance of the class. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// The class name is null or is zero (0). -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - protected SyntaxErrorException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Exceptions/TransactionSerializationFailureException.cs b/Orm/Xtensive.Orm/Orm/Exceptions/TransactionSerializationFailureException.cs index ae56fb09d4..24b729c993 100644 --- a/Orm/Xtensive.Orm/Orm/Exceptions/TransactionSerializationFailureException.cs +++ b/Orm/Xtensive.Orm/Orm/Exceptions/TransactionSerializationFailureException.cs @@ -5,7 +5,6 @@ // Created: 2010.02.08 using System; -using System.Runtime.Serialization; namespace Xtensive.Orm @@ -14,8 +13,7 @@ namespace Xtensive.Orm /// An exception that is thrown when RDBMS can not serialize concurrent access. /// This exception is not related to .NET serialization! /// - [Serializable] - public class TransactionSerializationFailureException : ReprocessableException + public sealed class TransactionSerializationFailureException : ReprocessableException { // Constructors @@ -37,22 +35,5 @@ public TransactionSerializationFailureException(string message, Exception innerE : base(message, innerException) { } - - // Serialization - - /// - /// Initializes a new instance of the class. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// The class name is null or is zero (0). -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - protected TransactionSerializationFailureException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Exceptions/UniqueConstraintViolationException.cs b/Orm/Xtensive.Orm/Orm/Exceptions/UniqueConstraintViolationException.cs index cb59f90e40..f95b628732 100644 --- a/Orm/Xtensive.Orm/Orm/Exceptions/UniqueConstraintViolationException.cs +++ b/Orm/Xtensive.Orm/Orm/Exceptions/UniqueConstraintViolationException.cs @@ -5,7 +5,6 @@ // Created: 2010.02.08 using System; -using System.Runtime.Serialization; namespace Xtensive.Orm @@ -14,8 +13,7 @@ namespace Xtensive.Orm /// An exception that is thrown when unique constaint is violated, /// this also denotes violation of a unique or primary index. /// - [Serializable] - public class UniqueConstraintViolationException : ConstraintViolationException + public sealed class UniqueConstraintViolationException : ConstraintViolationException { // Constructors @@ -37,22 +35,5 @@ public UniqueConstraintViolationException(string message, Exception innerExcepti : base(message, innerException) { } - - // Serialization - - /// - /// Initializes a new instance of the class. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// The class name is null or is zero (0). -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - protected UniqueConstraintViolationException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Exceptions/VersionConflictException.cs b/Orm/Xtensive.Orm/Orm/Exceptions/VersionConflictException.cs index 40dca55183..eaef71677f 100644 --- a/Orm/Xtensive.Orm/Orm/Exceptions/VersionConflictException.cs +++ b/Orm/Xtensive.Orm/Orm/Exceptions/VersionConflictException.cs @@ -5,8 +5,6 @@ // Created: 2009.08.17 using System; -using System.Runtime.Serialization; - namespace Xtensive.Orm { @@ -15,8 +13,7 @@ namespace Xtensive.Orm /// and similar methods /// to indicate version check didn't pass. /// - [Serializable] - public class VersionConflictException : StorageException + public sealed class VersionConflictException : StorageException { // Constructors @@ -38,22 +35,5 @@ public VersionConflictException(string message, Exception innerException) : base(message, innerException) { } - - // Serialization - - /// - /// Initializes a new instance of the class. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// The class name is null or is zero (0). -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - protected VersionConflictException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Interfaces/IOperation.cs b/Orm/Xtensive.Orm/Orm/Interfaces/IOperation.cs index ecde9d720b..8baba284f2 100644 --- a/Orm/Xtensive.Orm/Orm/Interfaces/IOperation.cs +++ b/Orm/Xtensive.Orm/Orm/Interfaces/IOperation.cs @@ -12,9 +12,8 @@ namespace Xtensive.Orm { /// /// Contract for an operation that could be executed later - /// after being logged in . - /// You shouldn't implement this interface directly. - /// Inherit from instead. + /// after being logged. + /// You shouldn't implement this interface directly. /// public interface IOperation { @@ -54,18 +53,6 @@ public interface IOperation /// IReadOnlyDictionary IdentifiedEntities { get; set; } - /// - /// Prepares the operation using specified execution context. - /// - /// The operation execution context. - void Prepare(OperationExecutionContext context); - - /// - /// Executes the operation using specified execution context. - /// - /// The operation execution context. - void Execute(OperationExecutionContext context); - /// /// Clones the operation, , /// and . diff --git a/Orm/Xtensive.Orm/Orm/Interfaces/IOperationFactory.cs b/Orm/Xtensive.Orm/Orm/Interfaces/IOperationFactory.cs new file mode 100644 index 0000000000..bd1876a313 --- /dev/null +++ b/Orm/Xtensive.Orm/Orm/Interfaces/IOperationFactory.cs @@ -0,0 +1,131 @@ +// Copyright (C) 2010-2020 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Alex Yakunin +// Created: 2010.08.04 + +using System; +using System.Collections.Generic; +using Xtensive.Orm.Model; + +namespace Xtensive.Orm.Operations +{ + public interface IOperationFactory : IDomainService + { + // Operations defined in kind-of-entity-lifecycle order + + /// + /// Creates operation of Key value being generated. + /// + /// Generated key. + /// Operation instance. + IOperation KeyGenerateOperation(Key key); + + // Entity creation + /// + /// Creates Operation of creation. + /// + /// Key of created entity + /// Operation instance. + IOperation EntityCreationOperation(Key key); + + /// + /// Creates initialization operation. + /// + /// Initializable entity key. + /// Operation instance. + /// + /// Actually, the operation does nothing - it is used to suppress nested + /// system operations. + /// + IOperation EntityInitializeOperation(Key key); + + // Entity Fields set calls + /// + /// Creates Operation of Field set. + /// + /// Field owner Entity. + /// The field that was set + /// The value set to field. + /// Operation instance. + IOperation EntityFieldSetOperation(Key key, FieldInfo field, object value); + /// + /// Creates Operation of Field set (field that references another ). + /// + /// Field owner Entity. + /// The field that was set. + /// Referenced Entity key. + /// Operation instance. + IOperation EntityFieldSetOperation(Key key, FieldInfo field, Key valueKey); + + // EntitySet Operations - Add, Remove, Clear + /// + /// Creates Operation of item addition to EntitySet. + /// + /// Owner entity key + /// The field of EntitySet. + /// Key of added item. + /// Operation instance. + IOperation EntitySetItemAddOperation(Key key, FieldInfo field, Key itemKey); + /// + /// Creates Operation of item removal from EntitySet. + /// + /// Owner entity key + /// The field of EntitySet. + /// Key of removed item. + /// Operation instance. + IOperation EntitySetItemRemoveOperation(Key key, FieldInfo field, Key itemKey); + + /// + /// Creates EntitySet' clear Operation. + /// + /// Owner entity key + /// The field of EntitySet + /// Operation instance. + IOperation EntitySetClearOperation(Key key, FieldInfo field); + + /// + /// Creates Operation of entity removal. + /// + /// Key of removed entity. + /// Operation instance. + IOperation EntityRemovalOperation(Key key); + /// + /// Creates Operation of number of entites removed. + /// + /// Keys of removed entites. + /// Operation instance. + IOperation EntitiesRemoveOperation(IEnumerable keys); + + + // other operations + + /// + /// Creates Operation of method call. + /// + /// Action that will be executed on replay of the operation. + /// The action arguments. + /// Operation instance. + IOperation MethodCallOperation(Action executeAction, params object[] arguments); + + /// + /// Creates Operation of method call. + /// + /// The peraration action which will be executed before on replay of the operation. + /// Action that will be executed on replay of operation. + /// The actions' arguments. + /// Operation instance. + IOperation MethodCallOperation( + Action prepareAction, + Action executeAction, + params object[] arguments); + + /// + /// Creates Operation of Entity version's validation + /// + /// Entity key. + /// Version that was validated. + /// Operation instance. + IOperation ValidateVersionOperation(Key key, VersionInfo version); + } +} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Interfaces/IOperationRegistry.cs b/Orm/Xtensive.Orm/Orm/Interfaces/IOperationRegistry.cs new file mode 100644 index 0000000000..04ebf77624 --- /dev/null +++ b/Orm/Xtensive.Orm/Orm/Interfaces/IOperationRegistry.cs @@ -0,0 +1,142 @@ +// Copyright (C) 2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System; +using Xtensive.Orm.Operations; + +namespace Xtensive.Orm +{ + /// + /// Contract for an operation registry as a session service. + /// Its implementors can be registered and be retrieved in + /// + public interface IOperationRegistry : ISessionService + { + /// + /// Gets the session this instance is bound to. + /// + Session Session { get; } + + /// + /// Indicates whether operation logging is enabled. + /// implicitly turns this option off; + /// does this explicitly. + /// + bool IsRegistrationEnabled { get; } + + /// + /// Gets a value indicating whether system operation registration is enabled. + /// + bool IsSystemOperationRegistrationEnabled { get; } + + /// + /// Gets a value indicating whether this instance can register operation + /// using method. + /// + bool CanRegisterOperation { get; } + + /// + /// Gets a value indicating whether this instance is registering operation now, + /// i.e. method was invoked, but the + /// scope isn't closed yet. + /// + bool IsRegisteringOperation { get; } + + /// + /// Registers the operation. + /// + /// The operation to register. + void RegisterOperation(IOperation operation); + + /// + /// Registers the operation. + /// + /// The operation to register. + /// If set to , + /// method + /// will be called on completion of operation registration. + void RegisterOperation(IOperation operation, bool isStarted); + + /// + /// Indicates that operation, that is currently registering, is started. + /// Leads to or notification. + /// + void NotifyOperationStarting(); + + /// + /// Indicates that operation, that is currently registering, is started. + /// Leads to or notification. + /// + /// Indicates whether + /// must be thrown if operation isn't registered yet. + void NotifyOperationStarting(bool throwIfNotRegistered); + + /// + /// Registers the operation. + /// + /// The operation to register. + void RegisterUndoOperation(IOperation operation); + + /// + /// Registers the entity identifier. + /// + /// The key of the entity to log the identifier for. + /// The entity identifier. + /// indicates identifier must be assigned automatically + /// as sequential number inside the current operation context. + void RegisterEntityIdentifier(Key key, string identifier); + + /// + /// Temporarily disables undo operation logging. + /// + /// An object enabling the logging back on its disposal. + IDisposable DisableUndoOperationRegistration(); + + /// + /// Temporarily disables system operation logging. + /// + /// An object enabling the logging back on its disposal. + SystemOperationRegistrationScope DisableSystemOperationRegistration(); + + /// + /// Temporarily enables system operation logging. + /// + /// An object disabling the logging back on its disposal. + SystemOperationRegistrationScope EnableSystemOperationRegistration(); + + /// + /// Registers the operation. + /// + /// Type of the operation. + /// + ICompletableScope BeginRegistration(OperationType operationType); + + long GetNextIdentifier() => -1; + + /// + /// Occurs when outermost is starting. + /// + event EventHandler OutermostOperationStarting; + + /// + /// Occurs when outermost is being registered. + /// + event EventHandler OutermostOperationCompleted; + + /// + /// Occurs when nested is starting. + /// + event EventHandler NestedOperationStarting; + + /// + /// Occurs when nested is being registered. + /// + event EventHandler NestedOperationCompleted; + + /// + /// Occurs when undo is being registered. + /// + event EventHandler UndoOperation; + } +} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Internals/EntitySetItem.cs b/Orm/Xtensive.Orm/Orm/Internals/EntitySetItem.cs index 154cbe6390..2467d1b3b4 100644 --- a/Orm/Xtensive.Orm/Orm/Internals/EntitySetItem.cs +++ b/Orm/Xtensive.Orm/Orm/Internals/EntitySetItem.cs @@ -20,7 +20,6 @@ namespace Xtensive.Orm.Internals /// /// The type of the master. /// The type of the slave. - [Serializable] [KeyGenerator(KeyGeneratorKind.None)] [HierarchyRoot(InheritanceSchema = InheritanceSchema.ConcreteTable)] public abstract class EntitySetItem : Entity diff --git a/Orm/Xtensive.Orm/Orm/Internals/EntitySetTypeState.cs b/Orm/Xtensive.Orm/Orm/Internals/EntitySetTypeState.cs index 35b89507cc..e534ce9ce1 100644 --- a/Orm/Xtensive.Orm/Orm/Internals/EntitySetTypeState.cs +++ b/Orm/Xtensive.Orm/Orm/Internals/EntitySetTypeState.cs @@ -10,7 +10,6 @@ namespace Xtensive.Orm.Internals { - [Serializable] internal sealed class EntitySetTypeState { public readonly ExecutableProvider SeekProvider; diff --git a/Orm/Xtensive.Orm/Orm/Internals/GenericKeyFactory.cs b/Orm/Xtensive.Orm/Orm/Internals/GenericKeyFactory.cs index 0f4fccbe22..6a24397df9 100644 --- a/Orm/Xtensive.Orm/Orm/Internals/GenericKeyFactory.cs +++ b/Orm/Xtensive.Orm/Orm/Internals/GenericKeyFactory.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Internals { - [Serializable] internal sealed class GenericKeyFactory { public readonly Type Type; diff --git a/Orm/Xtensive.Orm/Orm/Internals/Key{T1,T2,T3,T4}.cs b/Orm/Xtensive.Orm/Orm/Internals/Key{T1,T2,T3,T4}.cs index 4825bed798..90183d08af 100644 --- a/Orm/Xtensive.Orm/Orm/Internals/Key{T1,T2,T3,T4}.cs +++ b/Orm/Xtensive.Orm/Orm/Internals/Key{T1,T2,T3,T4}.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Internals { - [Serializable] internal sealed class Key : Key { private static readonly Predicate EqualityComparer1 = diff --git a/Orm/Xtensive.Orm/Orm/Internals/Key{T1,T2,T3}.cs b/Orm/Xtensive.Orm/Orm/Internals/Key{T1,T2,T3}.cs index f1c9fa0a8e..254776a9d3 100644 --- a/Orm/Xtensive.Orm/Orm/Internals/Key{T1,T2,T3}.cs +++ b/Orm/Xtensive.Orm/Orm/Internals/Key{T1,T2,T3}.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Internals { - [Serializable] internal sealed class Key : Key { private static readonly Predicate EqualityComparer1 = diff --git a/Orm/Xtensive.Orm/Orm/Internals/Key{T1,T2}.cs b/Orm/Xtensive.Orm/Orm/Internals/Key{T1,T2}.cs index 9f4834c3e5..d58db51fdc 100644 --- a/Orm/Xtensive.Orm/Orm/Internals/Key{T1,T2}.cs +++ b/Orm/Xtensive.Orm/Orm/Internals/Key{T1,T2}.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Internals { - [Serializable] internal sealed class Key : Key { private static readonly Predicate EqualityComparer1 = diff --git a/Orm/Xtensive.Orm/Orm/Internals/Key{T}.cs b/Orm/Xtensive.Orm/Orm/Internals/Key{T}.cs index 332f886dcf..327afd0926 100644 --- a/Orm/Xtensive.Orm/Orm/Internals/Key{T}.cs +++ b/Orm/Xtensive.Orm/Orm/Internals/Key{T}.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Internals { - [Serializable] internal sealed class Key : Key { private static readonly Predicate EqualityComparer1 = diff --git a/Orm/Xtensive.Orm/Orm/Internals/LongKey.cs b/Orm/Xtensive.Orm/Orm/Internals/LongKey.cs index 2203651e57..5ecf326a99 100644 --- a/Orm/Xtensive.Orm/Orm/Internals/LongKey.cs +++ b/Orm/Xtensive.Orm/Orm/Internals/LongKey.cs @@ -10,26 +10,19 @@ namespace Xtensive.Orm.Internals { - [Serializable] internal sealed class LongKey : Key { /// - protected override Tuple GetValue() - { - return value; - } + protected override Tuple GetValue() => value; /// - protected override int CalculateHashCode() - { - return value.GetHashCode(); - } + protected override int CalculateHashCode() => value.GetHashCode(); /// protected override bool ValueEquals(Key other) { var otherKey = other as LongKey; - if (otherKey==null) + if (otherKey is null) return false; return value.Equals(otherKey.value); diff --git a/Orm/Xtensive.Orm/Orm/Internals/PairIntegrity/SyncAction.cs b/Orm/Xtensive.Orm/Orm/Internals/PairIntegrity/SyncAction.cs index 4dae8aeeb2..9c756fa192 100644 --- a/Orm/Xtensive.Orm/Orm/Internals/PairIntegrity/SyncAction.cs +++ b/Orm/Xtensive.Orm/Orm/Internals/PairIntegrity/SyncAction.cs @@ -11,16 +11,15 @@ namespace Xtensive.Orm.PairIntegrity { - [Serializable] - internal struct SyncAction + internal readonly struct SyncAction { - public Action Action { get; private set; } + public readonly Action Action; - public AssociationInfo Association { get; private set; } + public readonly AssociationInfo Association; - public IEntity Owner { get; private set; } + public readonly IEntity Owner; - public IEntity Target { get; private set; } + public readonly IEntity Target; public SyncAction(Action action, AssociationInfo association, IEntity owner, IEntity target) diff --git a/Orm/Xtensive.Orm/Orm/Internals/PersistAction.cs b/Orm/Xtensive.Orm/Orm/Internals/PersistAction.cs index 9364214d55..cf24f36f91 100644 --- a/Orm/Xtensive.Orm/Orm/Internals/PersistAction.cs +++ b/Orm/Xtensive.Orm/Orm/Internals/PersistAction.cs @@ -5,12 +5,10 @@ // Created: 2009.07.09 using System; -using Xtensive.Orm.Providers; namespace Xtensive.Orm.Internals { - [Serializable] - internal struct PersistAction + internal readonly struct PersistAction { public readonly StorageNode Node; public readonly EntityState EntityState; diff --git a/Orm/Xtensive.Orm/Orm/Internals/Prefetch/EntityContainer.cs b/Orm/Xtensive.Orm/Orm/Internals/Prefetch/EntityContainer.cs index c775207038..aaaeda4915 100644 --- a/Orm/Xtensive.Orm/Orm/Internals/Prefetch/EntityContainer.cs +++ b/Orm/Xtensive.Orm/Orm/Internals/Prefetch/EntityContainer.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Internals.Prefetch { - [Serializable] internal abstract class EntityContainer { private SortedDictionary columns; diff --git a/Orm/Xtensive.Orm/Orm/Internals/Prefetch/EntityGroupTask.cs b/Orm/Xtensive.Orm/Orm/Internals/Prefetch/EntityGroupTask.cs index 3d5466c9d6..d544aca7f4 100644 --- a/Orm/Xtensive.Orm/Orm/Internals/Prefetch/EntityGroupTask.cs +++ b/Orm/Xtensive.Orm/Orm/Internals/Prefetch/EntityGroupTask.cs @@ -56,7 +56,6 @@ public RecordSetCacheKey(int[] columnIndexes, TypeInfo type, int cachedHashCode) } } - [Serializable] internal sealed class EntityGroupTask : IEquatable { private const int MaxKeyCountInOneStatement = 40; diff --git a/Orm/Xtensive.Orm/Orm/Internals/Prefetch/EntitySetTask.cs b/Orm/Xtensive.Orm/Orm/Internals/Prefetch/EntitySetTask.cs index c016df9e00..8a6f3a0360 100644 --- a/Orm/Xtensive.Orm/Orm/Internals/Prefetch/EntitySetTask.cs +++ b/Orm/Xtensive.Orm/Orm/Internals/Prefetch/EntitySetTask.cs @@ -49,7 +49,6 @@ public ItemsQueryCacheKey(FieldInfo referencingField, int? itemCountLimit) } } - [Serializable] internal sealed class EntitySetTask : IEquatable { private static readonly Parameter ownerParameter = new Parameter(WellKnown.KeyFieldName); diff --git a/Orm/Xtensive.Orm/Orm/Internals/Prefetch/PrefetchFieldDescriptor.cs b/Orm/Xtensive.Orm/Orm/Internals/Prefetch/PrefetchFieldDescriptor.cs index 9d49ade53c..5c57ad4967 100644 --- a/Orm/Xtensive.Orm/Orm/Internals/Prefetch/PrefetchFieldDescriptor.cs +++ b/Orm/Xtensive.Orm/Orm/Internals/Prefetch/PrefetchFieldDescriptor.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Internals.Prefetch /// /// Descriptor of a field's fetching request. /// - [Serializable] public sealed class PrefetchFieldDescriptor { private readonly Action keyExtractionSubscriber; @@ -46,27 +45,17 @@ public sealed class PrefetchFieldDescriptor public readonly Guid? PrefetchOperationId; /// - public bool Equals(PrefetchFieldDescriptor other) - { - return Equals(other.Field, Field); - } + public bool Equals(PrefetchFieldDescriptor other) => Equals(other.Field, Field); /// public override bool Equals(object obj) => obj is PrefetchFieldDescriptor other && Equals(other); /// - public override int GetHashCode() - { - return Field.GetHashCode(); - } + public override int GetHashCode() => Field.GetHashCode(); - internal void NotifySubscriber(Key ownerKey, Key referencedKey) - { - if (keyExtractionSubscriber != null) { - keyExtractionSubscriber.Invoke(ownerKey, Field, referencedKey); - } - } + internal void NotifySubscriber(Key ownerKey, Key referencedKey) => + keyExtractionSubscriber?.Invoke(ownerKey, Field, referencedKey); // Constructors diff --git a/Orm/Xtensive.Orm/Orm/Internals/Prefetch/PrefetchProcessor.cs b/Orm/Xtensive.Orm/Orm/Internals/Prefetch/PrefetchProcessor.cs deleted file mode 100644 index 96e240497c..0000000000 --- a/Orm/Xtensive.Orm/Orm/Internals/Prefetch/PrefetchProcessor.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (C) 2010-2020 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Alexis Kochetov -// Created: 2010.11.22 - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; - -namespace Xtensive.Orm.Internals.Prefetch -{ - [Serializable] - internal class PrefetchProcessor : IEnumerable - { - public IEnumerator GetEnumerator() - { - throw new NotImplementedException(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - } -} diff --git a/Orm/Xtensive.Orm/Orm/Internals/Prefetch/ReferencedEntityContainer.cs b/Orm/Xtensive.Orm/Orm/Internals/Prefetch/ReferencedEntityContainer.cs index 15b3a8cffe..57651982f7 100644 --- a/Orm/Xtensive.Orm/Orm/Internals/Prefetch/ReferencedEntityContainer.cs +++ b/Orm/Xtensive.Orm/Orm/Internals/Prefetch/ReferencedEntityContainer.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Internals.Prefetch { - [Serializable] internal sealed class ReferencedEntityContainer : EntityContainer { private readonly Key ownerKey; @@ -23,22 +22,21 @@ internal sealed class ReferencedEntityContainer : EntityContainer private readonly PrefetchFieldDescriptor referencingFieldDescriptor; private bool needToNotifyOwner; - public FieldInfo ReferencingField {get { return referencingFieldDescriptor.Field; } } + public FieldInfo ReferencingField => referencingFieldDescriptor.Field; public override EntityGroupTask GetTask() { - if (Key!=null && Task==null) + if (Key is not null && Task is null) return null; - if (Task!=null) + if (Task is not null) return Task; - EntityState ownerState; - var isStateCached = Manager.Owner.LookupState(ownerKey, out ownerState); + var isStateCached = Manager.Owner.LookupState(ownerKey, out var ownerState); if (isStateCached) { - if (ownerState == null) + if (ownerState is null) return null; - if (ownerState.Tuple == null) + if (ownerState.Tuple is null) return null; if (ownerState.PersistenceState == PersistenceState.Removed) return null; @@ -51,7 +49,7 @@ public override EntityGroupTask GetTask() if (!isOwnerTypeKnown && !ownerState.Key.TypeReference.Type.Fields.Contains(ReferencingField)) return null; var foreignKeyTuple = ExtractForeignKeyTuple(ownerState); - if (foreignKeyTuple == null) + if (foreignKeyTuple is null) return null; var session = Manager.Owner.Session; Key = Key.Create(session.Domain, session.StorageNodeId, Type, TypeReferenceAccuracy.BaseType, foreignKeyTuple); @@ -60,7 +58,7 @@ public override EntityGroupTask GetTask() public void NotifyOwnerAboutKeyWithUnknownType() { - if (needToNotifyOwner && Task != null) + if (needToNotifyOwner && Task is not null) referencingFieldDescriptor.NotifySubscriber(ownerKey, Key); } @@ -69,7 +67,7 @@ private Tuple ExtractForeignKeyTuple(EntityState ownerState) var association = ReferencingField.Associations[^1]; var result = association.ExtractForeignKey(ownerState.Type, ownerState.Tuple); var tupleState = result.GetFieldStateMap(TupleFieldState.Null); - for (int i = 0; i < result.Count; i++) { + for (int i = 0, count = result.Count; i < count; i++) { if (!result.GetFieldState(i).IsAvailable()) if (isOwnerTypeKnown) throw Exceptions.InternalError(Strings.ExForeignKeyValueHaveNotBeenLoaded, OrmLog.Instance); @@ -83,9 +81,8 @@ private Tuple ExtractForeignKeyTuple(EntityState ownerState) private EntityGroupTask CreateTask() { - TypeInfo exactReferencedType; - var hasExactTypeBeenGotten = PrefetchHelper.TryGetExactKeyType(Key, Manager, out exactReferencedType); - if (hasExactTypeBeenGotten!=null) { + var hasExactTypeBeenGotten = PrefetchHelper.TryGetExactKeyType(Key, Manager, out var exactReferencedType); + if (hasExactTypeBeenGotten is not null) { if (hasExactTypeBeenGotten.Value) { Type = exactReferencedType; //FillColumnCollection(); @@ -107,9 +104,8 @@ private void FillColumnCollection() { var descriptors = PrefetchHelper .GetCachedDescriptorsForFieldsLoadedByDefault(Manager.Owner.Session.Domain, Type); - SortedDictionary columns; - List columnsToBeLoaded; - Manager.GetCachedColumnIndexes(Type, descriptors, out columns, out columnsToBeLoaded); + + Manager.GetCachedColumnIndexes(Type, descriptors, out var columns, out var columnsToBeLoaded); SetColumnCollections(columns, columnsToBeLoaded); } diff --git a/Orm/Xtensive.Orm/Orm/Internals/Prefetch/RootEntityContainer.cs b/Orm/Xtensive.Orm/Orm/Internals/Prefetch/RootEntityContainer.cs index e9a59c641b..76781c5625 100644 --- a/Orm/Xtensive.Orm/Orm/Internals/Prefetch/RootEntityContainer.cs +++ b/Orm/Xtensive.Orm/Orm/Internals/Prefetch/RootEntityContainer.cs @@ -10,7 +10,6 @@ namespace Xtensive.Orm.Internals.Prefetch { - [Serializable] internal sealed class RootEntityContainer : EntityContainer { private PrefetchFieldDescriptor referencingFieldDescriptor; @@ -18,7 +17,7 @@ internal sealed class RootEntityContainer : EntityContainer public override EntityGroupTask GetTask() { - if (Task == null) { + if (Task is null) { if (!SelectColumnsToBeLoaded()) return null; Task = new EntityGroupTask(Type, ColumnIndexesToBeLoaded.ToArray(), Manager); @@ -34,7 +33,7 @@ public void SetParametersOfReference(PrefetchFieldDescriptor referencingField, K public void NotifyOwnerAboutKeyWithUnknownType() { - if (Task != null && ownerKey != null) + if (Task is not null && ownerKey is not null) referencingFieldDescriptor.NotifySubscriber(ownerKey, Key); } diff --git a/Orm/Xtensive.Orm/Orm/Internals/QueryTask.cs b/Orm/Xtensive.Orm/Orm/Internals/QueryTask.cs index f74ac3d16a..e8d3f1c0b9 100644 --- a/Orm/Xtensive.Orm/Orm/Internals/QueryTask.cs +++ b/Orm/Xtensive.Orm/Orm/Internals/QueryTask.cs @@ -17,7 +17,6 @@ namespace Xtensive.Orm.Internals /// Delayed query task. /// Used internally to support delayed (future) queries. /// - [Serializable] public sealed class QueryTask : IEnumerable { /// diff --git a/Orm/Xtensive.Orm/Orm/Internals/ReferentialActions.cs b/Orm/Xtensive.Orm/Orm/Internals/ReferentialActions.cs index 6f935d8bec..a28fcaa3fa 100644 --- a/Orm/Xtensive.Orm/Orm/Internals/ReferentialActions.cs +++ b/Orm/Xtensive.Orm/Orm/Internals/ReferentialActions.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Internals { - [Serializable] internal static class ReferentialActions { public static readonly Func GetReference = OnGetReference; @@ -34,9 +33,11 @@ private static IEntity OnGetReference(AssociationInfo association, IEntity owner private static void OnClearReference(AssociationInfo association, IEntity owner, IEntity target, SyncContext syncContext, RemovalContext removalContext) { - var nullIsEntity = owner as IHasNullEntity; - var nullValue = nullIsEntity == null ? null : nullIsEntity.NullEntity; - if (nullValue != null || association.OwnerField.IsNullable || removalContext?.Contains((Entity) owner) == true) + var nullValue = owner is IHasNullEntity nullIsEntity + ? nullIsEntity.NullEntity + : null; + + if (nullValue is not null || association.OwnerField.IsNullable || removalContext?.Contains((Entity) owner) == true) // If field is non-nullable & null value is real null, we should avoid assigning it, // since this will lead to an error on persist in almost any case; // but if we won't assign it, it will either fail with ref. constraint violation later, @@ -51,12 +52,14 @@ private static void OnSetReference(AssociationInfo association, IEntity owner, I private static void OnAddReference(AssociationInfo association, IEntity owner, IEntity target, SyncContext syncContext, RemovalContext removalContext) { - ((EntitySetBase) ((Entity) owner).GetFieldValue(association.OwnerField)).Add((Entity) target, syncContext, removalContext); + _ = ((EntitySetBase) ((Entity) owner).GetFieldValue(association.OwnerField)) + .Add((Entity) target, syncContext, removalContext); } private static void OnRemoveReference(AssociationInfo association, IEntity owner, IEntity target, SyncContext syncContext, RemovalContext removalContext) { - ((EntitySetBase) ((Entity) owner).GetFieldValue(association.OwnerField)).Remove((Entity) target, syncContext, removalContext); + _ = ((EntitySetBase) ((Entity) owner).GetFieldValue(association.OwnerField)) + .Remove((Entity) target, syncContext, removalContext); } #endregion diff --git a/Orm/Xtensive.Orm/Orm/Internals/ReferentialIntegrity/RemovalProcessor.cs b/Orm/Xtensive.Orm/Orm/Internals/ReferentialIntegrity/RemovalProcessor.cs index 685024968d..c6205116a3 100644 --- a/Orm/Xtensive.Orm/Orm/Internals/ReferentialIntegrity/RemovalProcessor.cs +++ b/Orm/Xtensive.Orm/Orm/Internals/ReferentialIntegrity/RemovalProcessor.cs @@ -61,14 +61,12 @@ public void Remove(IEnumerable entities, EntityRemoveReason reason) IReadOnlyList processedEntities = Array.Empty(); var notifiedEntities = new HashSet(); try { - var operations = Session.Operations; + var (operations, operationsFactory, allowRegistration) = Session.GetOperationsContext(); using (var scope = operations.BeginRegistration(OperationType.System)) using (Context = new RemovalContext(this)) { Session.EnforceChangeRegistrySizeLimit(); - if (operations.CanRegisterOperation) { - operations.RegisterOperation( - new EntitiesRemoveOperation(entities.Select(e => e.Key))); - } + if (allowRegistration && operations.CanRegisterOperation) + operations.RegisterOperation(operationsFactory.EntitiesRemoveOperation(entities.Select(e => e.Key))); Context.Enqueue(entities, reason); @@ -80,12 +78,14 @@ public void Remove(IEnumerable entities, EntityRemoveReason reason) } if (!isOperationStarted) { isOperationStarted = true; - operations.NotifyOperationStarting(); + if (allowRegistration && operations.CanRegisterOperation) + operations.NotifyOperationStarting(); } ProcessItems(entitiesForProcessing); } if (!isOperationStarted) { - operations.NotifyOperationStarting(); + if (allowRegistration && operations.CanRegisterOperation) + operations.NotifyOperationStarting(); } processedEntities = Context.GetProcessedEntities().ToList(); foreach (var entity in processedEntities) { @@ -95,7 +95,7 @@ public void Remove(IEnumerable entities, EntityRemoveReason reason) Context.ProcessFinalizers(); Session.EnforceChangeRegistrySizeLimit(); - scope.Complete(); // Successful anyway + scope?.Complete(); // Successful anyway using (var ea = new ExceptionAggregator()) { foreach (var entity in processedEntities) { diff --git a/Orm/Xtensive.Orm/Orm/Internals/WellKnownOrmTypes.cs b/Orm/Xtensive.Orm/Orm/Internals/WellKnownOrmTypes.cs index 392491ed02..6c05292de6 100644 --- a/Orm/Xtensive.Orm/Orm/Internals/WellKnownOrmTypes.cs +++ b/Orm/Xtensive.Orm/Orm/Internals/WellKnownOrmTypes.cs @@ -58,6 +58,8 @@ internal static class WellKnownOrmInterfaces public static readonly Type Entity = typeof(IEntity); public static readonly Type ObjectValidator = typeof(IObjectValidator); public static readonly Type PropertyValidator = typeof(IPropertyValidator); + + public static readonly Type OperationRegistry = typeof(IOperationRegistry); } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Key.cs b/Orm/Xtensive.Orm/Orm/Key.cs index 069d5f30c1..491b74b109 100644 --- a/Orm/Xtensive.Orm/Orm/Key.cs +++ b/Orm/Xtensive.Orm/Orm/Key.cs @@ -73,6 +73,11 @@ public TypeInfo TypeInfo } } + /// + /// Determines whether property has exact type value or not. + /// + public bool HasExactType => TypeReference.Accuracy == TypeReferenceAccuracy.ExactType; + /// /// Determines whether this key is a temporary key in the specified . /// @@ -135,14 +140,6 @@ public TypeInfo ResolveTypeInfo([NotNull, InstantHandle] Session session) /// protected abstract Tuple GetValue(); - /// - /// Determines whether property has exact type value or not. - /// - internal bool HasExactType - { - get { return TypeReference.Accuracy==TypeReferenceAccuracy.ExactType; } - } - internal Tuple CreateTuple() { var descriptor = TypeReference.Type.Key.TupleDescriptor; diff --git a/Orm/Xtensive.Orm/Orm/KeyEventArgs.cs b/Orm/Xtensive.Orm/Orm/KeyEventArgs.cs index 4f4db93a88..e54f6edf79 100644 --- a/Orm/Xtensive.Orm/Orm/KeyEventArgs.cs +++ b/Orm/Xtensive.Orm/Orm/KeyEventArgs.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm /// /// Arguments for -related events. /// - [Serializable] public readonly struct KeyEventArgs { /// diff --git a/Orm/Xtensive.Orm/Orm/KeyMapping.cs b/Orm/Xtensive.Orm/Orm/KeyMapping.cs index a077892746..3ff61e2634 100644 --- a/Orm/Xtensive.Orm/Orm/KeyMapping.cs +++ b/Orm/Xtensive.Orm/Orm/KeyMapping.cs @@ -8,8 +8,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; -using System.Runtime.Serialization; -using System.Security; using Xtensive.Core; @@ -19,8 +17,7 @@ namespace Xtensive.Orm /// Maps local ("disconnected") instances /// to actual (storage) instances. /// - [Serializable] - public sealed class KeyMapping : ISerializable + public sealed class KeyMapping { /// /// Gets the key map. @@ -72,35 +69,10 @@ orderby pairKeyString /// public KeyMapping(IDictionary map) { - Map = new ReadOnlyDictionary(map); - } - - // Serialization - - /// - [SecurityCritical] - void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) - { - var serializedMapping = new Dictionary, Ref>(); - foreach (var pair in Map) - serializedMapping.Add(pair.Key, pair.Value); - - info.AddValue("Map", serializedMapping, typeof(Dictionary, Ref>)); - } - - /// - /// Initializes a new instance of the class. - /// - /// The info. - /// The context. - private KeyMapping(SerializationInfo info, StreamingContext context) - { - var serializedMapping = (Dictionary, Ref>) - info.GetValue("Map", typeof(Dictionary, Ref>)); - var map = new Dictionary(); - foreach (var pair in serializedMapping) - map.Add(pair.Key, pair.Value); - Map = new ReadOnlyDictionary(map); + if (map is ReadOnlyDictionary nativeReadonly) + Map = nativeReadonly; + else + Map = new ReadOnlyDictionary(map); } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Linq/Expressions/ConstructorExpression.cs b/Orm/Xtensive.Orm/Orm/Linq/Expressions/ConstructorExpression.cs index 76008aab60..b2f7774ed0 100644 --- a/Orm/Xtensive.Orm/Orm/Linq/Expressions/ConstructorExpression.cs +++ b/Orm/Xtensive.Orm/Orm/Linq/Expressions/ConstructorExpression.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Linq { - [Serializable] internal class ConstructorExpression : ParameterizedExpression, IMappedExpression { @@ -61,9 +60,10 @@ public Expression RemoveOuterParameter(Dictionary proces public Expression Remap(int offset, Dictionary processedExpressions) { Func remapper = delegate(IMappedExpression mapped) { - var parametrizedExpression = mapped as ParameterizedExpression; - if (parametrizedExpression!=null && (parametrizedExpression.OuterParameter==OuterParameter || OuterParameter==null)) + if (mapped is ParameterizedExpression paramExpression + && (paramExpression.OuterParameter == OuterParameter || OuterParameter is null)) { return mapped.Remap(offset, new Dictionary()); + } return (Expression) mapped; }; @@ -84,8 +84,7 @@ public Expression Remap(int offset, Dictionary processed public Expression Remap(IReadOnlyList map, Dictionary processedExpressions) { Func remapper = delegate(IMappedExpression mapped) { - var parametrizedExpression = mapped as ParameterizedExpression; - if (parametrizedExpression!=null && (parametrizedExpression.OuterParameter==OuterParameter || OuterParameter==null)) + if (mapped is ParameterizedExpression paramExpression && (paramExpression.OuterParameter == OuterParameter || OuterParameter is null)) return mapped.Remap(map, new Dictionary()); return (Expression) mapped; }; diff --git a/Orm/Xtensive.Orm/Orm/Linq/Expressions/ExtendedExpressionType.cs b/Orm/Xtensive.Orm/Orm/Linq/Expressions/ExtendedExpressionType.cs index fff8f2aad6..6b1377d380 100644 --- a/Orm/Xtensive.Orm/Orm/Linq/Expressions/ExtendedExpressionType.cs +++ b/Orm/Xtensive.Orm/Orm/Linq/Expressions/ExtendedExpressionType.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Linq.Expressions { - [Serializable] internal enum ExtendedExpressionType { Projection = 1000, diff --git a/Orm/Xtensive.Orm/Orm/Linq/Expressions/FullTextExpression.cs b/Orm/Xtensive.Orm/Orm/Linq/Expressions/FullTextExpression.cs index 2e5477fcd1..cc20ec69b7 100644 --- a/Orm/Xtensive.Orm/Orm/Linq/Expressions/FullTextExpression.cs +++ b/Orm/Xtensive.Orm/Orm/Linq/Expressions/FullTextExpression.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Linq.Expressions { - [Serializable] internal class FullTextExpression : ParameterizedExpression, IMappedExpression { @@ -26,8 +25,7 @@ internal class FullTextExpression : ParameterizedExpression, public Expression BindParameter(ParameterExpression parameter, Dictionary processedExpressions) { - Expression result; - if (processedExpressions.TryGetValue(this, out result)) + if (processedExpressions.TryGetValue(this, out var result)) return result; var entityExpression = (EntityExpression) EntityExpression.BindParameter(parameter, processedExpressions); @@ -37,8 +35,7 @@ public Expression BindParameter(ParameterExpression parameter, Dictionary processedExpressions) { - Expression result; - if (processedExpressions.TryGetValue(this, out result)) + if (processedExpressions.TryGetValue(this, out var result)) return result; var entityExpression = (EntityExpression) EntityExpression.RemoveOuterParameter(processedExpressions); @@ -51,8 +48,7 @@ public Expression Remap(int offset, Dictionary processed if (!CanRemap) return this; - Expression result; - if (processedExpressions.TryGetValue(this, out result)) + if (processedExpressions.TryGetValue(this, out var result)) return result; var remappedEntityExpression = (EntityExpression) EntityExpression.Remap(offset, processedExpressions); @@ -65,8 +61,7 @@ public Expression Remap(IReadOnlyList map, Dictionary processedExpressions) { - Expression result; - if (processedExpressions.TryGetValue(this, out result)) + if (processedExpressions.TryGetValue(this, out var result)) return result; - var mappedKey = KeyExpression as IMappedExpression; - if (mappedKey==null) + if (KeyExpression is not IMappedExpression mappedKey) return this; var processedKey = mappedKey.BindParameter(parameter, processedExpressions); result = new GroupingExpression(Type, OuterParameter, DefaultIfEmpty, ProjectionExpression, ApplyParameter, processedKey, SelectManyInfo); @@ -58,11 +58,9 @@ public override Expression BindParameter(ParameterExpression parameter, Dictiona public override Expression RemoveOuterParameter(Dictionary processedExpressions) { - Expression result; - if (processedExpressions.TryGetValue(this, out result)) + if (processedExpressions.TryGetValue(this, out var result)) return result; - var mappedKey = KeyExpression as IMappedExpression; - if (mappedKey==null) + if (KeyExpression is not IMappedExpression mappedKey) return this; var processedKey = mappedKey.RemoveOuterParameter(processedExpressions); result = new GroupingExpression(Type, OuterParameter, DefaultIfEmpty, ProjectionExpression, ApplyParameter, processedKey, SelectManyInfo); diff --git a/Orm/Xtensive.Orm/Orm/Linq/Expressions/LocalCollectionExpression.cs b/Orm/Xtensive.Orm/Orm/Linq/Expressions/LocalCollectionExpression.cs index 2a7267bd2d..e05a858051 100644 --- a/Orm/Xtensive.Orm/Orm/Linq/Expressions/LocalCollectionExpression.cs +++ b/Orm/Xtensive.Orm/Orm/Linq/Expressions/LocalCollectionExpression.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Linq.Expressions { - [Serializable] internal class LocalCollectionExpression : ParameterizedExpression, IMappedExpression { diff --git a/Orm/Xtensive.Orm/Orm/Linq/Expressions/ResultAccessMethod.cs b/Orm/Xtensive.Orm/Orm/Linq/Expressions/ResultAccessMethod.cs index 6d910f7bfa..d882bec4db 100644 --- a/Orm/Xtensive.Orm/Orm/Linq/Expressions/ResultAccessMethod.cs +++ b/Orm/Xtensive.Orm/Orm/Linq/Expressions/ResultAccessMethod.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Linq.Expressions { - [Serializable] internal enum ResultAccessMethod { All, diff --git a/Orm/Xtensive.Orm/Orm/Linq/Expressions/SubQueryExpression.cs b/Orm/Xtensive.Orm/Orm/Linq/Expressions/SubQueryExpression.cs index ff5a3cdaae..705a47bf2e 100644 --- a/Orm/Xtensive.Orm/Orm/Linq/Expressions/SubQueryExpression.cs +++ b/Orm/Xtensive.Orm/Orm/Linq/Expressions/SubQueryExpression.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Linq.Expressions { - [Serializable] internal class SubQueryExpression : ParameterizedExpression, IMappedExpression { @@ -24,14 +23,10 @@ internal class SubQueryExpression : ParameterizedExpression, public ApplyParameter ApplyParameter { get; } public virtual Expression BindParameter(ParameterExpression parameter, Dictionary processedExpressions) - { - return this; - } + => this; public virtual Expression RemoveOuterParameter(Dictionary processedExpressions) - { - return this; - } + => this; public virtual Expression Remap(int offset, Dictionary processedExpressions) { diff --git a/Orm/Xtensive.Orm/Orm/Linq/Grouping.cs b/Orm/Xtensive.Orm/Orm/Linq/Grouping.cs index dbdd873c01..51d6afc1aa 100644 --- a/Orm/Xtensive.Orm/Orm/Linq/Grouping.cs +++ b/Orm/Xtensive.Orm/Orm/Linq/Grouping.cs @@ -13,12 +13,11 @@ namespace Xtensive.Orm.Linq { - [Serializable] internal class Grouping : SubQuery, IGrouping { - public TKey Key { get; private set; } + public TKey Key { get; } public Grouping(ProjectionExpression projectionExpression, TranslatedQuery translatedQuery, Parameter parameter, Tuple tuple, TKey key, ItemMaterializationContext context) : base(projectionExpression, translatedQuery, parameter, tuple, context) diff --git a/Orm/Xtensive.Orm/Orm/Linq/ItemToTupleConverter.cs b/Orm/Xtensive.Orm/Orm/Linq/ItemToTupleConverter.cs index dce583958f..6026137c23 100644 --- a/Orm/Xtensive.Orm/Orm/Linq/ItemToTupleConverter.cs +++ b/Orm/Xtensive.Orm/Orm/Linq/ItemToTupleConverter.cs @@ -15,11 +15,9 @@ namespace Xtensive.Orm.Linq { - [Serializable] internal abstract class ItemToTupleConverter { private static readonly Type ItemToTupleConverterType = typeof(ItemToTupleConverter<>); - protected static readonly Type RefOfTType = typeof(Ref<>); public abstract Expression>> GetEnumerable(); @@ -32,7 +30,7 @@ public static ItemToTupleConverter BuildConverter(Type type, Type storedEntityTy return (ItemToTupleConverter) ItemToTupleConverterType .CachedMakeGenericType(type) .GetConstructors()[0] - .Invoke(new[] { enumerable, model, sourceExpression, storedEntityType }); + .Invoke([enumerable, model, sourceExpression, storedEntityType]); } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Linq/ItemToTupleConverter{TItem}.cs b/Orm/Xtensive.Orm/Orm/Linq/ItemToTupleConverter{TItem}.cs index f73f1ff335..b0acd8b535 100644 --- a/Orm/Xtensive.Orm/Orm/Linq/ItemToTupleConverter{TItem}.cs +++ b/Orm/Xtensive.Orm/Orm/Linq/ItemToTupleConverter{TItem}.cs @@ -23,7 +23,6 @@ namespace Xtensive.Orm.Linq { - [Serializable] internal sealed class ItemToTupleConverter : ItemToTupleConverter { private struct TupleTypeCollection @@ -102,6 +101,7 @@ private enum PersistableKind Unknown } + private static readonly Type RefOfTType = typeof(Ref<>); private static readonly ParameterExpression ParamContext = Expression.Parameter(WellKnownOrmTypes.ParameterContext, "context"); private static readonly MethodInfo SelectMethod = WellKnownMembers.Enumerable.Select.MakeGenericMethod(typeof(TItem), WellKnownOrmTypes.Tuple); diff --git a/Orm/Xtensive.Orm/Orm/Linq/LinqBindingCollection.cs b/Orm/Xtensive.Orm/Orm/Linq/LinqBindingCollection.cs index e17ebc52c6..a3d0092084 100644 --- a/Orm/Xtensive.Orm/Orm/Linq/LinqBindingCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Linq/LinqBindingCollection.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Linq { - [Serializable] internal class LinqBindingCollection : BindingCollection { internal readonly ref struct ParameterScope diff --git a/Orm/Xtensive.Orm/Orm/Linq/Materialization/ExpressionMaterializer.cs b/Orm/Xtensive.Orm/Orm/Linq/Materialization/ExpressionMaterializer.cs index 23b7894e72..8792d6a742 100644 --- a/Orm/Xtensive.Orm/Orm/Linq/Materialization/ExpressionMaterializer.cs +++ b/Orm/Xtensive.Orm/Orm/Linq/Materialization/ExpressionMaterializer.cs @@ -23,7 +23,6 @@ namespace Xtensive.Orm.Linq.Materialization { - [Serializable] internal class ExpressionMaterializer : PersistentExpressionVisitor { private const string RootQueryTagsPrefix = "Root query tags ->"; diff --git a/Orm/Xtensive.Orm/Orm/Linq/MemberType.cs b/Orm/Xtensive.Orm/Orm/Linq/MemberType.cs index 155d113cb2..81a95346a6 100644 --- a/Orm/Xtensive.Orm/Orm/Linq/MemberType.cs +++ b/Orm/Xtensive.Orm/Orm/Linq/MemberType.cs @@ -8,7 +8,6 @@ namespace Xtensive.Orm.Linq { - [Serializable] internal enum MemberType { Default = Unknown, diff --git a/Orm/Xtensive.Orm/Orm/Linq/ParameterizedQuery.cs b/Orm/Xtensive.Orm/Orm/Linq/ParameterizedQuery.cs index 202d2b3332..0c5f079006 100644 --- a/Orm/Xtensive.Orm/Orm/Linq/ParameterizedQuery.cs +++ b/Orm/Xtensive.Orm/Orm/Linq/ParameterizedQuery.cs @@ -9,7 +9,6 @@ namespace Xtensive.Orm.Linq { - [Serializable] internal sealed class ParameterizedQuery : TranslatedQuery { public readonly Parameter QueryParameter; diff --git a/Orm/Xtensive.Orm/Orm/Linq/RemapContext.cs b/Orm/Xtensive.Orm/Orm/Linq/RemapContext.cs index 8845b632c7..d67268059e 100644 --- a/Orm/Xtensive.Orm/Orm/Linq/RemapContext.cs +++ b/Orm/Xtensive.Orm/Orm/Linq/RemapContext.cs @@ -10,7 +10,6 @@ namespace Xtensive.Orm.Linq { - [Serializable] internal class RemapContext { public ParameterExpression SubqueryParameterExpression { get; set; } diff --git a/Orm/Xtensive.Orm/Orm/Linq/RemapScope.cs b/Orm/Xtensive.Orm/Orm/Linq/RemapScope.cs index 0bdbdf50bd..be4f812354 100644 --- a/Orm/Xtensive.Orm/Orm/Linq/RemapScope.cs +++ b/Orm/Xtensive.Orm/Orm/Linq/RemapScope.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Linq { - [Serializable] internal class RemapScope : Scope { /// diff --git a/Orm/Xtensive.Orm/Orm/Linq/SubQuery.cs b/Orm/Xtensive.Orm/Orm/Linq/SubQuery.cs index 32da8bd58c..589b0469e2 100644 --- a/Orm/Xtensive.Orm/Orm/Linq/SubQuery.cs +++ b/Orm/Xtensive.Orm/Orm/Linq/SubQuery.cs @@ -19,15 +19,14 @@ namespace Xtensive.Orm.Linq { - [Serializable] internal class SubQuery : IOrderedQueryable, IOrderedEnumerable { private readonly ProjectionExpression projectionExpression; + private readonly QueryProvider provider; private DelayedQuery delayedQuery; private List materializedSequence; - private readonly QueryProvider provider; public IOrderedEnumerable CreateOrderedEnumerable(Func keySelector, IComparer comparer, bool descending) { @@ -36,7 +35,7 @@ public IOrderedEnumerable CreateOrderedEnumerable(Func GetEnumerator() { - if (materializedSequence == null) + if (materializedSequence is null) materializedSequence = delayedQuery.ToList(); return materializedSequence.GetEnumerator(); } @@ -46,24 +45,15 @@ IEnumerator IEnumerable.GetEnumerator() return GetEnumerator(); } - public Expression Expression - { - get { return projectionExpression; } - } + public Expression Expression => projectionExpression; - public Type ElementType - { - get { return typeof (TElement); } - } + public Type ElementType => typeof(TElement); - public IQueryProvider Provider - { - get { return provider; } - } + public IQueryProvider Provider => provider; private void MaterializeSelf() { - if (materializedSequence != null) + if (materializedSequence is not null) return; materializedSequence = delayedQuery.ToList(); delayedQuery = null; @@ -76,7 +66,7 @@ private void MaterializeSelf() public SubQuery(ProjectionExpression projectionExpression, TranslatedQuery query, Parameter parameter, Tuple tuple, ItemMaterializationContext context) // ReSharper restore MemberCanBeProtected.Global { - this.provider = context.Session.Query.Provider; + provider = context.Session.Query.Provider; var tupleParameterBindings = new Dictionary, Tuple>(projectionExpression.TupleParameterBindings); var currentTranslatedQuery = query; diff --git a/Orm/Xtensive.Orm/Orm/Metadata/Assembly.cs b/Orm/Xtensive.Orm/Orm/Metadata/Assembly.cs index da4c0ef275..41b423e1de 100644 --- a/Orm/Xtensive.Orm/Orm/Metadata/Assembly.cs +++ b/Orm/Xtensive.Orm/Orm/Metadata/Assembly.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Metadata /// Persistent descriptor of an assembly with registered persistent types. /// Used for schema upgrade purposes. /// - [Serializable] [SystemType(2)] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] diff --git a/Orm/Xtensive.Orm/Orm/Metadata/Extension.cs b/Orm/Xtensive.Orm/Orm/Metadata/Extension.cs index 6e0179bd37..754aa3fdcd 100644 --- a/Orm/Xtensive.Orm/Orm/Metadata/Extension.cs +++ b/Orm/Xtensive.Orm/Orm/Metadata/Extension.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Metadata /// /// Persistent value of any kind indentified by its . /// - [Serializable] [SystemType(3)] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] diff --git a/Orm/Xtensive.Orm/Orm/Metadata/MetadataBase.cs b/Orm/Xtensive.Orm/Orm/Metadata/MetadataBase.cs index d006f21e4d..e19dd0b38b 100644 --- a/Orm/Xtensive.Orm/Orm/Metadata/MetadataBase.cs +++ b/Orm/Xtensive.Orm/Orm/Metadata/MetadataBase.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Metadata /// /// Abstract base class for any metadata type. /// - [Serializable] public abstract class MetadataBase : Entity { /// Object is read-only. diff --git a/Orm/Xtensive.Orm/Orm/Metadata/Type.cs b/Orm/Xtensive.Orm/Orm/Metadata/Type.cs index a84845dc38..4cd5f4fcc3 100644 --- a/Orm/Xtensive.Orm/Orm/Metadata/Type.cs +++ b/Orm/Xtensive.Orm/Orm/Metadata/Type.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Metadata /// /// Persistent descriptor of registered type. /// - [Serializable] [SystemType(1)] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] diff --git a/Orm/Xtensive.Orm/Orm/Model/AssociationInfo.cs b/Orm/Xtensive.Orm/Orm/Model/AssociationInfo.cs index e30f4cc7e5..b67bd0745f 100644 --- a/Orm/Xtensive.Orm/Orm/Model/AssociationInfo.cs +++ b/Orm/Xtensive.Orm/Orm/Model/AssociationInfo.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Model /// /// Describes single association. /// - [Serializable] public sealed class AssociationInfo : Node { private Multiplicity multiplicity; @@ -30,10 +29,7 @@ public sealed class AssociationInfo : Node /// /// Gets the owner type. /// - public TypeInfo OwnerType - { - get { return OwnerField.ReflectedType; } - } + public TypeInfo OwnerType => OwnerField.ReflectedType; /// /// Gets the owner field. @@ -62,10 +58,7 @@ public TypeInfo AuxiliaryType /// Gets or sets ancestor association. /// /// The ancestor. - public NodeCollection Ancestors - { - get { return ancestors; } - } + public NodeCollection Ancestors => ancestors; /// /// Gets the underlying index for this instance. @@ -92,18 +85,12 @@ public bool IsMaster /// /// Gets a value indicating whether this instance is paired. /// - public bool IsPaired - { - get { return reversed!=null; } - } + public bool IsPaired => reversed is not null; /// /// Gets a value indicating whether this instance represents a loop. /// - public bool IsLoop - { - get { return IsPaired && Reversed == this; } - } + public bool IsLoop => IsPaired && Reversed == this; /// /// Gets master association. @@ -118,8 +105,8 @@ public AssociationInfo Master { if (isMaster) return this; - if (reversed==null || !reversed.isMaster) - throw new InvalidOperationException(String.Format(Strings.ExUnableToFindMasterAssociation, Name)); + if (reversed is null || !reversed.isMaster) + throw new InvalidOperationException(string.Format(Strings.ExUnableToFindMasterAssociation, Name)); return reversed; } } @@ -184,7 +171,7 @@ public OnRemoveAction? OnOwnerRemove public Tuple ExtractForeignKey(TypeInfo type, Tuple tuple) { // foreignKeyExtractor can be null if OwnerType is interface - if (foreignKeyExtractor != null) + if (foreignKeyExtractor is not null) return foreignKeyExtractor.Apply(TupleTransformType.TransformedTuple, tuple); if (OwnerType.IsInterface) { diff --git a/Orm/Xtensive.Orm/Orm/Model/AssociationInfoCollection.cs b/Orm/Xtensive.Orm/Orm/Model/AssociationInfoCollection.cs index f8027b4e40..97224bd3c1 100644 --- a/Orm/Xtensive.Orm/Orm/Model/AssociationInfoCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Model/AssociationInfoCollection.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Model /// /// A collection of objects. /// - [Serializable] public sealed class AssociationInfoCollection : NodeCollection { /// diff --git a/Orm/Xtensive.Orm/Orm/Model/ColumnGroup.cs b/Orm/Xtensive.Orm/Orm/Model/ColumnGroup.cs index c77ba3312c..fb0fd96ef5 100644 --- a/Orm/Xtensive.Orm/Orm/Model/ColumnGroup.cs +++ b/Orm/Xtensive.Orm/Orm/Model/ColumnGroup.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Model /// /// Describes a group of columns that belongs to the specified . /// - [Serializable] [DebuggerDisplay("Type = {TypeInfoRef}, Keys = {Keys}, Columns = {Columns}")] public readonly struct ColumnGroup { @@ -23,17 +22,17 @@ public readonly struct ColumnGroup /// Gets the pointing to /// this column group belongs to. /// - public TypeInfoRef TypeInfoRef { get; } + public readonly TypeInfoRef TypeInfoRef; /// /// Gets the indexes of key columns. /// - public IReadOnlyList Keys { get; } + public readonly IReadOnlyList Keys; /// /// Gets the indexes of all columns. /// - public IReadOnlyList Columns { get; } + public readonly IReadOnlyList Columns; // Constructors diff --git a/Orm/Xtensive.Orm/Orm/Model/ColumnIndexMap.cs b/Orm/Xtensive.Orm/Orm/Model/ColumnIndexMap.cs index 9e49ed67c6..a5764e8827 100644 --- a/Orm/Xtensive.Orm/Orm/Model/ColumnIndexMap.cs +++ b/Orm/Xtensive.Orm/Orm/Model/ColumnIndexMap.cs @@ -13,23 +13,22 @@ namespace Xtensive.Orm.Model /// /// A map of useful column indexes. /// - [Serializable] public readonly struct ColumnIndexMap { /// /// Gets or sets positions of system columns within . /// - public IReadOnlyList System { get; } + public readonly IReadOnlyList System; /// /// Gets or sets positions of lazy load columns within . /// - public IReadOnlyList LazyLoad { get; } + public readonly IReadOnlyList LazyLoad; /// /// Gets or sets positions of regular columns (not system and not lazy load) within . /// - public IReadOnlyList Regular { get; } + public readonly IReadOnlyList Regular; // Constructors diff --git a/Orm/Xtensive.Orm/Orm/Model/ColumnInfo.cs b/Orm/Xtensive.Orm/Orm/Model/ColumnInfo.cs index cdd0cce972..64f4b74d71 100644 --- a/Orm/Xtensive.Orm/Orm/Model/ColumnInfo.cs +++ b/Orm/Xtensive.Orm/Orm/Model/ColumnInfo.cs @@ -16,7 +16,6 @@ namespace Xtensive.Orm.Model /// Describes a single column. /// [DebuggerDisplay("{Name}; Attributes = {Attributes}")] - [Serializable] public sealed class ColumnInfo : Node, ICloneable { @@ -294,7 +293,7 @@ public ColumnInfo(FieldInfo field) } if (field.IsEnum) { valueType = Enum.GetUnderlyingType(valueType); - if (field.DefaultValue != null) + if (field.DefaultValue is not null) defaultValue = Convert.ChangeType(field.DefaultValue, valueType); } else { diff --git a/Orm/Xtensive.Orm/Orm/Model/ColumnInfoCollection.cs b/Orm/Xtensive.Orm/Orm/Model/ColumnInfoCollection.cs index 3666c2eba5..c71be79f10 100644 --- a/Orm/Xtensive.Orm/Orm/Model/ColumnInfoCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Model/ColumnInfoCollection.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Model /// /// A collection of objects. /// - [Serializable] public sealed class ColumnInfoCollection : NodeCollection, IFilterable { diff --git a/Orm/Xtensive.Orm/Orm/Model/ColumnInfoRef.cs b/Orm/Xtensive.Orm/Orm/Model/ColumnInfoRef.cs index b3500f781d..b243f24450 100644 --- a/Orm/Xtensive.Orm/Orm/Model/ColumnInfoRef.cs +++ b/Orm/Xtensive.Orm/Orm/Model/ColumnInfoRef.cs @@ -16,29 +16,28 @@ namespace Xtensive.Orm.Model /// /// Loosely-coupled reference that describes instance. /// - [Serializable] [DebuggerDisplay("TypeName = {TypeName}, FieldName = {FieldName}, ColumnName = {ColumnName}, CultureInfo = {CultureInfo}")] public readonly struct ColumnInfoRef: IEquatable { /// /// Gets type name of reflecting . /// - public string TypeName { get; } + public readonly string TypeName; /// /// Gets name of the . /// - public string FieldName { get; } + public readonly string FieldName; /// /// Gets name of the . /// - public string ColumnName { get; } + public readonly string ColumnName; /// /// Gets info of the . /// - public CultureInfo CultureInfo { get; } + public readonly CultureInfo CultureInfo; /// /// Resolves this instance to object within specified . @@ -61,7 +60,10 @@ public ColumnInfo Resolve(DomainModel model) => /// /// The result of the operator. /// - public static bool operator !=(in ColumnInfoRef x, in ColumnInfoRef y) => !x.Equals(y); + public static bool operator !=(in ColumnInfoRef x, in ColumnInfoRef y) + { + return !x.Equals(y); + } /// /// Implements the operator ==. @@ -71,7 +73,10 @@ public ColumnInfo Resolve(DomainModel model) => /// /// The result of the operator. /// - public static bool operator ==(in ColumnInfoRef x, in ColumnInfoRef y) => x.Equals(y); + public static bool operator ==(in ColumnInfoRef x, in ColumnInfoRef y) + { + return x.Equals(y); + } /// public bool Equals(ColumnInfoRef other) => diff --git a/Orm/Xtensive.Orm/Orm/Model/DomainModel.cs b/Orm/Xtensive.Orm/Orm/Model/DomainModel.cs index 763a54eaed..64e4145c7b 100644 --- a/Orm/Xtensive.Orm/Orm/Model/DomainModel.cs +++ b/Orm/Xtensive.Orm/Orm/Model/DomainModel.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Model /// /// A mapping model of storage. /// - [Serializable] public sealed class DomainModel : Node { /// diff --git a/Orm/Xtensive.Orm/Orm/Model/FieldInfo.cs b/Orm/Xtensive.Orm/Orm/Model/FieldInfo.cs index 9940dbae41..4250ee8e34 100644 --- a/Orm/Xtensive.Orm/Orm/Model/FieldInfo.cs +++ b/Orm/Xtensive.Orm/Orm/Model/FieldInfo.cs @@ -21,7 +21,6 @@ namespace Xtensive.Orm.Model /// Describes a single field. /// [DebuggerDisplay("{Name}; Attributes = {Attributes}")] - [Serializable] public sealed class FieldInfo : MappedNode, ICloneable { diff --git a/Orm/Xtensive.Orm/Orm/Model/FieldInfoCollection.cs b/Orm/Xtensive.Orm/Orm/Model/FieldInfoCollection.cs index 70e20bc35d..596ef9761b 100644 --- a/Orm/Xtensive.Orm/Orm/Model/FieldInfoCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Model/FieldInfoCollection.cs @@ -16,7 +16,6 @@ namespace Xtensive.Orm.Model /// /// A collection of objects. /// - [Serializable] public sealed class FieldInfoCollection : NodeCollection, IFilterable diff --git a/Orm/Xtensive.Orm/Orm/Model/FieldInfoRef.cs b/Orm/Xtensive.Orm/Orm/Model/FieldInfoRef.cs index 77f6541816..09baa36553 100644 --- a/Orm/Xtensive.Orm/Orm/Model/FieldInfoRef.cs +++ b/Orm/Xtensive.Orm/Orm/Model/FieldInfoRef.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Model /// /// Loosely-coupled reference that describes instance. /// - [Serializable] [DebuggerDisplay("TypeName = {TypeName}, FieldName = {FieldName}")] public sealed class FieldInfoRef : IEquatable { @@ -37,8 +36,7 @@ public sealed class FieldInfoRef : IEquatable public FieldInfo Resolve(DomainModel model) { var type = TypeRef.Resolve(model); - FieldInfo field; - if (!type.Fields.TryGetValue(FieldName, out field)) + if (!type.Fields.TryGetValue(FieldName, out var field)) throw new InvalidOperationException(string.Format(Strings.ExCouldNotResolveXYWithinDomain, "field", FieldName)); return field; } @@ -106,10 +104,7 @@ public override int GetHashCode() #endregion /// - public override string ToString() - { - return string.Format(ToStringFormat, TypeRef.TypeName, FieldName); - } + public override string ToString() => string.Format(ToStringFormat, TypeRef.TypeName, FieldName); // Constructors diff --git a/Orm/Xtensive.Orm/Orm/Model/FieldMap.cs b/Orm/Xtensive.Orm/Orm/Model/FieldMap.cs index f1f55feda8..5a02ef76cf 100644 --- a/Orm/Xtensive.Orm/Orm/Model/FieldMap.cs +++ b/Orm/Xtensive.Orm/Orm/Model/FieldMap.cs @@ -15,43 +15,32 @@ namespace Xtensive.Orm.Model /// /// Maps type fields to interface fields and vice versa. /// - [Serializable] public sealed class FieldMap: LockableBase, IEnumerable> { internal static readonly FieldMap Empty; - private readonly Dictionary map = new Dictionary(); - private readonly Dictionary> reversedMap = new Dictionary>(); + private readonly Dictionary map = new(); + private readonly Dictionary> reversedMap = new(); - public FieldInfo this[FieldInfo interfaceField] - { - get { return map[interfaceField]; } - } + public FieldInfo this[FieldInfo interfaceField] => map[interfaceField]; public IEnumerable GetImplementedInterfaceFields(FieldInfo typeField) { - HashSet value; - if (!reversedMap.TryGetValue(typeField, out value)) + if (!reversedMap.TryGetValue(typeField, out var value)) return Enumerable.Empty(); return value; } - public int Count - { - get { return map.Count; } - } + public int Count => map.Count; - public bool ContainsKey(FieldInfo interfaceField) - { - return map.ContainsKey(interfaceField); - } + public bool ContainsKey(FieldInfo interfaceField) => map.ContainsKey(interfaceField); public void Add(FieldInfo interfaceField, FieldInfo typeField) { EnsureNotLocked(); map.Add(interfaceField, typeField); if (reversedMap.TryGetValue(typeField, out var interfaceFields)) { - interfaceFields.Add(interfaceField); + _ = interfaceFields.Add(interfaceField); } else reversedMap.Add(typeField, new HashSet { interfaceField }); @@ -63,24 +52,17 @@ public void Override(FieldInfo interfaceField, FieldInfo typeField) var oldTypeField = map[interfaceField]; var interfaceFields = reversedMap[oldTypeField]; map[interfaceField] = typeField; - reversedMap.Remove(oldTypeField); + _ = reversedMap.Remove(oldTypeField); reversedMap.Add(typeField, interfaceFields); } public bool TryGetValue(FieldInfo interfaceField, out FieldInfo typeField) - { - return map.TryGetValue(interfaceField, out typeField); - } + => map.TryGetValue(interfaceField, out typeField); IEnumerator> IEnumerable>.GetEnumerator() - { - return map.GetEnumerator(); - } + => map.GetEnumerator(); - IEnumerator IEnumerable.GetEnumerator() - { - return ((IEnumerable>) this).GetEnumerator(); - } + IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable>) this).GetEnumerator(); // Constructors diff --git a/Orm/Xtensive.Orm/Orm/Model/FullTextColumnInfo.cs b/Orm/Xtensive.Orm/Orm/Model/FullTextColumnInfo.cs index 5331780d3d..df951f8976 100644 --- a/Orm/Xtensive.Orm/Orm/Model/FullTextColumnInfo.cs +++ b/Orm/Xtensive.Orm/Orm/Model/FullTextColumnInfo.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Model /// /// Describes single column in full-text index. /// - [Serializable] public sealed class FullTextColumnInfo : Node { public ColumnInfo Column { get; private set; } diff --git a/Orm/Xtensive.Orm/Orm/Model/FullTextColumnInfoCollection.cs b/Orm/Xtensive.Orm/Orm/Model/FullTextColumnInfoCollection.cs index c0fcdc2f77..deeb2ff1fd 100644 --- a/Orm/Xtensive.Orm/Orm/Model/FullTextColumnInfoCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Model/FullTextColumnInfoCollection.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Model /// /// A collection of objects. /// - [Serializable] public sealed class FullTextColumnInfoCollection : NodeCollection { diff --git a/Orm/Xtensive.Orm/Orm/Model/FullTextIndexInfo.cs b/Orm/Xtensive.Orm/Orm/Model/FullTextIndexInfo.cs index 0d043571b8..ac447d6a32 100644 --- a/Orm/Xtensive.Orm/Orm/Model/FullTextIndexInfo.cs +++ b/Orm/Xtensive.Orm/Orm/Model/FullTextIndexInfo.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Model /// /// Describes a single full-text index. /// - [Serializable] public sealed class FullTextIndexInfo : Node { private readonly IndexInfo primaryIndex; @@ -21,18 +20,12 @@ public sealed class FullTextIndexInfo : Node /// /// Gets the primary index. /// - public IndexInfo PrimaryIndex - { - get { return primaryIndex; } - } + public IndexInfo PrimaryIndex => primaryIndex; /// /// Gets the full-text index columns. /// - public FullTextColumnInfoCollection Columns - { - get { return columns; } - } + public FullTextColumnInfoCollection Columns => columns; /// public override void Lock(bool recursive) diff --git a/Orm/Xtensive.Orm/Orm/Model/FullTextIndexInfoCollection.cs b/Orm/Xtensive.Orm/Orm/Model/FullTextIndexInfoCollection.cs index c2c3894938..40cd9a6e4c 100644 --- a/Orm/Xtensive.Orm/Orm/Model/FullTextIndexInfoCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Model/FullTextIndexInfoCollection.cs @@ -15,21 +15,20 @@ namespace Xtensive.Orm.Model /// /// A collection of objects. /// - [Serializable] public sealed class FullTextIndexInfoCollection : LockableBase, IEnumerable { - private readonly HashSet container = new HashSet(); - private readonly Dictionary indexMap = new Dictionary(); + private readonly HashSet container = new(); + private readonly Dictionary indexMap = new(); /// /// Gets the by the specified type. /// /// Index is not found. - public FullTextIndexInfo this[TypeInfo type] { + public FullTextIndexInfo this[TypeInfo type] + { get { - FullTextIndexInfo fulltextIndex; - if (!TryGetValue(type, out fulltextIndex)) + if (!TryGetValue(type, out var fulltextIndex)) throw new KeyNotFoundException(); return fulltextIndex; } @@ -42,9 +41,7 @@ public FullTextIndexInfo this[TypeInfo type] { /// The full text index info. /// when the full-text index is found; otherwise . public bool TryGetValue(TypeInfo typeInfo, out FullTextIndexInfo fullTextIndexInfo) - { - return indexMap.TryGetValue(typeInfo, out fullTextIndexInfo); - } + => indexMap.TryGetValue(typeInfo, out fullTextIndexInfo); /// /// Registers specified full-text index by type key. @@ -54,23 +51,17 @@ public bool TryGetValue(TypeInfo typeInfo, out FullTextIndexInfo fullTextIndexIn public void Add(TypeInfo typeInfo, FullTextIndexInfo fullTextIndexInfo) { EnsureNotLocked(); - container.Add(fullTextIndexInfo); + _ = container.Add(fullTextIndexInfo); indexMap.Add(typeInfo, fullTextIndexInfo); } #region IEnumerable<...> members /// - public IEnumerator GetEnumerator() - { - return container.ToList().GetEnumerator(); - } + public IEnumerator GetEnumerator() => container.ToList().GetEnumerator(); /// - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion } diff --git a/Orm/Xtensive.Orm/Orm/Model/HierarchyInfo.cs b/Orm/Xtensive.Orm/Orm/Model/HierarchyInfo.cs index 7ced941373..817e0ee614 100644 --- a/Orm/Xtensive.Orm/Orm/Model/HierarchyInfo.cs +++ b/Orm/Xtensive.Orm/Orm/Model/HierarchyInfo.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Model /// /// Describes a single persistent type hierarchy. /// - [Serializable] public sealed class HierarchyInfo : Node { /// diff --git a/Orm/Xtensive.Orm/Orm/Model/HierarchyInfoCollection.cs b/Orm/Xtensive.Orm/Orm/Model/HierarchyInfoCollection.cs index fe661448a1..fe7d4637ff 100644 --- a/Orm/Xtensive.Orm/Orm/Model/HierarchyInfoCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Model/HierarchyInfoCollection.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Model /// /// A collection of objects. /// - [Serializable] public sealed class HierarchyInfoCollection : NodeCollection { /// diff --git a/Orm/Xtensive.Orm/Orm/Model/IndexInfo.cs b/Orm/Xtensive.Orm/Orm/Model/IndexInfo.cs index 569873d979..445f088370 100644 --- a/Orm/Xtensive.Orm/Orm/Model/IndexInfo.cs +++ b/Orm/Xtensive.Orm/Orm/Model/IndexInfo.cs @@ -20,7 +20,6 @@ namespace Xtensive.Orm.Model /// Describes a single index in terms of storage. /// [DebuggerDisplay("{Name}; Attributes = {Attributes}.")] - [Serializable] public sealed class IndexInfo : MappedNode, IDisposable { private IndexAttributes attributes; diff --git a/Orm/Xtensive.Orm/Orm/Model/IndexInfoCollection.cs b/Orm/Xtensive.Orm/Orm/Model/IndexInfoCollection.cs index a5988b8ec3..ad14e55211 100644 --- a/Orm/Xtensive.Orm/Orm/Model/IndexInfoCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Model/IndexInfoCollection.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Model /// /// A collection of objects. /// - [Serializable] public class IndexInfoCollection: NodeCollection, IFilterable { diff --git a/Orm/Xtensive.Orm/Orm/Model/IndexInfoRef.cs b/Orm/Xtensive.Orm/Orm/Model/IndexInfoRef.cs index 12ad5cd538..2d1fe3f762 100644 --- a/Orm/Xtensive.Orm/Orm/Model/IndexInfoRef.cs +++ b/Orm/Xtensive.Orm/Orm/Model/IndexInfoRef.cs @@ -17,7 +17,6 @@ namespace Xtensive.Orm.Model /// /// Loosely-coupled reference that describes instance. /// - [Serializable] [DebuggerDisplay("IndexName = {IndexName}, TypeName = {TypeName}")] public sealed class IndexInfoRef { @@ -33,6 +32,9 @@ public sealed class IndexInfoRef /// public string TypeName { get; private set; } + /// + /// Gets the tuple descriptor containing just key columns. + /// public TupleDescriptor KeyTupleDescriptor { get; private set; } /// @@ -41,13 +43,11 @@ public sealed class IndexInfoRef /// Domain model. public IndexInfo Resolve(DomainModel model) { - TypeInfo type; - if (!model.Types.TryGetValue(TypeName, out type)) + if (!model.Types.TryGetValue(TypeName, out var type)) throw new InvalidOperationException(string.Format(Strings.ExCouldNotResolveXYWithinDomain, "type", TypeName)); - IndexInfo index; - if (!type.Indexes.TryGetValue(IndexName, out index)) { + if (!type.Indexes.TryGetValue(IndexName, out var index)) { var hierarchy = type.Hierarchy; - if (hierarchy != null && hierarchy.InheritanceSchema == InheritanceSchema.SingleTable && hierarchy.Root.Indexes.TryGetValue(IndexName, out index)) + if (hierarchy != null && hierarchy.InheritanceSchema == InheritanceSchema.SingleTable && hierarchy.Root.Indexes.TryGetValue(IndexName, out index)) return index; throw new InvalidOperationException(string.Format(Strings.ExCouldNotResolveXYWithinDomain, "index", IndexName)); } @@ -124,10 +124,7 @@ public override int GetHashCode() #endregion /// - public override string ToString() - { - return string.Format(ToStringFormat, IndexName, TypeName); - } + public override string ToString() => string.Format(ToStringFormat, IndexName, TypeName); // Constructors @@ -138,7 +135,7 @@ public override string ToString() /// object to make reference for. public IndexInfoRef(IndexInfo indexInfo) { - IndexName = indexInfo.Name; + IndexName = indexInfo.Name; TypeName = indexInfo.ReflectedType.Name; KeyTupleDescriptor = indexInfo.KeyTupleDescriptor; } diff --git a/Orm/Xtensive.Orm/Orm/Model/KeyField.cs b/Orm/Xtensive.Orm/Orm/Model/KeyField.cs index 1856846ce9..8cad219a1e 100644 --- a/Orm/Xtensive.Orm/Orm/Model/KeyField.cs +++ b/Orm/Xtensive.Orm/Orm/Model/KeyField.cs @@ -13,13 +13,12 @@ namespace Xtensive.Orm.Model /// /// Describes a field that is a part of a primary key. /// - [Serializable] public sealed class KeyField : Node { /// /// Gets or sets the direction. /// - public Direction Direction { get; private set; } + public Direction Direction { get; } /// public override int GetHashCode() diff --git a/Orm/Xtensive.Orm/Orm/Model/KeyInfo.cs b/Orm/Xtensive.Orm/Orm/Model/KeyInfo.cs index a3ef2a6fad..c353f17f6a 100644 --- a/Orm/Xtensive.Orm/Orm/Model/KeyInfo.cs +++ b/Orm/Xtensive.Orm/Orm/Model/KeyInfo.cs @@ -18,9 +18,9 @@ namespace Xtensive.Orm.Model /// /// Describes key for a particular . /// - [Serializable] public sealed class KeyInfo : Node { + private readonly Type singleColumnType; private HierarchyInfo hierarchy; private SequenceInfo sequence; private object equalityIdentifier; @@ -28,7 +28,7 @@ public sealed class KeyInfo : Node private string generatorName; private string generatorBaseName; private KeyGeneratorKind generatorKind; - private Type singleColumnType; + /// /// Gets single column type if this @@ -36,14 +36,14 @@ public sealed class KeyInfo : Node /// If this has multiple columns /// returns . /// - public Type SingleColumnType { get { return singleColumnType; } } + public Type SingleColumnType => singleColumnType; /// /// Gets the hierarchy this key belongs to. /// public HierarchyInfo Hierarchy { - get { return hierarchy; } + get => hierarchy; set { EnsureNotLocked(); hierarchy = value; @@ -53,12 +53,12 @@ public HierarchyInfo Hierarchy /// /// Gets the fields forming the key. /// - public IReadOnlyList Fields { get; private set; } + public IReadOnlyList Fields { get; } /// /// Gets the columns forming the key. /// - public IReadOnlyList Columns { get; private set; } + public IReadOnlyList Columns { get; } /// /// Gets the key generator name. @@ -66,9 +66,8 @@ public HierarchyInfo Hierarchy /// public string GeneratorName { - get { return generatorName; } - set - { + get => generatorName; + set { EnsureNotLocked(); generatorName = value; } @@ -81,9 +80,8 @@ public string GeneratorName /// public string GeneratorBaseName { - get { return generatorBaseName; } - set - { + get => generatorBaseName; + set { EnsureNotLocked(); generatorBaseName = value; } @@ -94,9 +92,8 @@ public string GeneratorBaseName /// public KeyGeneratorKind GeneratorKind { - get { return generatorKind; } - set - { + get => generatorKind; + set { EnsureNotLocked(); generatorKind = value; } @@ -107,24 +104,25 @@ public KeyGeneratorKind GeneratorKind /// Gets the tuple descriptor of the key. /// /// - public TupleDescriptor TupleDescriptor { get; private set; } + public TupleDescriptor TupleDescriptor { get; } /// /// Gets the index of the column related to field with ==. /// If there is no such field, returns . /// - public int TypeIdColumnIndex { get; private set; } + public int TypeIdColumnIndex { get; } /// /// Gets or sets a value indicating whether key contains foreign keys. /// - public bool ContainsForeignKeys { get; private set; } + public bool ContainsForeignKeys { get; } /// /// Gets the information on associated sequence. /// - public SequenceInfo Sequence { - get { return sequence; } + public SequenceInfo Sequence + { + get => sequence; set { EnsureNotLocked(); sequence = value; @@ -137,7 +135,7 @@ public SequenceInfo Sequence { /// public bool IsFirstAmongSimilarKeys { - get { return isFirstAmongSimilarKeys; } + get => isFirstAmongSimilarKeys; set { EnsureNotLocked(); isFirstAmongSimilarKeys = value; @@ -153,7 +151,7 @@ public bool IsFirstAmongSimilarKeys /// public object EqualityIdentifier { - get { return equalityIdentifier; } + get => equalityIdentifier; set { EnsureNotLocked(); equalityIdentifier = value; @@ -164,24 +162,22 @@ public object EqualityIdentifier public override void UpdateState() { base.UpdateState(); - if (Sequence!=null) - Sequence.UpdateState(); + Sequence?.UpdateState(); } /// /// Hierarchy must be set before locking this instance. public override void Lock(bool recursive) { - if (Hierarchy==null) - throw Exceptions.NotInitialized("Hierarchy"); - if (EqualityIdentifier==null) - throw Exceptions.NotInitialized("EqualityIdentifier"); + if (Hierarchy is null) + throw Exceptions.NotInitialized(nameof(Hierarchy)); + if (EqualityIdentifier is null) + throw Exceptions.NotInitialized(nameof(EqualityIdentifier)); base.Lock(recursive); if (!recursive) return; // Hierarchy.Lock() is not necessary, because it isn't a contained object (= likely, already locked) - if (Sequence!=null) - Sequence.Lock(true); + Sequence?.Lock(true); } @@ -205,7 +201,7 @@ public KeyInfo(string name, IList fields, IList columns, TupleDescriptor = tupleDescriptor; TypeIdColumnIndex = typeIdColumnIndex; - ContainsForeignKeys = fields.Any(f => f.Parent!=null); + ContainsForeignKeys = fields.Any(static f => f.Parent is not null); if (Columns.Where((c, i) => i!=TypeIdColumnIndex).Count()==1) singleColumnType = Columns.Where((c, i) => i!=TypeIdColumnIndex).First().ValueType; diff --git a/Orm/Xtensive.Orm/Orm/Model/MappedNode.cs b/Orm/Xtensive.Orm/Orm/Model/MappedNode.cs index a3a75ddf5e..2496771ad4 100644 --- a/Orm/Xtensive.Orm/Orm/Model/MappedNode.cs +++ b/Orm/Xtensive.Orm/Orm/Model/MappedNode.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Model /// /// A that can be mapped to existing named node. /// - [Serializable] public abstract class MappedNode : Node { private string mappingName; @@ -22,9 +21,8 @@ public abstract class MappedNode : Node /// public string MappingName { - get { return mappingName; } - set - { + get => mappingName; + set { EnsureNotLocked(); ValidateName(value); mappingName = value; diff --git a/Orm/Xtensive.Orm/Orm/Model/ModelVisitor.cs b/Orm/Xtensive.Orm/Orm/Model/ModelVisitor.cs index 71ecc7dedd..a67d2eeada 100644 --- a/Orm/Xtensive.Orm/Orm/Model/ModelVisitor.cs +++ b/Orm/Xtensive.Orm/Orm/Model/ModelVisitor.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Model /// An abstract base class for all visitors. /// /// The type of the result. - [Serializable] public abstract class ModelVisitor { /// diff --git a/Orm/Xtensive.Orm/Orm/Model/Node.cs b/Orm/Xtensive.Orm/Orm/Model/Node.cs index 5dd5521a68..3b40bd7b10 100644 --- a/Orm/Xtensive.Orm/Orm/Model/Node.cs +++ b/Orm/Xtensive.Orm/Orm/Model/Node.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Model /// ///An abstract base class for model node. /// - [Serializable] public abstract class Node : LockableBase, IChangeNotifier, diff --git a/Orm/Xtensive.Orm/Orm/Model/NodeCollection.cs b/Orm/Xtensive.Orm/Orm/Model/NodeCollection.cs index 687dda668b..837de40691 100644 --- a/Orm/Xtensive.Orm/Orm/Model/NodeCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Model/NodeCollection.cs @@ -16,15 +16,14 @@ namespace Xtensive.Orm.Model /// A base class for collection of nodes in model. /// /// The type of the node. - [Serializable] public class NodeCollection : CollectionBaseSlim where TNode: Node { - [NonSerialized, DebuggerBrowsable(DebuggerBrowsableState.Never)] - private EventHandler itemChangedHandler; + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private readonly EventHandler itemChangedHandler; - [NonSerialized, DebuggerBrowsable(DebuggerBrowsableState.Never)] - private EventHandler itemChangingHandler; + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private readonly EventHandler itemChangingHandler; protected readonly Dictionary NameIndex; @@ -46,9 +45,10 @@ public class NodeCollection : CollectionBaseSlim /// /// Gets the full name. /// - public string FullName { + public string FullName + { get { - return Owner==null + return Owner is null ? Name : string.Format(Strings.NodeCollectionFullNameFormat, Owner.Name, Name); } @@ -91,7 +91,7 @@ public override bool Remove(TNode item) { if (base.Remove(item)) { TryUnsubscribe(item); - NameIndex.Remove(item.Name); + _ = NameIndex.Remove(item.Name); return true; } return false; @@ -126,10 +126,7 @@ public virtual void UpdateState() /// if this instance contains the specified key; otherwise, . /// [DebuggerStepThrough] - public bool Contains(string key) - { - return NameIndex.ContainsKey(key); - } + public bool Contains(string key) => NameIndex.ContainsKey(key); /// @@ -139,10 +136,7 @@ public bool Contains(string key) /// if it was found; otherwise . /// if value is found by specified ; otherwise . [DebuggerStepThrough] - public bool TryGetValue(string key, out TNode value) - { - return NameIndex.TryGetValue(key, out value); - } + public bool TryGetValue(string key, out TNode value) => NameIndex.TryGetValue(key, out value); /// /// An indexer that provides access to collection items. @@ -161,9 +155,7 @@ public TNode this[string key] } protected virtual string GetExceptionMessage(string key) - { - return string.Format(Strings.ExItemWithKeyXWasNotFound, key); - } + => string.Format(Strings.ExItemWithKeyXWasNotFound, key); /// /// Tries to subscribe the collection on diff --git a/Orm/Xtensive.Orm/Orm/Model/OnRemoveAction.cs b/Orm/Xtensive.Orm/Orm/Model/OnRemoveAction.cs index 0dcdf8fec0..8c3031c0f7 100644 --- a/Orm/Xtensive.Orm/Orm/Model/OnRemoveAction.cs +++ b/Orm/Xtensive.Orm/Orm/Model/OnRemoveAction.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm /// /// Defines actions that can be taken to preserve referential integrity. /// - [Serializable] public enum OnRemoveAction { /// diff --git a/Orm/Xtensive.Orm/Orm/Model/SchemaMappedNode.cs b/Orm/Xtensive.Orm/Orm/Model/SchemaMappedNode.cs index dd4424799f..108d9ec7cd 100644 --- a/Orm/Xtensive.Orm/Orm/Model/SchemaMappedNode.cs +++ b/Orm/Xtensive.Orm/Orm/Model/SchemaMappedNode.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2012 Xtensive LLC. +// Copyright (C) 2012 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Denis Krjuchkov @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Model /// /// A that is mapped to existing database schema node. /// - [Serializable] public abstract class SchemaMappedNode : MappedNode { private string mappingDatabase; @@ -23,9 +22,8 @@ public abstract class SchemaMappedNode : MappedNode /// public string MappingDatabase { - get { return mappingDatabase; } - set - { + get => mappingDatabase; + set { EnsureNotLocked(); mappingDatabase = value; } @@ -36,9 +34,8 @@ public string MappingDatabase /// public string MappingSchema { - get { return mappingSchema; } - set - { + get => mappingSchema; + set { EnsureNotLocked(); mappingSchema = value; } diff --git a/Orm/Xtensive.Orm/Orm/Model/TypeDiscriminatorMap.cs b/Orm/Xtensive.Orm/Orm/Model/TypeDiscriminatorMap.cs index 0977594230..18e6356595 100644 --- a/Orm/Xtensive.Orm/Orm/Model/TypeDiscriminatorMap.cs +++ b/Orm/Xtensive.Orm/Orm/Model/TypeDiscriminatorMap.cs @@ -15,43 +15,33 @@ namespace Xtensive.Orm.Model /// /// Type discriminator map. /// - [Serializable] public sealed class TypeDiscriminatorMap : Node, IEnumerable> { + private readonly Dictionary map = new(); + private readonly Dictionary reversedMap = new(); private TypeInfo @default; - private readonly Dictionary map = new Dictionary(); - private readonly Dictionary reversedMap = new Dictionary(); private FieldInfo @field; public FieldInfo Field { - get { return @field; } - set - { + get => @field; + set { EnsureNotLocked(); - if (@field != null) + if (@field is not null) throw new InvalidOperationException(Strings.ExTypeDiscriminatorFieldIsAlreadySet); @field = value; } } - public ColumnInfo Column - { - get { return Field.Column; } - } + public ColumnInfo Column => Field.Column; - public TypeInfo Default - { - get { return @default; } - } + public TypeInfo Default => @default; public TypeInfo this[object typeDiscriminatorValue] { - get - { - TypeInfo result; - if (map.TryGetValue(typeDiscriminatorValue, out result)) + get { + if (map.TryGetValue(typeDiscriminatorValue, out var result)) return result; return @default; } @@ -59,10 +49,8 @@ public TypeInfo this[object typeDiscriminatorValue] public object this[TypeInfo typeInfo] { - get - { - object result; - if (reversedMap.TryGetValue(typeInfo, out result)) + get { + if (reversedMap.TryGetValue(typeInfo, out var result)) return result; return null; } @@ -80,17 +68,14 @@ public void RegisterTypeMapping(TypeInfo type, object typeDiscriminatorValue) public void RegisterDefaultType(TypeInfo type) { EnsureNotLocked(); - if (@default != null) + if (@default is not null) throw new InvalidOperationException(Strings.ExDefaultTypeIsAlreadyRegistered); @default = type; } /// - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); /// public IEnumerator> GetEnumerator() diff --git a/Orm/Xtensive.Orm/Orm/Model/TypeIdRegistry.cs b/Orm/Xtensive.Orm/Orm/Model/TypeIdRegistry.cs index e1eab161d6..e54a375cb3 100644 --- a/Orm/Xtensive.Orm/Orm/Model/TypeIdRegistry.cs +++ b/Orm/Xtensive.Orm/Orm/Model/TypeIdRegistry.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Model /// /// Dual-mapping between type identifiers and . /// - [Serializable] public sealed class TypeIdRegistry : LockableBase { private readonly Dictionary mapping = new(); diff --git a/Orm/Xtensive.Orm/Orm/Model/TypeIndexInfoCollection.cs b/Orm/Xtensive.Orm/Orm/Model/TypeIndexInfoCollection.cs index 2911d4b34c..84dfae5401 100644 --- a/Orm/Xtensive.Orm/Orm/Model/TypeIndexInfoCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Model/TypeIndexInfoCollection.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Model /// /// A collection of indexes that belongs to a particular . /// - [Serializable] public sealed class TypeIndexInfoCollection : IndexInfoCollection { private IndexInfo primaryIndex; @@ -27,7 +26,7 @@ public sealed class TypeIndexInfoCollection : IndexInfoCollection public IndexInfo PrimaryIndex { [DebuggerStepThrough] - get { return IsLocked ? primaryIndex : FindPrimaryIndex(); } + get => IsLocked ? primaryIndex : FindPrimaryIndex(); } /// diff --git a/Orm/Xtensive.Orm/Orm/Model/TypeInfo.cs b/Orm/Xtensive.Orm/Orm/Model/TypeInfo.cs index 035c9b3885..014a6e5769 100644 --- a/Orm/Xtensive.Orm/Orm/Model/TypeInfo.cs +++ b/Orm/Xtensive.Orm/Orm/Model/TypeInfo.cs @@ -25,7 +25,6 @@ namespace Xtensive.Orm.Model /// Represents an object describing any persistent type. /// [DebuggerDisplay("{underlyingType}")] - [Serializable] public sealed class TypeInfo : SchemaMappedNode { /// diff --git a/Orm/Xtensive.Orm/Orm/Model/TypeInfoCollection.cs b/Orm/Xtensive.Orm/Orm/Model/TypeInfoCollection.cs index bf2f163a3b..08a6c075cc 100644 --- a/Orm/Xtensive.Orm/Orm/Model/TypeInfoCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Model/TypeInfoCollection.cs @@ -16,7 +16,6 @@ namespace Xtensive.Orm.Model /// /// A collection of objects. /// - [Serializable] public sealed class TypeInfoCollection : NodeCollection, IFilterable diff --git a/Orm/Xtensive.Orm/Orm/Model/TypeInfoRef.cs b/Orm/Xtensive.Orm/Orm/Model/TypeInfoRef.cs index 5e243b8b38..5b8744b8cf 100644 --- a/Orm/Xtensive.Orm/Orm/Model/TypeInfoRef.cs +++ b/Orm/Xtensive.Orm/Orm/Model/TypeInfoRef.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Model /// /// Loosely-coupled reference that describes instance. /// - [Serializable] [DebuggerDisplay("TypeName = {TypeName}")] public readonly struct TypeInfoRef : IEquatable { @@ -35,7 +34,10 @@ public TypeInfo Resolve(DomainModel model) => /// /// Creates reference for . /// - public static implicit operator TypeInfoRef (TypeInfo typeInfo) => new TypeInfoRef(typeInfo); + public static implicit operator TypeInfoRef(TypeInfo typeInfo) + { + return new TypeInfoRef(typeInfo); + } #region Equality members, ==, != @@ -47,7 +49,10 @@ public TypeInfo Resolve(DomainModel model) => /// /// The result of the operator. /// - public static bool operator !=(TypeInfoRef x, TypeInfoRef y) => !Equals(x, y); + public static bool operator !=(TypeInfoRef x, TypeInfoRef y) + { + return !Equals(x, y); + } /// /// Implements the operator ==. @@ -57,7 +62,10 @@ public TypeInfo Resolve(DomainModel model) => /// /// The result of the operator. /// - public static bool operator ==(TypeInfoRef x, TypeInfoRef y) => Equals(x, y); + public static bool operator ==(TypeInfoRef x, TypeInfoRef y) + { + return Equals(x, y); + } /// public bool Equals(TypeInfoRef other) => diff --git a/Orm/Xtensive.Orm/Orm/Operations/EntityFieldSetOperation.cs b/Orm/Xtensive.Orm/Orm/Operations/EntityFieldSetOperation.cs deleted file mode 100644 index e8aa99d59d..0000000000 --- a/Orm/Xtensive.Orm/Orm/Operations/EntityFieldSetOperation.cs +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright (C) 2009-2020 Xtensive LLC. -// This code is distributed under MIT license terms. -// See the License.txt file in the project root for more information. -// Created by: Alexis Kochetov -// Created: 2009.10.22 - -using System; -using System.Diagnostics; -using System.Runtime.Serialization; -using System.Security; -using System.Security.Permissions; -using Xtensive.Core; -using Xtensive.Orm.Internals; -using Xtensive.Tuples; -using Tuple = Xtensive.Tuples.Tuple; -using Xtensive.Orm.Model; -using Xtensive.Orm.Services; - -namespace Xtensive.Orm.Operations -{ - /// - /// Describes field set operation. - /// - [Serializable] - public sealed class EntityFieldSetOperation : EntityFieldOperation - { - /// - /// Gets the new field value, if field is NOT a reference field - /// (i.e. not a field of type). - /// - public object Value { get; set; } - - /// - /// Gets the new field value key, if field is a reference field - /// (i.e. field of type). - /// - public Key ValueKey { get; set; } - - /// - public override string Title { - get { return "Set field"; } - } - - /// - public override string Description { - get - { - return $"{base.Description}, Value = {Value ?? ValueKey}"; - } - } - - /// - protected override void PrepareSelf(OperationExecutionContext context) - { - base.PrepareSelf(context); - // Next line works properly when ValueKey==null - context.RegisterKey(context.TryRemapKey(ValueKey), false); - } - - /// - protected override void ExecuteSelf(OperationExecutionContext context) - { - var session = context.Session; - var key = context.TryRemapKey(Key); - var valueKey = context.TryRemapKey(ValueKey); - var entity = session.Query.Single(key); - var value = ValueKey != null ? session.Query.Single(valueKey) : Value; - entity.SetFieldValue(Field, value); - } - - /// - protected override Operation CloneSelf(Operation clone) - { - if (clone == null) { - if (ValueKey==null) - clone = new EntityFieldSetOperation(Key, Field, Value); - else - clone = new EntityFieldSetOperation(Key, Field, ValueKey); - } - return clone; - } - - - // Constructors - - /// - /// Initializes a new instance of this class.. - /// - /// The key of the changed entity. - /// The field involved into the operation. - /// The new field value. - public EntityFieldSetOperation(Key key, FieldInfo field, object value) - : base(key, field) - { - var entityValue = value as IEntity; - if (entityValue != null) - ValueKey = entityValue.Key; - else - Value = value; - } - - /// - /// Initializes a new instance of this class.. - /// - /// The key of the changed entity. - /// The field involved into the operation. - /// The new field value key. - public EntityFieldSetOperation(Key key, FieldInfo field, Key valueKey) - : base(key, field) - { - ValueKey = valueKey; - } - - - // Serialization - - /// - private EntityFieldSetOperation(SerializationInfo info, StreamingContext context) - : base(info, context) - { - var session = Session.Demand(); - if (WellKnownOrmInterfaces.Entity.IsAssignableFrom(Field.ValueType)) { - // deserializing entity - var value = info.GetString("value"); - if (!value.IsNullOrEmpty()) { - ValueKey = Key.Parse(session.Domain, value); -// ValueKey.TypeReference = new TypeReference(ValueKey.TypeReference.Type, TypeReferenceAccuracy.ExactType); - } - } - else if (WellKnownOrmTypes.Structure.IsAssignableFrom(Field.ValueType)) { - var tuple = (Tuple) info.GetValue("value", WellKnownOrmTypes.Tuple); - Value = session.Services.Get() - .CreateStructure(Field.ValueType, tuple); - } - else - Value = info.GetValue("value", Field.ValueType); - } - - /// - protected override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - var structureValue = Value as Structure; - if (WellKnownOrmInterfaces.Entity.IsAssignableFrom(Field.ValueType)) { - // serializing entity value as key - if (ValueKey != null) - info.AddValue("value", ValueKey.Format()); - else - info.AddValue("value", string.Empty); - } - else if (structureValue != null) { - // serializing structure value as tuple - info.AddValue("value", structureValue.Tuple.ToRegular(), WellKnownOrmTypes.Tuple); - } - else - info.AddValue("value", Value, Field.ValueType); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Operations/EntityIdentifierType.cs b/Orm/Xtensive.Orm/Orm/Operations/EntityIdentifierType.cs index 99e73d8cd7..d58b01caa5 100644 --- a/Orm/Xtensive.Orm/Orm/Operations/EntityIdentifierType.cs +++ b/Orm/Xtensive.Orm/Orm/Operations/EntityIdentifierType.cs @@ -10,7 +10,7 @@ namespace Xtensive.Orm.Operations { /// - /// Possible identifier types for method. + /// Possible identifier types for method. /// public enum EntityIdentifierType { diff --git a/Orm/Xtensive.Orm/Orm/Operations/KeyOperation.cs b/Orm/Xtensive.Orm/Orm/Operations/KeyOperation.cs deleted file mode 100644 index def9302b59..0000000000 --- a/Orm/Xtensive.Orm/Orm/Operations/KeyOperation.cs +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. -// Created by: Alexis Kochetov -// Created: 2009.10.22 - -using System; -using System.Runtime.Serialization; -using System.Security; -using System.Security.Permissions; -using Xtensive.Core; - - -namespace Xtensive.Orm.Operations -{ - /// - /// Describes an operation involving the . - /// - [Serializable] - public abstract class KeyOperation : Operation, - ISerializable - { - /// - /// Gets the key of the entity. - /// - public Key Key { get; private set; } - - /// - public override string Description { - get - { - return $"{Title}, Key = {Key}"; - } - } - - /// - protected override void PrepareSelf(OperationExecutionContext context) - { - context.RegisterKey(context.TryRemapKey(Key), false); - } - - - // Constructors - - /// - /// Initializes a new instance of this class.. - /// - /// The key of the entity. - protected KeyOperation(Key key) - { - Key = key; - } - - // Serialization - - [SecurityCritical] - void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) - { - GetObjectData(info, context); - } - - /// - /// Populates a with the data needed to serialize the target object. - /// - /// The to populate with data. - /// The destination (see ) for this serialization. - /// The caller does not have the required permission. - protected virtual void GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue("Key", Key.Format()); - } - - /// - protected KeyOperation(SerializationInfo info, StreamingContext context) - { - Key = Key.Parse(Domain.Demand(), info.GetString(WellKnown.KeyFieldName)); -// Key.TypeReference = new TypeReference(Key.TypeReference.Type, TypeReferenceAccuracy.ExactType); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Operations/KeySetOperation.cs b/Orm/Xtensive.Orm/Orm/Operations/KeySetOperation.cs deleted file mode 100644 index e4eb0fbafd..0000000000 --- a/Orm/Xtensive.Orm/Orm/Operations/KeySetOperation.cs +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. -// Created by: Alex Yakunin -// Created: 2010.08.10 - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Runtime.Serialization; -using System.Security; -using System.Security.Permissions; -using Xtensive.Core; -using Xtensive.Collections; - -using System.Linq; - -namespace Xtensive.Orm.Operations -{ - /// - /// Describes operation over key set. - /// - [Serializable] - public abstract class KeySetOperation : Operation, - ISerializable - { - /// - public override string Description { - get - { - return $"{Title}:{Environment.NewLine}{Keys.ToDelimitedString(Environment.NewLine).Indent(2)}"; - } - } - - /// - /// Gets the key set. - /// - public IReadOnlySet Keys { get; private set; } - - /// - protected override void PrepareSelf(OperationExecutionContext context) - { - foreach (var key in Keys) - context.RegisterKey(context.TryRemapKey(key), false); - } - - - // Constructors - - /// - public KeySetOperation(Key key) - : this(Enumerable.Repeat(key, 1)) - { - } - - /// - /// Initializes a new instance of this class. - /// - /// The sequence of keys. - public KeySetOperation(IEnumerable keys) - { - Keys = new ReadOnlyHashSet(new HashSet(keys)); - } - - // Serialization - - /// - protected KeySetOperation(SerializationInfo info, StreamingContext context) - { - var formattedKeys = info.GetString("Keys"); - var keys = new HashSet(); - foreach (var formattedKey in formattedKeys.RevertibleSplit('\\', ';')) { - var key = Key.Parse(Domain.Demand(), formattedKey); -// key.TypeReference = new TypeReference(key.TypeReference.Type, TypeReferenceAccuracy.ExactType); - keys.Add(key); - } - Keys = new ReadOnlyHashSet(keys); - } - - [SecurityCritical] - void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) - { - GetObjectData(info, context); - } - - /// - /// Populates a with the data needed to serialize the target object. - /// - /// The to populate with data. - /// The destination (see ) for this serialization. - /// The caller does not have the required permission. - protected virtual void GetObjectData(SerializationInfo info, StreamingContext context) - { - var formattedKeys = Keys.Select(key => key.Format()).RevertibleJoin('\\', ';'); - info.AddValue("Keys", formattedKeys); - } - } - -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Operations/OperationCompletedEventArgs.cs b/Orm/Xtensive.Orm/Orm/Operations/OperationCompletedEventArgs.cs index 1934192ef8..6904afafd1 100644 --- a/Orm/Xtensive.Orm/Orm/Operations/OperationCompletedEventArgs.cs +++ b/Orm/Xtensive.Orm/Orm/Operations/OperationCompletedEventArgs.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Operations /// /// Arguments for completion events. /// - [Serializable] public sealed class OperationCompletedEventArgs : OperationEventArgs { /// @@ -21,7 +20,7 @@ public sealed class OperationCompletedEventArgs : OperationEventArgs /// , if operation was completed successfully; /// otherwise, . /// - public bool IsCompleted { get; private set; } + public bool IsCompleted { get; } // Constructors @@ -29,7 +28,7 @@ public sealed class OperationCompletedEventArgs : OperationEventArgs /// /// Initializes a new instance of this class. /// - /// The property value. + /// The property value. /// property value. public OperationCompletedEventArgs(IOperation operation, bool isCompleted) : base(operation) diff --git a/Orm/Xtensive.Orm/Orm/Operations/OperationEventArgs.cs b/Orm/Xtensive.Orm/Orm/Operations/OperationEventArgs.cs index 016586ea66..b2d201a169 100644 --- a/Orm/Xtensive.Orm/Orm/Operations/OperationEventArgs.cs +++ b/Orm/Xtensive.Orm/Orm/Operations/OperationEventArgs.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Operations /// /// Arguments for -related events. /// - [Serializable] public class OperationEventArgs : EventArgs { /// diff --git a/Orm/Xtensive.Orm/Orm/Operations/OperationType.cs b/Orm/Xtensive.Orm/Orm/Operations/OperationType.cs index c1d10ea3a8..c94cf51e78 100644 --- a/Orm/Xtensive.Orm/Orm/Operations/OperationType.cs +++ b/Orm/Xtensive.Orm/Orm/Operations/OperationType.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Operations /// /// Defines possible operation types. /// - [Serializable] public enum OperationType { /// diff --git a/Orm/Xtensive.Orm/Orm/Operations/SystemOperationRegistrationScope.cs b/Orm/Xtensive.Orm/Orm/Operations/SystemOperationRegistrationScope.cs new file mode 100644 index 0000000000..e82d6ecdd8 --- /dev/null +++ b/Orm/Xtensive.Orm/Orm/Operations/SystemOperationRegistrationScope.cs @@ -0,0 +1,32 @@ +// Copyright (C) 2010-2020 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. +// Created by: Alex Yakunin +// Created: 2010.08.04 + +using System; + +namespace Xtensive.Orm.Operations +{ + public readonly struct SystemOperationRegistrationScope : IDisposable + { + private readonly IOperationRegistry registry; + private readonly Action onDispose; + private readonly bool prevState; + + public SystemOperationRegistrationScope(IOperationRegistry registry, bool newState, + Action stateChanger) + { + this.registry = registry; + prevState = registry.IsSystemOperationRegistrationEnabled; + stateChanger(registry, newState); + this.onDispose = stateChanger; + } + + public void Dispose() + { + if (onDispose is not null) + onDispose(registry, prevState); + } + } +} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Operations/VoidOperationRegistry.cs b/Orm/Xtensive.Orm/Orm/Operations/VoidOperationRegistry.cs new file mode 100644 index 0000000000..4ffbf0cafe --- /dev/null +++ b/Orm/Xtensive.Orm/Orm/Operations/VoidOperationRegistry.cs @@ -0,0 +1,68 @@ +// Copyright (C) 2026 Xtensive LLC. +// This code is distributed under MIT license terms. +// See the License.txt file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Xtensive.Orm.Operations +{ + /// + /// An implementor that does nothing + /// so wastes no time, basically a null object. + /// + internal sealed class VoidOperationRegistry(Session session) : IOperationRegistry + { + /// + public Session Session { get; private set; } = session; + + /// + public bool IsRegistrationEnabled => false; + + /// + public bool CanRegisterOperation => false; + + /// + public bool IsRegisteringOperation => false; + + /// + public bool IsSystemOperationRegistrationEnabled => false; + + /// + public ICompletableScope BeginRegistration(OperationType operationType) => null; + + /// + public IDisposable DisableUndoOperationRegistration() => throw new NotSupportedException(); + + /// + public SystemOperationRegistrationScope DisableSystemOperationRegistration() => default; + /// + public SystemOperationRegistrationScope EnableSystemOperationRegistration() => default; + + public void NotifyOperationStarting() => throw new NotSupportedException(); + /// + public void NotifyOperationStarting(bool throwIfNotRegistered) => throw new NotSupportedException(); + /// + public void RegisterEntityIdentifier(Key key, string identifier) => throw new NotSupportedException(); + /// + public void RegisterOperation(IOperation operation) => throw new NotSupportedException(); + /// + public void RegisterOperation(IOperation operation, bool isStarted) => throw new NotSupportedException(); + /// + public void RegisterUndoOperation(IOperation operation) => throw new NotSupportedException(); + +#pragma warning disable CS0067 + /// + public event EventHandler OutermostOperationStarting; + /// + public event EventHandler OutermostOperationCompleted; + /// + public event EventHandler NestedOperationStarting; + /// + public event EventHandler NestedOperationCompleted; + /// + public event EventHandler UndoOperation; +#pragma warning restore CS0067 + } +} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Persistent.cs b/Orm/Xtensive.Orm/Orm/Persistent.cs index 3e48bca07f..acf153e932 100644 --- a/Orm/Xtensive.Orm/Orm/Persistent.cs +++ b/Orm/Xtensive.Orm/Orm/Persistent.cs @@ -12,8 +12,8 @@ using Xtensive.Core; using Xtensive.Orm.Internals; using Xtensive.Orm.Model; -using Xtensive.Orm.Operations; using Xtensive.Orm.PairIntegrity; +using Xtensive.Orm.Providers; using Xtensive.Orm.ReferentialIntegrity; using Xtensive.Orm.Validation; using Xtensive.Tuples; @@ -127,7 +127,7 @@ public void SetProperty(string fieldName, T value) var dt = p.DeclaringType; mi = dt.GetProperty(p.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).GetSetMethod(true); } - mi.Invoke(this, new object[] { value }); + _ = mi.Invoke(this, new object[] { value }); } else SetFieldValue(pair.First, (object) value); // Untyped, since T might be wrong @@ -145,7 +145,7 @@ public void SetProperty(string fieldName, T value) /// /// Gets the field value. /// Field value type must be specified precisely. - /// E.g. usage of instead of might lead to unpredictable effects. + /// E.g. usage of instead of might lead to unpredictable effects. /// /// Field value type. /// The field name. @@ -168,7 +168,7 @@ protected internal object GetFieldValue(string fieldName) /// /// Gets the field value. /// Field value type must be specified precisely. - /// E.g. usage of instead of might lead to unpredictable effects. + /// E.g. usage of instead of might lead to unpredictable effects. /// /// Field value type. /// The field. @@ -239,7 +239,7 @@ protected internal Key GetReferenceKey(FieldInfo field) SystemBeforeGetValue(field); if (!field.IsEntity) throw new InvalidOperationException( - String.Format(Strings.ExFieldIsNotAnEntityField, field.Name, field.ReflectedType.Name)); + string.Format(Strings.ExFieldIsNotAnEntityField, field.Name, field.ReflectedType.Name)); var types = Session.Domain.Model.Types; var type = types[field.ValueType]; @@ -336,7 +336,7 @@ protected internal void SetReferenceKey(FieldInfo field, Key value) /// /// Sets the field value. /// Field value type must be specified precisely. - /// E.g. usage of instead of might lead to unpredictable effects. + /// E.g. usage of instead of might lead to unpredictable effects. /// /// Field value type. /// The field name. @@ -359,7 +359,7 @@ protected internal void SetFieldValue(string fieldName, object value) /// /// Sets the field value. /// Field value type must be specified precisely. - /// E.g. usage of instead of might lead to unpredictable effects. + /// E.g. usage of instead of might lead to unpredictable effects. /// /// Field value type. /// The field. @@ -374,7 +374,7 @@ protected internal void SetFieldValue(FieldInfo field, T value) /// /// Sets the field value. /// Field value type must be specified precisely. - /// E.g. usage of instead of might lead to unpredictable effects. + /// E.g. usage of instead of might lead to unpredictable effects. /// /// The field. /// The value to set. @@ -398,13 +398,13 @@ internal void SetFieldValue(FieldInfo field, object value, SyncContext syncConte } try { - var operations = Session.Operations; + var (operations, operationsFactory, allowRegistration) = Session.GetOperationsContext(); var scope = operations.BeginRegistration(Operations.OperationType.System); try { var entity = this as Entity; if (entity != null) { - if (operations.CanRegisterOperation) - operations.RegisterOperation(new EntityFieldSetOperation(entity.Key, field, value)); + if (allowRegistration && operations.CanRegisterOperation) + operations.RegisterOperation(operationsFactory.EntityFieldSetOperation(entity.Key, field, value)); var entityValue = value as IEntity; if (entityValue != null) { var valueKey = entityValue.Key; @@ -423,8 +423,8 @@ internal void SetFieldValue(FieldInfo field, object value, SyncContext syncConte } entity = persistent as Entity; if (entity != null) { - if (operations.CanRegisterOperation) - operations.RegisterOperation(new EntityFieldSetOperation(entity.Key, currentField, value)); + if (allowRegistration && operations.CanRegisterOperation) + operations.RegisterOperation(operationsFactory.EntityFieldSetOperation(entity.Key, currentField, value)); var entityValue = value as IEntity; if (entityValue != null) { var valueKey = entityValue.Key; @@ -434,13 +434,15 @@ internal void SetFieldValue(FieldInfo field, object value, SyncContext syncConte } if (fieldAccessor.AreSameValues(oldValue, value)) { - operations.NotifyOperationStarting(false); - scope.Complete(); + if (allowRegistration && operations.CanRegisterOperation) + operations.NotifyOperationStarting(false); + scope?.Complete(); return; } { SystemBeforeSetValue(field, value); - operations.NotifyOperationStarting(false); + if (allowRegistration && operations.CanRegisterOperation) + operations.NotifyOperationStarting(false); AssociationInfo association = null; entity = value as Entity ?? oldValue as Entity; if (entity != null) @@ -485,7 +487,7 @@ internal void SetFieldValue(FieldInfo field, object value, SyncContext syncConte try { SystemSetValue(field, oldValue, value); SystemSetValueCompleted(field, oldValue, value, null); - scope.Complete(); + scope?.Complete(); } finally { scope.DisposeSafely(); @@ -502,7 +504,7 @@ internal void SetFieldValue(FieldInfo field, object value, SyncContext syncConte SystemSetValue(field, oldValue, value); SystemSetValueCompleted(field, oldValue, value, null); } - scope.Complete(); + scope?.Complete(); } finally { if (removalContext == null) diff --git a/Orm/Xtensive.Orm/Orm/Providers/ProviderInfo.cs b/Orm/Xtensive.Orm/Orm/Providers/ProviderInfo.cs index d9169a3560..7c987f1293 100644 --- a/Orm/Xtensive.Orm/Orm/Providers/ProviderInfo.cs +++ b/Orm/Xtensive.Orm/Orm/Providers/ProviderInfo.cs @@ -14,55 +14,54 @@ namespace Xtensive.Orm.Providers /// /// Provider's features provider. /// - [Serializable] public sealed class ProviderInfo { /// /// Gets provider name. /// - public string ProviderName { get; private set; } + public string ProviderName { get; } /// /// Version of the underlying storage. /// - public Version StorageVersion { get; private set; } + public Version StorageVersion { get; } /// /// Gets the features. /// - public ProviderFeatures ProviderFeatures { get; private set; } + public ProviderFeatures ProviderFeatures { get; } /// /// Gets maximal identifier length. /// - public int MaxIdentifierLength { get; private set; } + public int MaxIdentifierLength { get; } /// /// Gets the constant name of the primary index. /// /// The constant name of the primary index. - public string ConstantPrimaryIndexName { get; private set; } + public string ConstantPrimaryIndexName { get; } /// /// Gets default database for current user. /// - public string DefaultDatabase { get; private set; } + public string DefaultDatabase { get; } /// /// Gets default schema for current user. /// - public string DefaultSchema { get; private set; } + public string DefaultSchema { get; } /// /// Gets the supported types. /// - public IReadOnlySet SupportedTypes { get; private set; } + public IReadOnlySet SupportedTypes { get; } /// /// Gets max query parameter count. /// - public int MaxQueryParameterCount { get; private set; } + public int MaxQueryParameterCount { get; } /// /// Determines whether the specified features are supported. diff --git a/Orm/Xtensive.Orm/Orm/Providers/SessionExtensions.cs b/Orm/Xtensive.Orm/Orm/Providers/SessionExtensions.cs index 7731e797e7..72531a7bfe 100644 --- a/Orm/Xtensive.Orm/Orm/Providers/SessionExtensions.cs +++ b/Orm/Xtensive.Orm/Orm/Providers/SessionExtensions.cs @@ -4,6 +4,9 @@ // Created by: Alex Yakunin // Created: 2009.10.14 +using System; +using Xtensive.Orm.Operations; + namespace Xtensive.Orm.Providers { /// @@ -22,5 +25,19 @@ public static string ToStringSafely(this Session session) { return session==null ? Strings.NA : session.ToString(); } + + internal static (IOperationRegistry operations, IOperationFactory operationsFactory, bool allowedRegistration) GetOperationsContext(this Session session) + { + var operations = session.Operations; + var allowRegistration = operations.IsRegistrationEnabled; + IOperationFactory operationsFactory = null; + if (allowRegistration) { + operationsFactory = session.Domain.Services.Get(); + if (operationsFactory is null) + throw new InvalidOperationException("Factory of operations can't be found."); + } + + return(operations, operationsFactory, allowRegistration); + } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Providers/StorageExceptionBuilder.cs b/Orm/Xtensive.Orm/Orm/Providers/StorageExceptionBuilder.cs index ebb178a634..2e4cc338fb 100644 --- a/Orm/Xtensive.Orm/Orm/Providers/StorageExceptionBuilder.cs +++ b/Orm/Xtensive.Orm/Orm/Providers/StorageExceptionBuilder.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2012 Xtensive LLC. +// Copyright (C) 2012 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Denis Krjuchkov @@ -7,6 +7,7 @@ using System; using System.Linq; using System.Text; +using Xtensive.Core; using Xtensive.Orm.Configuration; using Xtensive.Orm.Model; using Xtensive.Sql; @@ -33,27 +34,26 @@ public StorageException BuildException(Exception origin, string queryText) if (storageExceptionInfo!=null) { var storageErrorDetails = storageExceptionInfo.ToString(); if (!string.IsNullOrEmpty(storageErrorDetails)) { - builder.AppendLine(); - builder.AppendFormat(Strings.StorageErrorDetailsX, storageErrorDetails); + _ = builder.AppendLine() + .AppendFormat(Strings.StorageErrorDetailsX, storageErrorDetails); } } var sqlErrorDetails = sqlExceptionInfo.ToString(); if (!string.IsNullOrEmpty(sqlErrorDetails)) { - builder.AppendLine(); - builder.AppendFormat(Strings.SqlErrorDetailsX, sqlErrorDetails); + _ = builder.AppendLine() + .AppendFormat(Strings.SqlErrorDetailsX, sqlErrorDetails); } if (!string.IsNullOrEmpty(queryText) && includeSqlInExceptions) { - builder.AppendLine(); - builder.AppendFormat(Strings.QueryX, queryText); + _ = builder.AppendLine() + .AppendFormat(Strings.QueryX, queryText); } var sqlMessage = origin.Message; if (!string.IsNullOrEmpty(sqlMessage)) { - builder.AppendLine(); - builder.AppendFormat(Strings.OriginalMessageX, sqlMessage); + _ = builder.AppendLine() + .AppendFormat(Strings.OriginalMessageX, sqlMessage); } - var storageException = CreateStorageException(sqlExceptionInfo.Type, builder.ToString(), origin); - storageException.Info = storageExceptionInfo; + var storageException = CreateStorageException(sqlExceptionInfo.Type, builder.ToString(), origin, storageExceptionInfo); return storageException; } @@ -73,27 +73,27 @@ private StorageExceptionInfo GetStorageExceptionInfo(SqlExceptionInfo info) } private static StorageException CreateStorageException(SqlExceptionType type, string message, - Exception innerException) + Exception innerException, StorageExceptionInfo storageExceptionInfo) { switch (type) { case SqlExceptionType.ConnectionError: - return new ConnectionErrorException(message, innerException); + return new ConnectionErrorException(message, innerException) { Info = storageExceptionInfo}; case SqlExceptionType.SyntaxError: - return new SyntaxErrorException(message, innerException); + return new SyntaxErrorException(message, innerException) { Info = storageExceptionInfo }; case SqlExceptionType.CheckConstraintViolation: - return new CheckConstraintViolationException(message, innerException); + return new CheckConstraintViolationException(message, innerException) { Info = storageExceptionInfo }; case SqlExceptionType.UniqueConstraintViolation: - return new UniqueConstraintViolationException(message, innerException); + return new UniqueConstraintViolationException(message, innerException) { Info = storageExceptionInfo }; case SqlExceptionType.ReferentialConstraintViolation: - return new ReferentialConstraintViolationException(message, innerException); + return new ReferentialConstraintViolationException(message, innerException) { Info = storageExceptionInfo }; case SqlExceptionType.Deadlock: - return new DeadlockException(message, innerException); + return new DeadlockException(message, innerException) { Info = storageExceptionInfo }; case SqlExceptionType.SerializationFailure: - return new TransactionSerializationFailureException(message, innerException); + return new TransactionSerializationFailureException(message, innerException) { Info = storageExceptionInfo }; case SqlExceptionType.OperationTimeout: - return new OperationTimeoutException(message, innerException); + return new OperationTimeoutException(message, innerException) { Info = storageExceptionInfo }; default: - return new StorageException(message, innerException); + return new StorageException(message, innerException) { Info = storageExceptionInfo }; } } diff --git a/Orm/Xtensive.Orm/Orm/Ref.cs b/Orm/Xtensive.Orm/Orm/Ref.cs index eb468d5cad..0ce8bc6e03 100644 --- a/Orm/Xtensive.Orm/Orm/Ref.cs +++ b/Orm/Xtensive.Orm/Orm/Ref.cs @@ -6,9 +6,6 @@ using System; using System.Diagnostics; -using System.Runtime.Serialization; -using System.Security; - using Xtensive.Reflection; @@ -18,12 +15,10 @@ namespace Xtensive.Orm /// Typed reference to . /// /// The type of referenced object ( property). - [Serializable] [DebuggerDisplay("Key = {Key}")] public struct Ref : IEquatable>, - IEquatable, - ISerializable + IEquatable where T : class, IEntity { private object keyOrString; @@ -33,7 +28,7 @@ public struct Ref : /// public Key Key { get { - if (keyOrString==null) + if (keyOrString is null) return null; var key = keyOrString as Key; if (key==null) { @@ -50,7 +45,7 @@ public Key Key { /// public string FormattedKey { get { - if (keyOrString==null) + if (keyOrString is null) return null; var key = keyOrString as Key; return key!=null ? key.Format() : (string) keyOrString; @@ -82,7 +77,7 @@ public override bool Equals(object other) => }; /// - public override int GetHashCode() => Key!=null ? Key.GetHashCode() : 0; + public override int GetHashCode() => Key is not null ? Key.GetHashCode() : 0; #endregion @@ -166,31 +161,7 @@ public Ref(string formattedKey) /// The entity this reference points to. public Ref(T entity) { - if (entity==null) - keyOrString = null; - else - keyOrString = entity.Key; - } - - #region ISerializable members - - private Ref(SerializationInfo info, StreamingContext context) - { - keyOrString = info.GetString("FormattedKey"); - } - - /// - /// Populates a with the data needed to serialize the target object. - /// - /// The to populate with data. - /// The destination (see ) for this serialization. - /// The caller does not have the required permission. - [SecurityCritical] - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue("FormattedKey", FormattedKey); + keyOrString = entity is null ? null : (object) entity.Key; } - - #endregion } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/ReferenceInfo.cs b/Orm/Xtensive.Orm/Orm/ReferenceInfo.cs index 254f89a75f..e8e2b6c84f 100644 --- a/Orm/Xtensive.Orm/Orm/ReferenceInfo.cs +++ b/Orm/Xtensive.Orm/Orm/ReferenceInfo.cs @@ -13,23 +13,22 @@ namespace Xtensive.Orm /// /// Describes referential relationship between two particular entities. /// - [Serializable] - public struct ReferenceInfo + public readonly struct ReferenceInfo { /// /// Gets the referencing entity. /// - public Entity ReferencingEntity { get; private set; } + public readonly Entity ReferencingEntity; /// /// Gets the referenced entity. /// - public Entity ReferencedEntity { get; private set; } + public readonly Entity ReferencedEntity; /// /// Gets the object describing the relationship. /// - public AssociationInfo Association { get; private set; } + public readonly AssociationInfo Association; // Constructors @@ -41,7 +40,6 @@ public struct ReferenceInfo /// The referenced entity. /// The association. public ReferenceInfo(Entity referencingEntity, Entity referencedEntity, AssociationInfo association) - : this() { ReferencingEntity = referencingEntity; ReferencedEntity = referencedEntity; diff --git a/Orm/Xtensive.Orm/Orm/Rse/AggregateColumn.cs b/Orm/Xtensive.Orm/Orm/Rse/AggregateColumn.cs index f1a6226247..ca2939c9f5 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/AggregateColumn.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/AggregateColumn.cs @@ -11,11 +11,8 @@ namespace Xtensive.Orm.Rse /// /// Aggregate column of the . /// - [Serializable] public sealed class AggregateColumn : Column { - private const string ToStringFormat = "{0} = {1} on ({2})"; - /// /// Gets the aggregate function. /// @@ -33,22 +30,14 @@ public sealed class AggregateColumn : Column /// public override string ToString() - { - return string.Format(ToStringFormat, - base.ToString(), AggregateType, SourceIndex); - } + => $"{base.ToString()} = {AggregateType} on ({SourceIndex})"; + /// - public override AggregateColumn Clone(int newIndex) - { - return new AggregateColumn(this, newIndex); - } + public override AggregateColumn Clone(int newIndex) => new AggregateColumn(this, newIndex); /// - public override AggregateColumn Clone(string newName) - { - return new AggregateColumn(this, newName); - } + public override AggregateColumn Clone(string newName) => new AggregateColumn(this, newName); // Constructors diff --git a/Orm/Xtensive.Orm/Orm/Rse/AggregateColumnDescriptor.cs b/Orm/Xtensive.Orm/Orm/Rse/AggregateColumnDescriptor.cs index 14ae967235..48ddfb22bb 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/AggregateColumnDescriptor.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/AggregateColumnDescriptor.cs @@ -13,11 +13,8 @@ namespace Xtensive.Orm.Rse /// /// Descriptor of the calculated column. /// - [Serializable] public class AggregateColumnDescriptor { - private const string ToStringFormat = "{0} = {1} on ({2})"; - /// /// Gets the column index. /// @@ -40,10 +37,7 @@ public class AggregateColumnDescriptor /// public override string ToString() - { - return string.Format(ToStringFormat, - base.ToString(), AggregateType, SourceIndex); - } + => $"{base.ToString()} = {AggregateType} on ({SourceIndex})"; // Constructors diff --git a/Orm/Xtensive.Orm/Orm/Rse/ApplyParameter.cs b/Orm/Xtensive.Orm/Orm/Rse/ApplyParameter.cs index bbcffc9655..c151cf2c47 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/ApplyParameter.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/ApplyParameter.cs @@ -6,8 +6,6 @@ using System; using System.Diagnostics; -using System.Runtime.Serialization; -using System.Xml.Serialization; using Xtensive.Core; using Xtensive.Orm.Rse.Providers; using Tuple = Xtensive.Tuples.Tuple; @@ -18,13 +16,10 @@ namespace Xtensive.Orm.Rse /// A parameter for accessing current tuple of left (outer) /// within right (inner) . /// - [Serializable] [DebuggerDisplay("{Name}")] - public sealed class ApplyParameter : ISerializable + public sealed class ApplyParameter { - [NonSerialized] - private Parameter parameter; - + private readonly Parameter parameter; /// /// Gets the name of this parameter. @@ -41,11 +36,6 @@ public Tuple Value { get { return parameter.Value; } } - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue("Name", Name); - } - /// public override string ToString() { @@ -72,19 +62,5 @@ public ApplyParameter() : this(string.Empty) { } - - public ApplyParameter(SerializationInfo info, StreamingContext context) - { - Name = info.GetString("Name"); - parameter = new Parameter(Name); - } - - // Deserialization - - //[OnDeserialized] - //private void OnDeserialized(StreamingContext context) - //{ - // parameter = new Parameter(Name); - //} } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Rse/CalculatedColumn.cs b/Orm/Xtensive.Orm/Orm/Rse/CalculatedColumn.cs index 08d19d322f..6543b2bb41 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/CalculatedColumn.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/CalculatedColumn.cs @@ -17,11 +17,8 @@ namespace Xtensive.Orm.Rse /// /// Calculated column of the . /// - [Serializable] public sealed class CalculatedColumn : Column { - private const string ToStringFormat = "{0} = {1}"; - /// /// Gets the column expression. /// @@ -29,22 +26,13 @@ public sealed class CalculatedColumn : Column /// public override string ToString() - { - return string.Format(ToStringFormat, - base.ToString(), Expression.ToString(true)); - } + => $"{base.ToString()} = {Expression.ToString(true)}"; /// - public override CalculatedColumn Clone(int newIndex) - { - return new CalculatedColumn(this, newIndex); - } + public override CalculatedColumn Clone(int newIndex) => new CalculatedColumn(this, newIndex); /// - public override CalculatedColumn Clone(string newName) - { - return new CalculatedColumn(this, newName); - } + public override CalculatedColumn Clone(string newName) => new CalculatedColumn(this, newName); // Constructors diff --git a/Orm/Xtensive.Orm/Orm/Rse/CalculatedColumnDescriptor.cs b/Orm/Xtensive.Orm/Orm/Rse/CalculatedColumnDescriptor.cs index 22f2a63c65..4271151aa9 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/CalculatedColumnDescriptor.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/CalculatedColumnDescriptor.cs @@ -18,11 +18,8 @@ namespace Xtensive.Orm.Rse /// /// Descriptor of the calculated column. /// - [Serializable] public class CalculatedColumnDescriptor { - private const string ToStringFormat = "{0} {1} = {2}"; - /// /// Gets the column name. /// @@ -40,10 +37,7 @@ public class CalculatedColumnDescriptor /// public override string ToString() - { - return string.Format(ToStringFormat, - Type.GetShortName(), Name, Expression.ToString(true)); - } + => $"{Type.GetShortName()} {Name} = {Expression.ToString(true)}"; // Constructors diff --git a/Orm/Xtensive.Orm/Orm/Rse/Column.cs b/Orm/Xtensive.Orm/Orm/Rse/Column.cs index fad40cca10..b2779e15a5 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Column.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Column.cs @@ -12,11 +12,8 @@ namespace Xtensive.Orm.Rse /// /// Base class for any column of the . /// - [Serializable] public abstract class Column : IEquatable { - private const string ToStringFormat = "{0} {1} ({2})"; - /// /// Gets origin for this instance. /// @@ -91,9 +88,7 @@ public override int GetHashCode() /// public override string ToString() - { - return string.Format(ToStringFormat, Type.Name, Name, Index); - } + => $"{Type.Name} {Name} ({Index})"; /// /// Creates clone of the column, but with another . diff --git a/Orm/Xtensive.Orm/Orm/Rse/ColumnCollection.cs b/Orm/Xtensive.Orm/Orm/Rse/ColumnCollection.cs index 5343abf07d..e229eb8919 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/ColumnCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/ColumnCollection.cs @@ -16,7 +16,6 @@ namespace Xtensive.Orm.Rse /// /// Collection of items. /// - [Serializable] public sealed class ColumnCollection : IReadOnlyList { public struct Enumerator : IEnumerator, IEnumerator diff --git a/Orm/Xtensive.Orm/Orm/Rse/ColumnGroupCollection.cs b/Orm/Xtensive.Orm/Orm/Rse/ColumnGroupCollection.cs index 6bd6d03bd7..6ae62879c6 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/ColumnGroupCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/ColumnGroupCollection.cs @@ -17,11 +17,10 @@ namespace Xtensive.Orm.Rse /// /// Read only collection of the instances. /// - [Serializable] public class ColumnGroupCollection : IReadOnlyList { private static readonly Lazy CachedEmpty = - new Lazy(() => new ColumnGroupCollection(Array.Empty())); + new(() => new ColumnGroupCollection(Array.Empty())); private readonly IReadOnlyList items; @@ -36,11 +35,10 @@ public class ColumnGroupCollection : IReadOnlyList /// /// Gets the empty . /// - public static ColumnGroupCollection Empty { + public static ColumnGroupCollection Empty + { [DebuggerStepThrough] - get { - return CachedEmpty.Value; - } + get => CachedEmpty.Value; } /// diff --git a/Orm/Xtensive.Orm/Orm/Rse/MappedColumn.cs b/Orm/Xtensive.Orm/Orm/Rse/MappedColumn.cs index 7cd71fb2ef..2d83ba449d 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/MappedColumn.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/MappedColumn.cs @@ -12,11 +12,8 @@ namespace Xtensive.Orm.Rse /// /// Mapped column of the . /// - [Serializable] public sealed class MappedColumn : Column { - private const string ToStringFormat = "{0} = {1}"; - private readonly ColumnInfoRef columnInfo; /// /// Gets the reference that describes a column. @@ -24,22 +21,13 @@ public sealed class MappedColumn : Column public ref readonly ColumnInfoRef ColumnInfoRef => ref columnInfo; /// - public override string ToString() - { - return string.Format(ToStringFormat, base.ToString(), ColumnInfoRef); - } + public override string ToString() => $"{base.ToString()} = {ColumnInfoRef}"; /// - public override MappedColumn Clone(int newIndex) - { - return new MappedColumn(ColumnInfoRef, Name, newIndex, Type); - } + public override MappedColumn Clone(int newIndex) => new MappedColumn(ColumnInfoRef, Name, newIndex, Type); /// - public override MappedColumn Clone(string newName) - { - return new MappedColumn(this, newName); - } + public override MappedColumn Clone(string newName) => new MappedColumn(this, newName); // Constructors diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/AggregateProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/AggregateProvider.cs index cc69851625..b9291583de 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/AggregateProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/AggregateProvider.cs @@ -15,13 +15,8 @@ namespace Xtensive.Orm.Rse.Providers /// /// Compilable provider that applies aggregate functions to grouped columns from . /// - [Serializable] public sealed class AggregateProvider : UnaryProvider { - private const string ToStringFormatGroupOnly = "Group by ({0})"; - private const string ToStringFormatAggregateOnly = "{0}"; - private const string ToStringFormatFull = "{0}, Group by ({1})"; - /// /// Gets the aggregate columns. /// @@ -35,20 +30,13 @@ public sealed class AggregateProvider : UnaryProvider /// protected override string ParametersToString() { - if (AggregateColumns.Length==0) - return string.Format( - ToStringFormatGroupOnly, - GroupColumnIndexes.ToCommaDelimitedString()); - - if (GroupColumnIndexes.Length==0) - return string.Format( - ToStringFormatAggregateOnly, - AggregateColumns.ToCommaDelimitedString()); - - return string.Format( - ToStringFormatFull, - AggregateColumns.ToCommaDelimitedString(), - GroupColumnIndexes.ToCommaDelimitedString()); + if (AggregateColumns.Length == 0) + return $"Group by ({GroupColumnIndexes.ToCommaDelimitedString()})"; + + if (GroupColumnIndexes.Length == 0) + return AggregateColumns.ToCommaDelimitedString(); + + return $"{AggregateColumns.ToCommaDelimitedString()}, Group by ({GroupColumnIndexes.ToCommaDelimitedString()})"; } /// @@ -62,19 +50,13 @@ public static Type GetAggregateColumnType(Type sourceColumnType, AggregateType a // TODO: very stupid - remove when nullables handing fixed everywhere. if (sourceColumnType.IsNullable()) sourceColumnType = sourceColumnType.GetGenericArguments()[0]; - switch (aggregateType) { - case AggregateType.Count: - return WellKnownTypes.Int64; - case AggregateType.Min: - case AggregateType.Max: - return GetMinMaxColumnType(sourceColumnType, aggregateType); - case AggregateType.Sum: - return GetSumColumnType(sourceColumnType); - case AggregateType.Avg: - return GetAvgColumnType(sourceColumnType); - default: - throw AggregateNotSupported(sourceColumnType, aggregateType); - } + return aggregateType switch { + AggregateType.Count => WellKnownTypes.Int64, + AggregateType.Min or AggregateType.Max => GetMinMaxColumnType(sourceColumnType, aggregateType), + AggregateType.Sum => GetSumColumnType(sourceColumnType), + AggregateType.Avg => GetAvgColumnType(sourceColumnType), + _ => throw AggregateNotSupported(sourceColumnType, aggregateType), + }; } #region Private / internal methods @@ -82,68 +64,68 @@ public static Type GetAggregateColumnType(Type sourceColumnType, AggregateType a private static Type GetMinMaxColumnType(Type sourceColumnType, AggregateType aggregateType) { switch (System.Type.GetTypeCode(sourceColumnType)) { - case TypeCode.Char: - case TypeCode.SByte: - case TypeCode.Byte: - case TypeCode.Int16: - case TypeCode.Int32: - case TypeCode.Int64: - case TypeCode.UInt16: - case TypeCode.UInt32: - case TypeCode.UInt64: - case TypeCode.Decimal: - case TypeCode.Single: - case TypeCode.Double: - case TypeCode.String: - case TypeCode.DateTime: - return sourceColumnType; - default: - if (sourceColumnType==WellKnownTypes.TimeSpan || sourceColumnType==WellKnownTypes.DateTimeOffset) + case TypeCode.Char: + case TypeCode.SByte: + case TypeCode.Byte: + case TypeCode.Int16: + case TypeCode.Int32: + case TypeCode.Int64: + case TypeCode.UInt16: + case TypeCode.UInt32: + case TypeCode.UInt64: + case TypeCode.Decimal: + case TypeCode.Single: + case TypeCode.Double: + case TypeCode.String: + case TypeCode.DateTime: return sourceColumnType; - if (sourceColumnType == WellKnownTypes.DateOnly || sourceColumnType == WellKnownTypes.TimeOnly) - return sourceColumnType; - throw AggregateNotSupported(sourceColumnType, aggregateType); + default: + if (sourceColumnType == WellKnownTypes.TimeSpan || sourceColumnType == WellKnownTypes.DateTimeOffset) + return sourceColumnType; + if (sourceColumnType == WellKnownTypes.DateOnly || sourceColumnType == WellKnownTypes.TimeOnly) + return sourceColumnType; + throw AggregateNotSupported(sourceColumnType, aggregateType); } } private static Type GetSumColumnType(Type sourceColumnType) { switch (System.Type.GetTypeCode(sourceColumnType)) { - case TypeCode.SByte: - case TypeCode.Byte: - case TypeCode.Int16: - case TypeCode.Int32: - case TypeCode.Int64: - case TypeCode.UInt16: - case TypeCode.UInt32: - case TypeCode.UInt64: - case TypeCode.Decimal: - case TypeCode.Single: - case TypeCode.Double: - return sourceColumnType; - default: - throw AggregateNotSupported(sourceColumnType, AggregateType.Sum); + case TypeCode.SByte: + case TypeCode.Byte: + case TypeCode.Int16: + case TypeCode.Int32: + case TypeCode.Int64: + case TypeCode.UInt16: + case TypeCode.UInt32: + case TypeCode.UInt64: + case TypeCode.Decimal: + case TypeCode.Single: + case TypeCode.Double: + return sourceColumnType; + default: + throw AggregateNotSupported(sourceColumnType, AggregateType.Sum); } } private static Type GetAvgColumnType(Type sourceColumnType) { switch (System.Type.GetTypeCode(sourceColumnType)) { - case TypeCode.SByte: - case TypeCode.Byte: - case TypeCode.Int16: - case TypeCode.Int32: - case TypeCode.Int64: - case TypeCode.UInt16: - case TypeCode.UInt32: - case TypeCode.UInt64: - return WellKnownTypes.Double; - case TypeCode.Decimal: - case TypeCode.Single: - case TypeCode.Double: - return sourceColumnType; - default: - throw AggregateNotSupported(sourceColumnType, AggregateType.Avg); + case TypeCode.SByte: + case TypeCode.Byte: + case TypeCode.Int16: + case TypeCode.Int32: + case TypeCode.Int64: + case TypeCode.UInt16: + case TypeCode.UInt32: + case TypeCode.UInt64: + return WellKnownTypes.Double; + case TypeCode.Decimal: + case TypeCode.Single: + case TypeCode.Double: + return sourceColumnType; + default: + throw AggregateNotSupported(sourceColumnType, AggregateType.Avg); } } diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/AliasProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/AliasProvider.cs index 93519aee97..08c83243fa 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/AliasProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/AliasProvider.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Rse.Providers /// /// Aliases the with specified . /// - [Serializable] public sealed class AliasProvider : UnaryProvider { /// @@ -23,10 +22,7 @@ public sealed class AliasProvider : UnaryProvider public string Alias { get; } /// - protected override string ParametersToString() - { - return Alias; - } + protected override string ParametersToString() => Alias; // Constructors diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/ApplyProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/ApplyProvider.cs index 1e0c675bbe..d50ccaef4d 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/ApplyProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/ApplyProvider.cs @@ -5,11 +5,6 @@ // Created: 2009.02.16 using System; -using System.Collections.Generic; -using System.Linq; -using Xtensive.Collections; -using Xtensive.Core; - namespace Xtensive.Orm.Rse.Providers { @@ -17,7 +12,6 @@ namespace Xtensive.Orm.Rse.Providers /// Compilable provider that iterates over /// provider result for each item from the provider. /// - [Serializable] public sealed class ApplyProvider : BinaryProvider, IInlinableProvider { diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/BinaryProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/BinaryProvider.cs index 8d0211ccb8..c9cc7e448e 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/BinaryProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/BinaryProvider.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Rse.Providers /// Base class for binary operation provider over /// the and providers. /// - [Serializable] public abstract class BinaryProvider : CompilableProvider { /// diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/CalculateProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/CalculateProvider.cs index a7142712ba..4b2cfda187 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/CalculateProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/CalculateProvider.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Rse.Providers /// /// Compilable provider that calculates columns from . /// - [Serializable] public class CalculateProvider : UnaryProvider, IInlinableProvider { diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/ConcatProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/ConcatProvider.cs index 3bb954dfe0..57f1ad898e 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/ConcatProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/ConcatProvider.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Rse.Providers /// Produces concatenation between and /// sources. /// - [Serializable] public sealed class ConcatProvider : BinaryProvider { #region Header build diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/ContainsTableProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/ContainsTableProvider.cs index 62ff8b20c9..2ef5475012 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/ContainsTableProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/ContainsTableProvider.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Rse.Providers /// /// Executes full-text search (contains table query) against specified . /// - [Serializable] public sealed class ContainsTableProvider : CompilableProvider { public Func SearchCriteria { get; } diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/DistinctProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/DistinctProvider.cs index 9f23130099..e03a58b6c7 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/DistinctProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/DistinctProvider.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Rse.Providers /// /// Distinct provider /// - [Serializable] public sealed class DistinctProvider : UnaryProvider { // Constructors diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/ExceptProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/ExceptProvider.cs index e472702345..534f83d39d 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/ExceptProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/ExceptProvider.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Rse.Providers /// Produces except operation between and /// sources. /// - [Serializable] public sealed class ExceptProvider : BinaryProvider { #region Header build diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/ExistenceProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/ExistenceProvider.cs index c736e9070a..5104aeb472 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/ExistenceProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/ExistenceProvider.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Rse.Providers /// Compilable provider that returns column. /// Column value is if contains any result; otherwise . /// - [Serializable] public sealed class ExistenceProvider : UnaryProvider { private static readonly TupleDescriptor BoolTupleDescriptor = TupleDescriptor.Create(new[] { WellKnownTypes.Bool }); diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/FilterProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/FilterProvider.cs index 54fc42e577..290590cb6e 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/FilterProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/FilterProvider.cs @@ -7,7 +7,6 @@ using System; using System.Linq.Expressions; using Xtensive.Core; - using Xtensive.Tuples; using Tuple = Xtensive.Tuples.Tuple; @@ -17,7 +16,6 @@ namespace Xtensive.Orm.Rse.Providers /// Compilable provider that declares filtering operation /// over the . /// - [Serializable] public sealed class FilterProvider : UnaryProvider { /// diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/FreeTextProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/FreeTextProvider.cs index d7194090ae..2e920b2672 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/FreeTextProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/FreeTextProvider.cs @@ -17,7 +17,6 @@ namespace Xtensive.Orm.Rse.Providers /// /// Executes full-text search (free text query) against specified . /// - [Serializable] public sealed class FreeTextProvider : CompilableProvider { public Func SearchCriteria { get; } diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/IncludeProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/IncludeProvider.cs index d053630d96..6813e7994e 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/IncludeProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/IncludeProvider.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq.Expressions; using Xtensive.Core; using Xtensive.Reflection; @@ -20,7 +19,6 @@ namespace Xtensive.Orm.Rse.Providers /// Column value is if source value equal to one of provided values; /// otherwise, . /// - [Serializable] public sealed class IncludeProvider: UnaryProvider, IInlinableProvider { @@ -43,7 +41,7 @@ public sealed class IncludeProvider: UnaryProvider, /// /// Gets the filtered columns. /// - public IReadOnlyList FilteredColumns { [DebuggerStepThrough] get; } + public IReadOnlyList FilteredColumns { get; } /// /// Gets filter data. diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/IndexProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/IndexProvider.cs index 5756c8614a..fce4dd8913 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/IndexProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/IndexProvider.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Rse.Providers /// /// Gives access to the specified . /// - [Serializable] public sealed class IndexProvider : CompilableProvider { /// diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/IntersectProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/IntersectProvider.cs index de2a4f7a3b..1aece63691 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/IntersectProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/IntersectProvider.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Rse.Providers /// Produces intersect operation between and /// sources. /// - [Serializable] public sealed class IntersectProvider : BinaryProvider { #region Header build diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/JoinProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/JoinProvider.cs index 40fceb17e1..7ae2a3b005 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/JoinProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/JoinProvider.cs @@ -8,14 +8,12 @@ using System.Linq; using Xtensive.Core; - namespace Xtensive.Orm.Rse.Providers { /// /// Produces equality join between and /// sources. /// - [Serializable] public sealed class JoinProvider : BinaryProvider { private const string ToStringFormat = "{0}, {1}"; diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/LockProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/LockProvider.cs index dbc5d0c807..cb517d657b 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/LockProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/LockProvider.cs @@ -6,13 +6,11 @@ using System; - namespace Xtensive.Orm.Rse.Providers { /// /// Acquires the lock for a data in a source provider. /// - [Serializable] public sealed class LockProvider : UnaryProvider { /// diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/OrderProviderBase.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/OrderProviderBase.cs index e3821bdd42..6f6dfdb337 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/OrderProviderBase.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/OrderProviderBase.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Rse.Providers /// /// Base class for any compilable sorting providers (such as ). /// - [Serializable] public abstract class OrderProviderBase : UnaryProvider { /// diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/PagingProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/PagingProvider.cs index fee3766124..7a4d024ead 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/PagingProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/PagingProvider.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Rse.Providers /// /// Compilable provider that skips X result records and takes Y result records from . /// - [Serializable] public sealed class PagingProvider : UnaryProvider { /// diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/PredicateJoinProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/PredicateJoinProvider.cs index 6bfc829934..4589988b33 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/PredicateJoinProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/PredicateJoinProvider.cs @@ -6,7 +6,6 @@ using System; using System.Linq.Expressions; - using Tuple = Xtensive.Tuples.Tuple; namespace Xtensive.Orm.Rse.Providers @@ -15,7 +14,6 @@ namespace Xtensive.Orm.Rse.Providers /// Produces join between and /// sources by . /// - [Serializable] public sealed class PredicateJoinProvider : BinaryProvider { /// diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/RawProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/RawProvider.cs index 4d3b63d090..d869aeaaae 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/RawProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/RawProvider.cs @@ -8,7 +8,6 @@ using System.Collections.Generic; using System.Linq.Expressions; using Xtensive.Core; - using Xtensive.Tuples; using Tuple = Xtensive.Tuples.Tuple; @@ -17,7 +16,6 @@ namespace Xtensive.Orm.Rse.Providers /// /// Enumerates specified array of instances. /// - [Serializable] public sealed class RawProvider : CompilableProvider { private Func> compiledSource; diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/RowNumberProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/RowNumberProvider.cs index 03e4604754..4fa6bb62f4 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/RowNumberProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/RowNumberProvider.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Rse.Providers /// /// Compilable provider that adds row number to . /// - [Serializable] public sealed class RowNumberProvider : UnaryProvider { /// diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/SeekProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/SeekProvider.cs index c93ba61dd6..a64f3d09e2 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/SeekProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/SeekProvider.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Rse.Providers /// /// Compilable provider that returns one record if it matches specified from . /// - [Serializable] public sealed class SeekProvider : UnaryProvider { /// diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/SelectProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/SelectProvider.cs index 239b465b17..4f5d1cde7e 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/SelectProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/SelectProvider.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using Xtensive.Core; @@ -15,13 +14,12 @@ namespace Xtensive.Orm.Rse.Providers /// /// Compilable provider that declares select operator over the . /// - [Serializable] public sealed class SelectProvider : UnaryProvider { /// /// Indexes of columns that should be selected from the . /// - public IReadOnlyList ColumnIndexes { [DebuggerStepThrough] get; } + public IReadOnlyList ColumnIndexes { get; } /// protected override string ParametersToString() diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/SkipProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/SkipProvider.cs index 4efdd3de3d..e2f7df07a8 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/SkipProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/SkipProvider.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Rse.Providers /// /// Compilable provider that skips result records from . Skip amount is specified using property. /// - [Serializable] public sealed class SkipProvider : UnaryProvider { /// diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/SortProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/SortProvider.cs index 279ed35f36..e4bb2d934d 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/SortProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/SortProvider.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Rse.Providers /// Compilable provider that sorts the /// by . /// - [Serializable] public sealed class SortProvider : OrderProviderBase { // Constructors diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/StoreProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/StoreProvider.cs index 052506f103..32061ac943 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/StoreProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/StoreProvider.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Rse.Providers /// Provides access to some previously stored named /// or stores the specified with the specified . /// - [Serializable] public sealed class StoreProvider : CompilableProvider { /// diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/TagProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/TagProvider.cs index 5e443e5b75..ac4a06f3bc 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/TagProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/TagProvider.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Rse.Providers /// /// Injects SQL comment for query identification /// - [Serializable] public sealed class TagProvider : UnaryProvider { public readonly string Tag; diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/TakeProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/TakeProvider.cs index ae45afe3cc..660317472e 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/TakeProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/TakeProvider.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Rse.Providers /// /// Compilable provider that takes first N result records from . Amount of records is specified using property. /// - [Serializable] public sealed class TakeProvider : UnaryProvider { /// diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/UnionProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/UnionProvider.cs index d95a3eb372..e250202772 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/UnionProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Compilable/UnionProvider.cs @@ -16,7 +16,6 @@ namespace Xtensive.Orm.Rse.Providers /// Produces union between and /// sources. /// - [Serializable] public sealed class UnionProvider : BinaryProvider { #region Header build diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/CompilableProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/CompilableProvider.cs index eadf1840f9..d96b0989e1 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/CompilableProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/CompilableProvider.cs @@ -5,7 +5,6 @@ // Created: 2008.07.03 using System; -using System.Collections.Generic; namespace Xtensive.Orm.Rse.Providers { @@ -13,7 +12,6 @@ namespace Xtensive.Orm.Rse.Providers /// Abstract base class for any query provider, /// that requires storage-specific compilation before in can be executed. /// - [Serializable] public abstract class CompilableProvider : Provider { // Constructors diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/CompilableProviderVisitor.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/CompilableProviderVisitor.cs index ca8f534b05..f2aa9eea2e 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/CompilableProviderVisitor.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/CompilableProviderVisitor.cs @@ -17,7 +17,6 @@ namespace Xtensive.Orm.Rse.Providers /// /// visitor class. Result is . /// - [Serializable] public class CompilableProviderVisitor : ProviderVisitor { protected Func translate; diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/EnumerationContext.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/EnumerationContext.cs index 583ffba583..3355648ac5 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/EnumerationContext.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/EnumerationContext.cs @@ -8,20 +8,14 @@ using System.Collections.Generic; using Xtensive.Core; - -using Xtensive.IoC; -using Xtensive.Reflection; - namespace Xtensive.Orm.Rse.Providers { /// /// The single enumeration attempt context for the . /// - [Serializable] public abstract class EnumerationContext { - - private readonly Dictionary, object> cache = new Dictionary, object>(); + private readonly Dictionary, object> cache = new(); /// /// Gets the options of this context. diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Executable/ExecutableRawProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Executable/ExecutableRawProvider.cs index 3a2964ec5e..626ebfeb60 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Executable/ExecutableRawProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Executable/ExecutableRawProvider.cs @@ -16,7 +16,6 @@ namespace Xtensive.Orm.Rse.Providers /// /// Enumerates specified array of instances. /// - [Serializable] public sealed class ExecutableRawProvider : ExecutableProvider { private const string CachedSourceName = "CachedSource"; diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/ExecutableProvider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/ExecutableProvider.cs index c1ba20a441..b74083825f 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/ExecutableProvider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/ExecutableProvider.cs @@ -17,7 +17,6 @@ namespace Xtensive.Orm.Rse.Providers /// /// Abstract base class for any query provider that can be directly executed. /// - [Serializable] public abstract class ExecutableProvider : Provider { /// diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/ExecutableProvider{TOrigin}.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/ExecutableProvider{TOrigin}.cs index 9b04e3735b..1f4e7e2d7a 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/ExecutableProvider{TOrigin}.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/ExecutableProvider{TOrigin}.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Rse.Providers /// Abstract base class for -typed executable providers. /// /// The type of the . - [Serializable] public abstract class ExecutableProvider : ExecutableProvider where TOrigin: CompilableProvider { diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/Provider.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/Provider.cs index 445ed96768..52a730febd 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/Provider.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/Provider.cs @@ -17,7 +17,6 @@ namespace Xtensive.Orm.Rse.Providers /// /// Abstract base class for any query provider. /// - [Serializable] [DebuggerDisplay("{DebuggerDisplayName}, Source count = {Sources.Count}")] public abstract class Provider { diff --git a/Orm/Xtensive.Orm/Orm/Rse/Providers/ProviderVisitor.cs b/Orm/Xtensive.Orm/Orm/Rse/Providers/ProviderVisitor.cs index bb6f7f51fd..1994215b37 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Providers/ProviderVisitor.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Providers/ProviderVisitor.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Rse.Providers /// /// Abstract visitor class. /// - [Serializable] public abstract class ProviderVisitor where TResult : Provider { /// diff --git a/Orm/Xtensive.Orm/Orm/Rse/RecordSetHeader.cs b/Orm/Xtensive.Orm/Orm/Rse/RecordSetHeader.cs index 6299961abb..5bb504046b 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/RecordSetHeader.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/RecordSetHeader.cs @@ -6,14 +6,12 @@ using System; using System.Collections.Generic; +using System.Linq; using Xtensive.Collections; using Xtensive.Core; - using Xtensive.Orm.Model; using Xtensive.Orm.Rse.Providers; using Xtensive.Tuples; -using Tuple = Xtensive.Tuples.Tuple; -using System.Linq; using IndexInfo = Xtensive.Orm.Model.IndexInfo; namespace Xtensive.Orm.Rse @@ -21,7 +19,6 @@ namespace Xtensive.Orm.Rse /// /// Header of . /// - [Serializable] public sealed class RecordSetHeader { private volatile bool hasOrderTupleDescriptor; diff --git a/Orm/Xtensive.Orm/Orm/Rse/SystemColumn.cs b/Orm/Xtensive.Orm/Orm/Rse/SystemColumn.cs index 7835222b53..9d4a45d1f1 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/SystemColumn.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/SystemColumn.cs @@ -12,20 +12,13 @@ namespace Xtensive.Orm.Rse /// /// System column of the . /// - [Serializable] public class SystemColumn : Column { /// - public override SystemColumn Clone(int newIndex) - { - return new SystemColumn(this, newIndex); - } + public override SystemColumn Clone(int newIndex) => new SystemColumn(this, newIndex); /// - public override SystemColumn Clone(string newName) - { - return new SystemColumn(this, newName); - } + public override SystemColumn Clone(string newName) => new SystemColumn(this, newName); /// /// Initializes a new instance of this class. diff --git a/Orm/Xtensive.Orm/Orm/Rse/Transformation/OrderingCorrector.cs b/Orm/Xtensive.Orm/Orm/Rse/Transformation/OrderingCorrector.cs index 30eb41bd01..7c79f1e9a4 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Transformation/OrderingCorrector.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Transformation/OrderingCorrector.cs @@ -6,7 +6,6 @@ using System; using Xtensive.Core; - using Xtensive.Orm.Rse.Compilation; using Xtensive.Orm.Rse.Providers; @@ -15,7 +14,6 @@ namespace Xtensive.Orm.Rse.Transformation /// /// Corrects an ordering of records. /// - [Serializable] public sealed class OrderingCorrector : IPreCompiler { public static OrderingCorrector DefaultInstance { get; } = new OrderingCorrector(); diff --git a/Orm/Xtensive.Orm/Orm/Rse/Transformation/ProviderOrderingDescriptor.cs b/Orm/Xtensive.Orm/Orm/Rse/Transformation/ProviderOrderingDescriptor.cs index b15b96d4ee..6c6dffa1bb 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Transformation/ProviderOrderingDescriptor.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Transformation/ProviderOrderingDescriptor.cs @@ -5,7 +5,6 @@ // Created: 2009.04.24 using System; - using Xtensive.Orm.Rse.Providers; namespace Xtensive.Orm.Rse.Transformation @@ -13,8 +12,7 @@ namespace Xtensive.Orm.Rse.Transformation /// /// Descriptor of a provider's ordering behavior. /// - [Serializable] - public struct ProviderOrderingDescriptor + public readonly struct ProviderOrderingDescriptor { /// /// Gets a value indicating whether the diff --git a/Orm/Xtensive.Orm/Orm/Rse/Transformation/RedundantColumnOptimizer.cs b/Orm/Xtensive.Orm/Orm/Rse/Transformation/RedundantColumnOptimizer.cs index 69667830e0..227db7f750 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Transformation/RedundantColumnOptimizer.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Transformation/RedundantColumnOptimizer.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Rse.Transformation /// /// implementation that removes redundant columns in tree. /// - [Serializable] public class RedundantColumnOptimizer: IPreCompiler { public static RedundantColumnOptimizer Instance { get; } = new RedundantColumnOptimizer(); diff --git a/Orm/Xtensive.Orm/Orm/Rse/Transformation/SkipTakeCorrector.cs b/Orm/Xtensive.Orm/Orm/Rse/Transformation/SkipTakeCorrector.cs index 00b11ee521..c1cc6bf205 100644 --- a/Orm/Xtensive.Orm/Orm/Rse/Transformation/SkipTakeCorrector.cs +++ b/Orm/Xtensive.Orm/Orm/Rse/Transformation/SkipTakeCorrector.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Rse.Transformation /// /// Corrects an using of and /// - [Serializable] public sealed class SkipTakeCorrector : IPreCompiler { public static SkipTakeCorrector FullPaginationSupportCorrector { get; } = new(true, true); diff --git a/Orm/Xtensive.Orm/Orm/Serialization/DeserializationContext.cs b/Orm/Xtensive.Orm/Orm/Serialization/DeserializationContext.cs deleted file mode 100644 index 4175d724fe..0000000000 --- a/Orm/Xtensive.Orm/Orm/Serialization/DeserializationContext.cs +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. -// Created by: Alex Kofman -// Created: 2009.03.30 - -using System; -using System.Collections.Generic; -using System.Runtime.Serialization; -using Xtensive.Core; -using Xtensive.IoC; - -namespace Xtensive.Orm.Serialization -{ - /// - /// Deserialization context. - /// - [Serializable] - public class DeserializationContext: Context - { - private readonly Dictionary serializationInfos = - new Dictionary(); - private bool isDeserialized = false; - private StreamingContext? streamingContext; - - #region Current, Demand & activation-related methods - - /// - /// Gets the current . - /// - public static DeserializationContext Current - { - get { return DeserializationScope.CurrentContext; } - } - - /// - /// Gets the current , - /// or throws , if active context is not found. - /// - /// Current context. - /// is . - public static DeserializationContext Demand() - { - var currentContext = Current; - if (currentContext==null) - throw Exceptions.ContextRequired(); - return currentContext; - } - - - /// - protected override DeserializationScope CreateActiveScope() - { - return new DeserializationScope(this); - } - - /// - public override bool IsActive - { - get { return DeserializationScope.CurrentContext==this; } - } - - #endregion - - internal void SetObjectData(Persistent persistent, SerializationInfo info, StreamingContext context) - { - serializationInfos[persistent] = info; - if (streamingContext==null) - streamingContext = context; - } - - internal void OnDeserialization() - { - if (isDeserialized) - return; - - InitializeEntities(); - DeserializeEntities(); - - isDeserialized = true; - } - - /// - /// Initializes the . - /// - /// The to initialize. - internal protected void InitializeEntity(Entity entity) - { - InitializeEntity(entity, serializationInfos[entity], streamingContext.Value); - } - - - /// - /// Initializes the entity, i.e. deserializes or generates its and creates its . - /// - /// The entity to initialize. - /// The information to populate the . - /// The source from which the object is deserialized. - /// - /// Target is not initialized on this step, therefore it is unable to get or set its field values. - /// - protected virtual void InitializeEntity(Entity entity, SerializationInfo serializationInfo, StreamingContext context) - { - SerializationHelper.InitializeEntity(entity, serializationInfo, streamingContext.Value); - } - - /// - /// Deserializes the 's field values. - /// - /// The to deserialize. - /// The information to populate the 's field values. - /// The source from which the object is deserialized. - /// - /// is already deserialized and all another Entities is already initialized on this step. - /// - protected virtual void DeserializeEntities(Entity entity, SerializationInfo serializationInfo, StreamingContext context) - { - SerializationHelper.DeserializeEntityFields(entity, serializationInfo, context); - } - - private void InitializeEntities() - { - foreach (var pair in serializationInfos) { - var entity = pair.Key as Entity; - var info = pair.Value; - if (entity!=null) { - InitializeEntity(entity, info, streamingContext.Value); - } - } - } - - private void DeserializeEntities() - { - foreach (var pair in serializationInfos) { - var entity = pair.Key as Entity; - var info = pair.Value; - if (entity!=null) - DeserializeEntities(entity, info, streamingContext.Value); - } - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Serialization/DeserializationScope.cs b/Orm/Xtensive.Orm/Orm/Serialization/DeserializationScope.cs deleted file mode 100644 index bdbe1d51d0..0000000000 --- a/Orm/Xtensive.Orm/Orm/Serialization/DeserializationScope.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. -// Created by: Alex Kofman -// Created: 2009.03.30 - -using Xtensive.Core; - -using Xtensive.IoC; - -namespace Xtensive.Orm.Serialization -{ - /// - /// Deserialization scope. - /// - public sealed class DeserializationScope : Scope - { - /// - /// Gets the current context. - /// - public new static DeserializationContext CurrentContext - { - get { return Scope.CurrentContext; } - } - - - // Constructors - - /// - /// Initializes a new instance of this class. - /// - /// The context. - public DeserializationScope(DeserializationContext context) - : base(context) - { - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Serialization/EntityReference.cs b/Orm/Xtensive.Orm/Orm/Serialization/EntityReference.cs deleted file mode 100644 index 7593b65ad1..0000000000 --- a/Orm/Xtensive.Orm/Orm/Serialization/EntityReference.cs +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. -// Created by: Alex Kofman -// Created: 2009.03.18 - -using System; -using System.Runtime.Serialization; -using System.Security; -using System.Security.Permissions; - - -namespace Xtensive.Orm.Serialization -{ - /// - /// Object to be serialized instead of when serialization is used. - /// - [Serializable] - internal sealed class EntityReference : -#pragma warning disable SYSLIB0050 // Type or member is obsolete - IObjectReference, -#pragma warning restore SYSLIB0050 // Type or member is obsolete - ISerializable - { - private const string KeyValueName = WellKnown.KeyFieldName; - private readonly Entity entity; - - [SecurityCritical] - public object GetRealObject(StreamingContext context) - { - return entity; - } - - [SecurityCritical] - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue(KeyValueName, entity.Key.Format()); - } - - public EntityReference(Entity entity) - { - this.entity = entity; - } - - private EntityReference(SerializationInfo info, StreamingContext context) - { - var session = Session.Demand(); - Key key = Key.Parse(session.Domain, info.GetString(KeyValueName)); - entity = session.Query.SingleOrDefault(key); - - if (entity==null) - throw new InvalidOperationException( - string.Format(Strings.ExCannotResolveEntityWithKeyX, key)); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Serialization/SerializationContext.cs b/Orm/Xtensive.Orm/Orm/Serialization/SerializationContext.cs deleted file mode 100644 index fa1e208705..0000000000 --- a/Orm/Xtensive.Orm/Orm/Serialization/SerializationContext.cs +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. -// Created by: Alex Kofman -// Created: 2009.03.18 - -using System; -using System.Runtime.Serialization; -using Xtensive.Core; - -using Xtensive.IoC; - - -namespace Xtensive.Orm.Serialization -{ - /// - /// Serialization context. - /// - public class SerializationContext : Context - { - private readonly Func serializationKindGetter; - - /// - /// Gets the current . - /// - public static SerializationContext Current - { - get { return SerializationScope.CurrentContext; } - } - - /// - /// Gets the current , or throws , if active context is not found. - /// - /// Current context. - /// is . - public static SerializationContext Demand() - { - var currentContext = Current; - if (currentContext==null) - throw Exceptions.ContextRequired(); - return currentContext; - } - - /// - protected override SerializationScope CreateActiveScope() - { - return new SerializationScope(this); - } - - internal void GetEntityData(Entity entity, SerializationInfo info, StreamingContext context) - { - var serializationKind = GetSerializationKind(entity); - if (serializationKind==SerializationKind.ByReference) - GetEntityReferenceData(entity, info, context); - else - GetEntityValueData(entity, info, context); - } - - /// - /// Gets the entity value data, i.e. data which will be deserialized as a new . - /// - /// The to serialize. - /// The object to be populated with serialization information. - /// The destination context of the serialization. - protected virtual void GetEntityValueData(Entity entity, SerializationInfo info, StreamingContext context) - { - SerializationHelper.GetEntityValueData(entity, info, context); - } - - /// - /// Gets the entity reference data, i.e. data which will be deserialized as a reference to existing - /// - /// The to serialize. - /// The object to be populated with serialization information. - /// The destination context of the serialization. - protected virtual void GetEntityReferenceData(Entity entity, SerializationInfo info, StreamingContext context) - { - SerializationHelper.GetEntityReferenceData(entity, info, context); - } - - /// - /// Gets the kind of serialization for the specified . - /// - /// The to be serialized. - /// Serialization kind. - protected virtual SerializationKind GetSerializationKind(Entity entity) - { - return serializationKindGetter.Invoke(entity); - } - - /// - public override bool IsActive - { - get { return SerializationScope.CurrentContext==this; } - } - - - // Constructors - - /// - /// Initializes a new instance of this class. - /// - /// Default . - public SerializationContext(SerializationKind serializationKind) - { - serializationKindGetter = (entity => serializationKind); - } - - /// - /// Initializes a new instance of this class. - /// - /// The getter. - public SerializationContext(Func serializationKindGetter) - { - this.serializationKindGetter = serializationKindGetter ?? throw new ArgumentNullException(nameof(serializationKindGetter)); - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Serialization/SerializationHelper.cs b/Orm/Xtensive.Orm/Orm/Serialization/SerializationHelper.cs deleted file mode 100644 index ce46e97f67..0000000000 --- a/Orm/Xtensive.Orm/Orm/Serialization/SerializationHelper.cs +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. -// Created by: Alex Kofman -// Created: 2009.03.24 - -using System; -using System.Collections.Generic; -using System.Runtime.Serialization; -using System.Security; -using Xtensive.Core; -using Xtensive.Orm.Model; -using Xtensive.Tuples; -using Tuple = Xtensive.Tuples.Tuple; -using System.Linq; - -namespace Xtensive.Orm.Serialization -{ - [Serializable] - internal static class SerializationHelper - { - public static void GetEntityValueData(Entity entity, SerializationInfo info, StreamingContext context) - { - foreach (FieldInfo field in entity.TypeInfo.Fields) { - if (!IsSerializable(field)) - continue; - - object value = entity.GetFieldValue(field); - info.AddValue(field.Name, value, field.ValueType); - } - } - - [SecuritySafeCritical] - public static void GetEntityReferenceData(Entity entity, SerializationInfo info, StreamingContext context) - { - EntityReference reference = new EntityReference(entity); - info.SetType(typeof(EntityReference)); - reference.GetObjectData(info, context); - } - - public static void InitializeEntity(Entity entity, SerializationInfo info, StreamingContext context) - { - if (IsInitialized(entity)) - return; - - var session = Session.Demand(); - var domain = session.Domain; - var registry = session.StorageNode.TypeIdRegistry; - var typeInfo = domain.Model.Types[entity.GetType()]; - var isTemporary = session.LazyKeyGenerationIsEnabled && !session.IsPersisting; - var keyGenerator = domain.KeyGenerators.Get(typeInfo.Key, isTemporary); - var keyValue = keyGenerator!=null - ? keyGenerator.GenerateKey(typeInfo.Key, session) - : DeserializeKeyFields(typeInfo, registry, info, context); - var key = Key.Create(domain, session.StorageNodeId, typeInfo, TypeReferenceAccuracy.ExactType, keyValue); - - var entityState = session.CreateEntityState(key, false); - entity.State = entityState; - session.InitializeEntity(entity, false); - } - - public static Tuple DeserializeKeyFields(TypeInfo entityType, TypeIdRegistry registry, SerializationInfo info, StreamingContext context) - { - var keyTuple = Tuple.Create(entityType.Hierarchy.Key.TupleDescriptor); - foreach (FieldInfo keyField in entityType.Fields.Where(f => f.IsPrimaryKey && f.Parent == null)) { - if (keyField.IsTypeId) - keyTuple.SetValue(keyField.MappingInfo.Offset, registry[entityType]); - else { - var value = info.GetValue(keyField.Name, keyField.ValueType); - if (keyField.IsEntity) { - var referencedEntity = (Entity) value; - if (!IsInitialized(referencedEntity)) - DeserializationContext.Demand().InitializeEntity(referencedEntity); - var referencedTuple = referencedEntity.Key.Value; - referencedTuple.CopyTo(keyTuple, keyField.MappingInfo.Offset); - } - else - keyTuple.SetValue(keyField.MappingInfo.Offset, value); - } - } - return keyTuple; - } - - public static void DeserializeEntityFields(Entity entity, SerializationInfo info, StreamingContext context) - { - foreach (FieldInfo field in entity.TypeInfo.Fields) { - if (field.IsPrimaryKey) - continue; - - if (!IsSerializable(field)) - continue; - - object value = info.GetValue(field.Name, field.ValueType); - entity.SetFieldValue(field, value); - } - } - - private static bool IsSerializable(FieldInfo field) - { - return field.Parent==null && !field.IsTypeId; - } - - private static bool IsInitialized(Entity entity) - { - return entity.State != null; - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Serialization/SerializationKind.cs b/Orm/Xtensive.Orm/Orm/Serialization/SerializationKind.cs deleted file mode 100644 index 019486243e..0000000000 --- a/Orm/Xtensive.Orm/Orm/Serialization/SerializationKind.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. -// Created by: Alex Kofman -// Created: 2009.03.18 - -namespace Xtensive.Orm.Serialization -{ - /// - /// Serialization kind (serialization by reference or by value). - /// - public enum SerializationKind - { - /// - /// Serialization by reference. - /// - ByReference = 0, - - /// - /// Serialization by value - /// - ByValue = 1, - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Serialization/SerializationScope.cs b/Orm/Xtensive.Orm/Orm/Serialization/SerializationScope.cs deleted file mode 100644 index dfdbde251a..0000000000 --- a/Orm/Xtensive.Orm/Orm/Serialization/SerializationScope.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (C) 2003-2010 Xtensive LLC. -// All rights reserved. -// For conditions of distribution and use, see license. -// Created by: Alex Kofman -// Created: 2009.03.18 - -using Xtensive.Core; - -using Xtensive.IoC; - -namespace Xtensive.Orm.Serialization -{ - /// - /// Serialization scope. - /// - public sealed class SerializationScope : Scope - { - /// - /// Gets the current context. - /// - public new static SerializationContext CurrentContext - { - get { return Scope.CurrentContext; } - } - - - // Constructors - - /// - /// Initializes a new instance of this class. - /// - /// The context. - public SerializationScope(SerializationContext context) - : base(context) - { - } - } -} \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Session.cs b/Orm/Xtensive.Orm/Orm/Session.cs index b4273b1085..ed25de5b2a 100644 --- a/Orm/Xtensive.Orm/Orm/Session.cs +++ b/Orm/Xtensive.Orm/Orm/Session.cs @@ -140,7 +140,7 @@ public bool IsDisposed /// /// Gets the operations registry of this . /// - public OperationRegistry Operations { get; private set; } + public IOperationRegistry Operations { get; } /// /// Gets or sets timeout for all s that @@ -570,7 +570,7 @@ internal Session(Domain domain, StorageNode selectedStorageNode, SessionConfigur PairSyncManager = new SyncManager(this); RemovalProcessor = new RemovalProcessor(this); pinner = new Pinner(this); - Operations = new OperationRegistry(this); + NonPairedReferencesRegistry = new NonPairedReferenceChangesRegistry(this); CommandProcessorContextProvider = new CommandProcessorContextProvider(this); @@ -582,6 +582,11 @@ internal Session(Domain domain, StorageNode selectedStorageNode, SessionConfigur // Creating Services Services = CreateServices(); + // If there is no service registered we use null object + Operations = !Domain.Configuration.Types.ServiceRegistrations.Any(static r => r.Type == WellKnownOrmInterfaces.OperationRegistry) + ? new VoidOperationRegistry(this) + : Services.Get(); + disposableSet = new DisposableSet(); remapper = new KeyRemapper(this); diff --git a/Orm/Xtensive.Orm/Orm/Structure.cs b/Orm/Xtensive.Orm/Orm/Structure.cs index 9b9108409a..1eba6c5e13 100644 --- a/Orm/Xtensive.Orm/Orm/Structure.cs +++ b/Orm/Xtensive.Orm/Orm/Structure.cs @@ -8,15 +8,11 @@ using System.ComponentModel; using System.Diagnostics; using System.Linq; -using System.Runtime.Serialization; -using Xtensive.Comparison; using Xtensive.Core; using Xtensive.Orm.Validation; using Xtensive.Tuples; using Xtensive.Orm.Configuration; -using Xtensive.Orm.Serialization; -using Xtensive.Orm.Services; using Tuple = Xtensive.Tuples.Tuple; using Xtensive.Orm; using Xtensive.Orm.Model; @@ -474,15 +470,5 @@ protected Structure(Persistent owner, FieldInfo field) throw; } } - - /// - /// Initializes a new instance of the class. - /// - /// The info. - /// The context. - protected Structure(SerializationInfo info, StreamingContext context) - { - DeserializationContext.Demand().SetObjectData(this, info, context); - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/TransactionState.cs b/Orm/Xtensive.Orm/Orm/TransactionState.cs index d29eea03e7..22efa0f085 100644 --- a/Orm/Xtensive.Orm/Orm/TransactionState.cs +++ b/Orm/Xtensive.Orm/Orm/TransactionState.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm /// /// Indicates operational state of the instance. /// - [Serializable] public enum TransactionState { /// diff --git a/Orm/Xtensive.Orm/Orm/TypeReference.cs b/Orm/Xtensive.Orm/Orm/TypeReference.cs index 93faa6d0f9..e9a3e5f8e8 100644 --- a/Orm/Xtensive.Orm/Orm/TypeReference.cs +++ b/Orm/Xtensive.Orm/Orm/TypeReference.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm /// /// Reference to with the specified degree of accuracy. /// - [Serializable] public readonly struct TypeReference { /// diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Attributes/AssemblyInfoAttribute.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Attributes/AssemblyInfoAttribute.cs index fc357f60bf..0e25ddc76b 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Attributes/AssemblyInfoAttribute.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Attributes/AssemblyInfoAttribute.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Upgrade /// /// An attribute providing persistence-related information for the assembly. /// - [Serializable] [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public sealed class AssemblyInfoAttribute : Attribute diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Attributes/RecycledAttribute.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Attributes/RecycledAttribute.cs index 38906a90ef..1b27bd3cb0 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Attributes/RecycledAttribute.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Attributes/RecycledAttribute.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Upgrade /// /// An attribute describing the recycled type or property. /// - [Serializable] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public sealed class RecycledAttribute : Attribute diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Hints/ChangeFieldTypeHint.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Hints/ChangeFieldTypeHint.cs index 70be9dbccb..3282bff914 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Hints/ChangeFieldTypeHint.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Hints/ChangeFieldTypeHint.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Upgrade /// /// Change field type enforced (ignore type conversion verification) hint. /// - [Serializable] public sealed class ChangeFieldTypeHint : UpgradeHint, IEquatable { diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Hints/CopyFieldHint.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Hints/CopyFieldHint.cs index 9c0a71dfbe..ffc7ed337a 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Hints/CopyFieldHint.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Hints/CopyFieldHint.cs @@ -7,7 +7,6 @@ using System; using System.Linq.Expressions; using Xtensive.Core; - using Xtensive.Reflection; namespace Xtensive.Orm.Upgrade @@ -15,7 +14,6 @@ namespace Xtensive.Orm.Upgrade /// /// Copy field hint. /// - [Serializable] public class CopyFieldHint : UpgradeHint, IEquatable { diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Hints/MergeTypeHint.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Hints/MergeTypeHint.cs index 99180bf541..b6eb435bf9 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Hints/MergeTypeHint.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Hints/MergeTypeHint.cs @@ -5,10 +5,7 @@ // Created: 2009.04.29 using System; -using System.Collections.Generic; -using System.Linq.Expressions; using Xtensive.Core; - using Xtensive.Reflection; namespace Xtensive.Orm.Upgrade @@ -16,7 +13,6 @@ namespace Xtensive.Orm.Upgrade /// /// Rename type hint. /// - [Serializable] public sealed class MergeTypeHint : UpgradeHint, IEquatable { diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Hints/MoveFieldHint.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Hints/MoveFieldHint.cs index 96d975efc6..b53ac5a395 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Hints/MoveFieldHint.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Hints/MoveFieldHint.cs @@ -5,10 +5,8 @@ // Created: 2009.10.14 using System; -using System.Diagnostics; using System.Linq.Expressions; using Xtensive.Core; - using Xtensive.Reflection; namespace Xtensive.Orm.Upgrade @@ -16,7 +14,6 @@ namespace Xtensive.Orm.Upgrade /// /// Move field hint. /// - [Serializable] public class MoveFieldHint : UpgradeHint, IEquatable { diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Hints/RecycledTypeHint.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Hints/RecycledTypeHint.cs index 92c44cbd2e..b2b15e2002 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Hints/RecycledTypeHint.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Hints/RecycledTypeHint.cs @@ -5,18 +5,13 @@ // Created: 2009.04.29 using System; -using System.Collections.Generic; -using System.Linq.Expressions; using Xtensive.Core; -using Xtensive.Reflection; - namespace Xtensive.Orm.Upgrade { /// /// Rename type hint. /// - [Serializable] public sealed class RecycledTypeHint : UpgradeHint, IEquatable { diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Hints/RemoveFieldHint.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Hints/RemoveFieldHint.cs index 547e657cd8..287c505f82 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Hints/RemoveFieldHint.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Hints/RemoveFieldHint.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Upgrade /// /// Remove field hint. /// - [Serializable] public class RemoveFieldHint : UpgradeHint, IEquatable { diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Hints/RemoveTypeHint.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Hints/RemoveTypeHint.cs index 17134b2290..c2bd1868b1 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Hints/RemoveTypeHint.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Hints/RemoveTypeHint.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Upgrade /// /// Remove type hint. /// - [Serializable] public class RemoveTypeHint : UpgradeHint, IEquatable { diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Hints/RenameFieldHint.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Hints/RenameFieldHint.cs index 4fc163b84a..92e8075d87 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Hints/RenameFieldHint.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Hints/RenameFieldHint.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Upgrade /// /// Rename field hint. /// - [Serializable] public sealed class RenameFieldHint : UpgradeHint, IEquatable { diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Hints/RenameTypeHint.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Hints/RenameTypeHint.cs index 0f0ee9ab0a..6f9c6f939c 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Hints/RenameTypeHint.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Hints/RenameTypeHint.cs @@ -14,12 +14,9 @@ namespace Xtensive.Orm.Upgrade /// /// Rename type hint. /// - [Serializable] public sealed class RenameTypeHint : UpgradeHint, IEquatable { - private const string ToStringFormat = "Rename type: {0} -> {1}"; - /// /// Gets the new type. /// diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Hints/UpgradeHint.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Hints/UpgradeHint.cs index 5b94bfe73f..083fadaa76 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Hints/UpgradeHint.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Hints/UpgradeHint.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Upgrade /// /// Abstract base class for any upgrade hint. /// - [Serializable] public abstract class UpgradeHint : IEquatable { diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/ColumnInfoCollection.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/ColumnInfoCollection.cs index a90e584408..f252c65aad 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/ColumnInfoCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/ColumnInfoCollection.cs @@ -5,7 +5,6 @@ // Created: 2009.03.20 using System; - using Xtensive.Modelling; namespace Xtensive.Orm.Upgrade.Model @@ -13,7 +12,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// Column collection. /// - [Serializable] public sealed class ColumnInfoCollection : NodeCollectionBase, IUnorderedNodeCollection { diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/ColumnInfoRef.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/ColumnInfoRef.cs index 7d92afd470..641cfe7278 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/ColumnInfoRef.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/ColumnInfoRef.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// An abstract base class for all columns refs. /// - [Serializable] public abstract class ColumnInfoRef : Ref where TParent: NodeBase { diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/Exceptions/IntegrityException.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/Exceptions/IntegrityException.cs index cd6e13b65f..b37a9e3abb 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/Exceptions/IntegrityException.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/Exceptions/IntegrityException.cs @@ -5,7 +5,6 @@ // Created: 2009.03.23 using System; -using System.Runtime.Serialization; using Xtensive.Modelling; @@ -14,7 +13,7 @@ namespace Xtensive.Orm.Upgrade.Model /// /// Describes errors detected during . execution. /// - [Serializable] + [Obsolete("No longer in use")] public class IntegrityException : Exception { /// @@ -39,23 +38,5 @@ public IntegrityException(string message, string nodePath) { NodePath = nodePath; } - - // Serialization - - /// - /// Initializes a new instance of the class. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// - /// The class name is null or is zero (0). -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - public IntegrityException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/Exceptions/ValidationException.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/Exceptions/ValidationException.cs index 5d6acd52c2..45c455ceef 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/Exceptions/ValidationException.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/Exceptions/ValidationException.cs @@ -5,9 +5,6 @@ // Created: 2009.03.23 using System; -using System.Runtime.Serialization; -using System.Security; -using System.Security.Permissions; using Xtensive.Modelling; @@ -17,84 +14,16 @@ namespace Xtensive.Orm.Upgrade.Model /// Describes errors detected during /// . execution. /// - [Serializable] - public class ValidationException : Exception + /// + /// Initializes a new instance of this class. + /// + /// The message. + /// The path of the invalid node. + public class ValidationException(string message, string nodePath) : Exception(message) { /// /// Gets the path of the node which validation has failed. /// - public string NodePath { get; private set; } - - - // Constructors - - /// - protected ValidationException() - { - } - - /// - public ValidationException(string message) - : base(message) - { - } - - /// - public ValidationException(string message, Exception innerException) - : base(message, innerException) - { - } - - /// - /// Initializes a new instance of this class. - /// - /// The message. - /// The path of the invalid node. - public ValidationException(string message, string nodePath) - : base(message) - { - NodePath = nodePath; - } - - #region Serializing members - - /// - /// Initializes a new instance of the class. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// - /// The class name is null or is zero (0). -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - protected ValidationException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - NodePath = info.GetString("NodePath"); - } - - /// - /// When overridden in a derived class, sets the with information about the exception. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is a null reference (Nothing in Visual Basic). - /// - /// - /// - /// - /// - [SecurityCritical] -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue("NodePath", NodePath); - } - - #endregion + public string NodePath { get; } = nodePath; } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/ForeignKeyCollection.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/ForeignKeyCollection.cs index 20796c6d5f..35f2af1d8b 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/ForeignKeyCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/ForeignKeyCollection.cs @@ -5,16 +5,13 @@ // Created: 2009.03.23 using System; - using Xtensive.Modelling; -using Xtensive.Orm.Upgrade.Model; namespace Xtensive.Orm.Upgrade.Model { /// /// Foreign key collection. /// - [Serializable] public sealed class ForeignKeyCollection : NodeCollectionBase, IUnorderedNodeCollection { diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/ForeignKeyColumnCollection.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/ForeignKeyColumnCollection.cs index d94d254bc4..dfe920f7df 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/ForeignKeyColumnCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/ForeignKeyColumnCollection.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// A collection of instances. /// - [Serializable] public sealed class ForeignKeyColumnCollection : NodeCollectionBase { /// @@ -24,7 +23,7 @@ public void Set(StorageIndexInfo source) { Clear(); foreach (var keyColumn in source.KeyColumns) - new ForeignKeyColumnRef(Parent, keyColumn.Value); + _ = new ForeignKeyColumnRef(Parent, keyColumn.Value); } diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/ForeignKeyColumnRef.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/ForeignKeyColumnRef.cs index 001d991aed..e147ceebd5 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/ForeignKeyColumnRef.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/ForeignKeyColumnRef.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// References to foreign key column. /// - [Serializable] public sealed class ForeignKeyColumnRef : Ref { /// diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/ForeignKeyInfo.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/ForeignKeyInfo.cs index 5f87f5bb2c..eb63b21c6e 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/ForeignKeyInfo.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/ForeignKeyInfo.cs @@ -16,7 +16,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// Foreign key. /// - [Serializable] [DataDependent] public sealed class ForeignKeyInfo : NodeBase { @@ -30,9 +29,8 @@ public sealed class ForeignKeyInfo : NodeBase [Property(Priority = -1100)] public PrimaryIndexInfo PrimaryKey { - get { return primaryKey; } - set - { + get => primaryKey; + set { EnsureIsEditable(); using (var scope = LogPropertyChange("PrimaryKey", value)) { primaryKey = value; @@ -53,9 +51,8 @@ public PrimaryIndexInfo PrimaryKey [Property(Priority = -110)] public ReferentialAction OnRemoveAction { - get { return onRemoveAction; } - set - { + get => onRemoveAction; + set { EnsureIsEditable(); using (var scope = LogPropertyChange("OnUpdateAction", value)) { onRemoveAction = value; @@ -70,9 +67,8 @@ public ReferentialAction OnRemoveAction [Property(Priority = -100)] public ReferentialAction OnUpdateAction { - get { return onUpdateAction; } - set - { + get => onUpdateAction; + set { EnsureIsEditable(); using (var scope = LogPropertyChange("OnUpdateAction", value)) { onUpdateAction = value; @@ -88,10 +84,8 @@ protected override void ValidateState() using (var ea = new ExceptionAggregator()) { ea.Execute(base.ValidateState); - if (PrimaryKey == null) { - ea.Execute(() => { - throw new ValidationException(Strings.ExUndefinedPrimaryKey, Path); - }); + if (PrimaryKey is null) { + ea.Add(new ValidationException(Strings.ExUndefinedPrimaryKey, Path), handle: true); ea.Complete(); return; } @@ -100,21 +94,12 @@ protected override void ValidateState() var fkColumns = ForeignKeyColumns; if (pkColumns.Count!=pkColumns - .Zip(fkColumns, (pkColumn, fkColumn) => new Pair(pkColumn, fkColumn)) + .Zip(fkColumns, static (pkColumn, fkColumn) => new Pair(pkColumn, fkColumn)) .Count(p => CompareKeyColumns(p.First, p.Second))) { - ea.Execute(() => { - throw new ValidationException( - Strings.ExInvalidForeignKeyStructure, Path); - }); - } - // var pkTypes = PrimaryKey.KeyColumns.Select(c => c.Value.Type); - // var fkTypes = ForeignKeyColumns.Select(c => c.Value.Type); - // if (pkTypes.Count()!=pkTypes.Zip(fkTypes).Where(p => p.First==p.Second).Count()) - // ea.Execute(() => { - // throw new ValidationException( - // Strings.ExInvalidForeignKeyStructure, Path); - // }); + ea.Add(new ValidationException( + Strings.ExInvalidForeignKeyStructure, Path), handle: true); + } ea.Complete(); } @@ -137,7 +122,7 @@ protected override void Initialize() private static bool CompareKeyColumns(KeyColumnRef first, ForeignKeyColumnRef second) { - if (first == null || second == null) + if (first is null || second is null) return false; return first.Index==second.Index @@ -146,7 +131,7 @@ private static bool CompareKeyColumns(KeyColumnRef first, ForeignKeyColumnRef se private static bool CompareTypes(StorageTypeInfo first, StorageTypeInfo second) { - if (first==null || second==null) + if (first is null || second is null) return false; if (first.IsTypeUndefined || second.IsTypeUndefined) return true; diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/FullTextColumnRef.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/FullTextColumnRef.cs index 1de0251bbe..7947e02d63 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/FullTextColumnRef.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/FullTextColumnRef.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// Reference to full-text column. /// - [Serializable] public sealed class FullTextColumnRef : ColumnInfoRef { [Property(Priority = -1100, CaseInsensitiveComparison = true)] diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/FullTextColumnRefCollection.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/FullTextColumnRefCollection.cs index e080c8a678..f9b8bfd031 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/FullTextColumnRefCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/FullTextColumnRefCollection.cs @@ -5,16 +5,12 @@ // Created: 2010.01.14 using System; -using System.Diagnostics; - -using Xtensive.Modelling; namespace Xtensive.Orm.Upgrade.Model { /// /// A collection of instances. /// - [Serializable] public sealed class FullTextColumnRefCollection : NodeCollectionBase { diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/FullTextIndexInfoCollection.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/FullTextIndexInfoCollection.cs index cba4efdfad..c1744d824e 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/FullTextIndexInfoCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/FullTextIndexInfoCollection.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// A collection of full-text indexes. /// - [Serializable] public class FullTextIndexInfoCollection: NodeCollectionBase, IUnorderedNodeCollection { diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/IncludedColumnRef.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/IncludedColumnRef.cs index 18519d6f50..e87c504028 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/IncludedColumnRef.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/IncludedColumnRef.cs @@ -5,7 +5,6 @@ // Created: 2009.03.24 using System; - using Xtensive.Modelling; namespace Xtensive.Orm.Upgrade.Model @@ -13,7 +12,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// References to included column. /// - [Serializable] public sealed class IncludedColumnRef : ColumnInfoRef { /// diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/IncludedColumnRefCollection.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/IncludedColumnRefCollection.cs index b86e941555..c457d3b40c 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/IncludedColumnRefCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/IncludedColumnRefCollection.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// A collection of instances. /// - [Serializable] public sealed class IncludedColumnRefCollection : NodeCollectionBase { // Constructors diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/KeyColumnRef.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/KeyColumnRef.cs index 446bfe634c..c5453a5167 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/KeyColumnRef.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/KeyColumnRef.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// References to key column. /// - [Serializable] public sealed class KeyColumnRef : KeyColumnRef { /// diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/KeyColumnRefCollection.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/KeyColumnRefCollection.cs index 30473adec2..34f5889edf 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/KeyColumnRefCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/KeyColumnRefCollection.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// A collection of instances. /// - [Serializable] public sealed class KeyColumnRefCollection : NodeCollectionBase { // Constructors diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/KeyColumnRef{TParent}.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/KeyColumnRef{TParent}.cs index 33afbc2e03..53987f7a8a 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/KeyColumnRef{TParent}.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/KeyColumnRef{TParent}.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// References to key column. /// - [Serializable] public abstract class KeyColumnRef : ColumnInfoRef where TParent: StorageIndexInfo { @@ -23,8 +22,9 @@ public abstract class KeyColumnRef : ColumnInfoRef /// Gets or sets the column direction. /// [Property(Priority = -1000)] - public Direction Direction { - get { return direction; } + public Direction Direction + { + get => direction; set { EnsureIsEditable(); using (var scope = LogPropertyChange("Direction", value)) { @@ -42,9 +42,7 @@ protected override void ValidateState() using (var ea = new ExceptionAggregator()) { ea.Execute(base.ValidateState); if (direction==Direction.None) { - ea.Execute(() => { - throw new ValidationException(Strings.ExInvalidDirectionValue, Path); - }); + ea.Add(new ValidationException(Strings.ExInvalidDirectionValue, Path), handle: true); } ea.Complete(); } diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/NodeBase.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/NodeBase.cs index e4beaa8257..8f8577b88e 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/NodeBase.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/NodeBase.cs @@ -5,7 +5,6 @@ // Created: 2009.03.20 using System; - using Xtensive.Modelling; namespace Xtensive.Orm.Upgrade.Model @@ -14,46 +13,9 @@ namespace Xtensive.Orm.Upgrade.Model /// A base class for all nodes in storage model. /// /// The type of the parent node. - [Serializable] public abstract class NodeBase : Node where TParent : Node { -// /// -// protected override void PerformCreate() -// { -// base.PerformCreate(); -// Log.Info("Created: {0}", this); -// } -// -// /// -// protected override void PerformMove(Node newParent, string newName, int newIndex) -// { -// using (Log.InfoRegion("Moving: {0}", this)) -// { -// if (Parent != newParent) -// Log.Info("new Parent={0}", newParent); -// if (Name != newName) -// Log.Info("new Name={0}", newName); -// if (Index != newIndex) -// Log.Info("new Index={0}", newIndex); -// base.PerformMove(newParent, newName, newIndex); -// } -// } -// -// /// -// protected override void PerformShift(int offset) -// { -// Log.Info("Shifting: {0}, from {1} to {2}", this, Index, Index + offset); -// base.PerformShift(offset); -// } -// -// /// -// protected override void ValidateRemove() -// { -// base.ValidateRemove(); -// Log.Info("Removed: {0}", this); -// } - // Constructors diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/NodeCollectionBase.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/NodeCollectionBase.cs index eb466fd687..9088f7ff2e 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/NodeCollectionBase.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/NodeCollectionBase.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// The type of the node. /// The type of the parent node. - [Serializable] public abstract class NodeCollectionBase : NodeCollection where TNode : Node where TParent : Node diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/PartialIndexFilterInfo.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/PartialIndexFilterInfo.cs index 13e68ff93e..6c4fb9be2e 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/PartialIndexFilterInfo.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/PartialIndexFilterInfo.cs @@ -9,10 +9,9 @@ namespace Xtensive.Orm.Upgrade.Model { - [Serializable] public sealed class PartialIndexFilterInfo : IEquatable { - public string Expression { get; private set; } + public string Expression { get; } #region Equality members @@ -36,17 +35,11 @@ public override bool Equals(object obj) return Equals((PartialIndexFilterInfo)obj); } - public override int GetHashCode() - { - return Expression.GetHashCode(); - } + public override int GetHashCode() => Expression.GetHashCode(); #endregion - public override string ToString() - { - return Expression; - } + public override string ToString() => Expression; // Constructors diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/PrimaryIndexInfo.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/PrimaryIndexInfo.cs index 2bd67e6ba8..675fab8e4e 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/PrimaryIndexInfo.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/PrimaryIndexInfo.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// Primary index. /// - [Serializable] public sealed class PrimaryIndexInfo : StorageIndexInfo { /// @@ -33,7 +32,7 @@ public void PopulateValueColumns() { var keySet = KeyColumns.Select(kc => kc.Value).ToHashSet(); foreach (var column in Parent.Columns.Where(c => !keySet.Contains(c))) - new ValueColumnRef(this, column); + _ = new ValueColumnRef(this, column); } /// @@ -42,30 +41,26 @@ protected override void ValidateState() { using (var ea = new ExceptionAggregator()) { ea.Execute(base.ValidateState); - base.ValidateState(); var tableColumns = Parent.Columns; var keys = KeyColumns.Select(keyRef => keyRef.Value).ToArray(KeyColumns.Count); - if (keys.Length==0) - ea.Execute(() => { - throw new ValidationException(Strings.ExEmptyKeyColumnsCollection, Path); - }); - if (keys.Where(ci => ci.Type == null || ci.Type.IsNullable).Count() > 0) - ea.Execute(() => { - throw new ValidationException(Strings.ExPrimaryKeyColumnCanNotBeNullable, Path); - }); + if (keys.Length == 0) { + ea.Add(new ValidationException(Strings.ExEmptyKeyColumnsCollection, Path), handle: true); + } + if (keys.Count(static ci => ci.Type is null || ci.Type.IsNullable) > 0) { + ea.Add(new ValidationException(Strings.ExPrimaryKeyColumnCanNotBeNullable, Path), handle: true); + } var values = ValueColumns.Select(valueRef => valueRef.Value).ToArray(ValueColumns.Count); var allCount = keys.Length + values.Length; - if (allCount!=tableColumns.Count) - ea.Execute(() => { - throw new ValidationException(Strings.ExInvalidPrimaryKeyStructure, Path); - }); - if (keys.Concat(values).Zip(tableColumns, (column, tableColumn) => new Pair(column, tableColumn)).Any(p => p.First!=p.Second)) - ea.Execute(() => { - throw new ValidationException(Strings.ExInvalidPrimaryKeyStructure, Path); - }); + if (allCount!=tableColumns.Count) { + ea.Add(new ValidationException(Strings.ExInvalidPrimaryKeyStructure, Path), handle: true); + } + + if (keys.Concat(values).Zip(tableColumns, (column, tableColumn) => new Pair(column, tableColumn)).Any(p => p.First!=p.Second)) { + ea.Add(new ValidationException(Strings.ExInvalidPrimaryKeyStructure, Path), handle: true); + } ea.Complete(); } @@ -81,7 +76,7 @@ protected override Nesting CreateNesting() protected override void Initialize() { base.Initialize(); - if (ValueColumns==null) + if (ValueColumns is null) ValueColumns = new ValueColumnRefCollection(this); } diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/PrimaryKeyColumnRef.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/PrimaryKeyColumnRef.cs index 3ac334747d..2d09829ab1 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/PrimaryKeyColumnRef.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/PrimaryKeyColumnRef.cs @@ -6,7 +6,6 @@ using System; using Xtensive.Core; - using Xtensive.Modelling; namespace Xtensive.Orm.Upgrade.Model @@ -14,7 +13,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// References to key column. /// - [Serializable] public sealed class PrimaryKeyColumnRef : KeyColumnRef { /// diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/PrimaryKeyColumnRefCollection.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/PrimaryKeyColumnRefCollection.cs index 6bf5e37836..883e76c27d 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/PrimaryKeyColumnRefCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/PrimaryKeyColumnRefCollection.cs @@ -12,7 +12,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// A collection of instances. /// - [Serializable] public sealed class PrimaryKeyColumnRefCollection : NodeCollectionBase { // Constructors diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/Ref.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/Ref.cs index 5eb2cdf75e..e0981e7552 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/Ref.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/Ref.cs @@ -16,7 +16,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// The type of the target node. /// The type of the parent node. - [Serializable] public abstract class Ref : NodeBase, IUnnamedNode, INodeReference @@ -32,11 +31,8 @@ public abstract class Ref : NodeBase, [Property(Priority = 0)] public TTarget Value { - get { return value; } - set - { -// if (this.value!=null) -// throw Exceptions.AlreadyInitialized("Value"); + get => value; + set { EnsureIsEditable(); using (var scope = LogPropertyChange("Value", value)) { this.value = value; @@ -47,8 +43,8 @@ public TTarget Value Node INodeReference.Value { - get { return Value; } - set { Value = (TTarget)value; } + get => Value; + set => Value = (TTarget) value; } diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/ReferentialAction.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/ReferentialAction.cs index 8b49c7b821..04f9497231 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/ReferentialAction.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/ReferentialAction.cs @@ -11,7 +11,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// Referential integrity maintenance actions. /// - [Serializable] public enum ReferentialAction { /// diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/SecondaryIndexInfo.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/SecondaryIndexInfo.cs index bc8d1a02f3..16eb29a8f4 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/SecondaryIndexInfo.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/SecondaryIndexInfo.cs @@ -9,14 +9,12 @@ using Xtensive.Core; using Xtensive.Modelling; using Xtensive.Modelling.Attributes; -using Xtensive.Collections; namespace Xtensive.Orm.Upgrade.Model { /// /// Secondary index. /// - [Serializable] public sealed class SecondaryIndexInfo : StorageIndexInfo { private PartialIndexFilterInfo filter; @@ -39,9 +37,8 @@ public sealed class SecondaryIndexInfo : StorageIndexInfo [Property(Priority = -90)] public PartialIndexFilterInfo Filter { - get { return filter; } - set - { + get => filter; + set { EnsureIsEditable(); filter = value; } @@ -56,7 +53,7 @@ public void PopulatePrimaryKeyColumns() if (Parent.PrimaryIndex == null) return; foreach (var kcr in Parent.PrimaryIndex.KeyColumns) - new PrimaryKeyColumnRef(this, kcr.Value, kcr.Direction); + _ = new PrimaryKeyColumnRef(this, kcr.Value, kcr.Direction); } /// @@ -68,32 +65,27 @@ protected override void ValidateState() // Secondary key columns: empty set, duplicates var keyColumns = KeyColumns.Select(valueRef => valueRef.Value).ToArray(KeyColumns.Count); - if (keyColumns.Length==0) - ea.Execute(() => { - throw new ValidationException(Strings.ExEmptyKeyColumnsCollection, Path); - }); + if (keyColumns.Length == 0) { + ea.Add(new ValidationException(Strings.ExEmptyKeyColumnsCollection, Path), handle: true); + } foreach (var group in keyColumns .GroupBy(keyColumn => keyColumn) - .Where(g => g.Count() > 1)) { - ea.Execute((_column) => { - throw new ValidationException( - string.Format(Strings.ExMoreThenOneKeyColumnReferenceToColumnX, _column.Name), - Path); - }, group.Key); + .Where(static g => g.Count() > 1)) { + + ea.Add(new ValidationException(string.Format(Strings.ExMoreThenOneKeyColumnReferenceToColumnX, group.Key.Name), Path), handle: true); } // Primary key columns - if (Parent.PrimaryIndex != null && PrimaryKeyColumns.Count!=Parent.PrimaryIndex.KeyColumns.Count) - ea.Execute(() => { - throw new ValidationException(Strings.ExInvalidPrimaryKeyColumnsCollection, Path); - }); - for (int i = 0; i < PrimaryKeyColumns.Count; i++) { + if (Parent.PrimaryIndex != null && PrimaryKeyColumns.Count != Parent.PrimaryIndex.KeyColumns.Count) { + ea.Add(new ValidationException(Strings.ExInvalidPrimaryKeyColumnsCollection, Path), handle: true); + } + + for (int i = 0, count = PrimaryKeyColumns.Count; i < count; i++) { var ref1 = PrimaryKeyColumns[i]; var ref2 = Parent.PrimaryIndex.KeyColumns[i]; - if (ref1.Value!=ref2.Value || ref1.Direction!=ref2.Direction) - ea.Execute(() => { - throw new ValidationException(Strings.ExInvalidPrimaryKeyColumnsCollection, Path); - }); + if (ref1.Value != ref2.Value || ref1.Direction != ref2.Direction) { + ea.Add(new ValidationException(Strings.ExInvalidPrimaryKeyColumnsCollection, Path), handle: true); + } } // Included columns @@ -103,20 +95,19 @@ protected override void ValidateState() .Concat(PrimaryKeyColumns.Select(cr => cr.Value)) .ToHashSet(); foreach (var columnRef in IncludedColumns) { - if (fullKeySet.Contains(columnRef.Value)) - ea.Execute(() => { - throw new ValidationException(Strings.ExInvalidIncludedColumnsCollection, Path); - }); + if (fullKeySet.Contains(columnRef.Value)) { + ea.Add(new ValidationException(Strings.ExInvalidIncludedColumnsCollection, Path), handle: true); + } } foreach (var group in IncludedColumns .GroupBy(keyColumn => keyColumn) .Where(g => g.Count() > 1)) { - ea.Execute((_column) => { - throw new ValidationException( - string.Format(Strings.ExMoreThenOneIncludedColumnReferenceToColumnX, _column.Name), - Path); - }, group.Key); + + ea.Add( + new ValidationException( + string.Format(Strings.ExMoreThenOneIncludedColumnReferenceToColumnX, group.Key.Name), Path), + handle: true); } ea.Complete(); @@ -133,9 +124,9 @@ protected override Nesting CreateNesting() protected override void Initialize() { base.Initialize(); - if (PrimaryKeyColumns==null) + if (PrimaryKeyColumns is null) PrimaryKeyColumns = new PrimaryKeyColumnRefCollection(this); - if (IncludedColumns==null) + if (IncludedColumns is null) IncludedColumns = new IncludedColumnRefCollection(this); } diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/SecondaryIndexInfoCollection.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/SecondaryIndexInfoCollection.cs index 853661a483..49645e80ad 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/SecondaryIndexInfoCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/SecondaryIndexInfoCollection.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// A collection of secondary indexes. /// - [Serializable] public sealed class SecondaryIndexInfoCollection : NodeCollectionBase, IUnorderedNodeCollection { diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/SequenceInfoCollection.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/SequenceInfoCollection.cs index 33145e64ff..a752e64bad 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/SequenceInfoCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/SequenceInfoCollection.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// The collection of instances. /// - [Serializable] public sealed class SequenceInfoCollection : NodeCollectionBase, IUnorderedNodeCollection { diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageColumnInfo.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageColumnInfo.cs index f87a2bae98..4a982d9025 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageColumnInfo.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageColumnInfo.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// Column. /// - [Serializable] public sealed class StorageColumnInfo : NodeBase { private StorageTypeInfo type; @@ -25,8 +24,9 @@ public sealed class StorageColumnInfo : NodeBase /// Gets or sets the type of the column. /// [Property(Priority = -1000)] - public StorageTypeInfo Type { - get { return type; } + public StorageTypeInfo Type + { + get => type; set { EnsureIsEditable(); using (var scope = LogPropertyChange("Type", value)) { @@ -42,7 +42,7 @@ public StorageTypeInfo Type { [Property(IgnoreInComparison = true)] public object DefaultValue { - get { return defaultValue; } + get => defaultValue; set { EnsureIsEditable(); using (var scope = LogPropertyChange("DefaultValue", value)) { @@ -59,9 +59,8 @@ public object DefaultValue [Property(IgnoreInComparison = true)] public string DefaultSqlExpression { - get { return defaultSqlExpression; } - set - { + get => defaultSqlExpression; + set { EnsureIsEditable(); using (var scope = LogPropertyChange("DefaultSqlExpression", value)) { defaultSqlExpression = value; @@ -76,12 +75,8 @@ protected override void ValidateState() { using (var ea = new ExceptionAggregator()) { ea.Execute(base.ValidateState); - if (Type==null) { - ea.Execute(() => { - throw new ValidationException( - string.Format(Strings.ExUndefinedTypeOfColumnX, Name), - Path); - }); + if (Type is null) { + ea.Add(new ValidationException(string.Format(Strings.ExUndefinedTypeOfColumnX, Name), Path), handle: true); } ea.Complete(); } diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageFullTextIndexInfo.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageFullTextIndexInfo.cs index b683a05b48..4907276fd6 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageFullTextIndexInfo.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageFullTextIndexInfo.cs @@ -16,7 +16,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// Full-text index. /// - [Serializable] public sealed class StorageFullTextIndexInfo : NodeBase { /// @@ -58,14 +57,11 @@ protected override void ValidateState() { using (var ea = new ExceptionAggregator()) { ea.Execute(base.ValidateState); - base.ValidateState(); var tableColumns = Parent.Columns; - if (Columns.Select(keyRef => keyRef.Value).Any()) { - ea.Execute(() => { - throw new ValidationException(Strings.ExEmptyColumnsCollection, Path); - }); + if (!Columns.Select(keyRef => keyRef.Value).Any()) { + ea.Add(new ValidationException(Strings.ExEmptyColumnsCollection, Path), handle: true); } ea.Complete(); diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageIndexInfo.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageIndexInfo.cs index 75bedeaff7..22f87931d4 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageIndexInfo.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageIndexInfo.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// The base abstract class for all indexes. /// - [Serializable] public abstract class StorageIndexInfo : NodeBase { private bool isUnique; diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageModel.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageModel.cs index 88cf149090..e01b1f4a70 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageModel.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageModel.cs @@ -15,7 +15,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// Storage schema. /// - [Serializable] public sealed class StorageModel : NodeBase, IModel { @@ -27,8 +26,9 @@ public sealed class StorageModel : NodeBase, private ActionSequence actions; /// - public ActionSequence Actions { - get { return actions; } + public ActionSequence Actions + { + get => actions; set { EnsureIsEditable(); actions = value; diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageSequenceInfo.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageSequenceInfo.cs index c7a5d059fd..2506abffbd 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageSequenceInfo.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageSequenceInfo.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// Sequence. /// - [Serializable] public sealed class StorageSequenceInfo : NodeBase { private StorageTypeInfo type; @@ -90,19 +89,11 @@ protected override void ValidateState() { using (var ea = new ExceptionAggregator()) { ea.Execute(base.ValidateState); - if (Increment<=0) { - ea.Execute(() => { - throw new ValidationException( - string.Format(Strings.ExInvalideIncrementValue), - Path); - }); + if (Increment <= 0) { + ea.Add(new ValidationException(string.Format(Strings.ExInvalideIncrementValue), Path), handle: true); } - if (Type==null) { - ea.Execute(() => { - throw new ValidationException( - string.Format(string.Format(Strings.ExUndefinedTypeOfSequenceX, Name)), - Path); - }); + if (Type is null) { + ea.Add(new ValidationException(string.Format(string.Format(Strings.ExUndefinedTypeOfSequenceX, Name)), Path), handle: true); } ea.Complete(); } diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageTypeInfo.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageTypeInfo.cs index 661071e5ed..7ea2613962 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageTypeInfo.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/StorageTypeInfo.cs @@ -5,10 +5,7 @@ // Created: 2009.03.24 using System; -using System.Globalization; using Xtensive.Core; - -using System.Text; using Xtensive.Reflection; using Xtensive.Modelling.Validation; using Xtensive.Sql; @@ -18,7 +15,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// Type of table column. /// - [Serializable] public sealed class StorageTypeInfo : IEquatable, IValidatable, ICloneable diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/TableInfo.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/TableInfo.cs index 07beb0e689..2a141b51f9 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/TableInfo.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/TableInfo.cs @@ -14,7 +14,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// Table. /// - [Serializable] public sealed class TableInfo : NodeBase { private PrimaryIndexInfo primaryIndex; @@ -29,8 +28,9 @@ public sealed class TableInfo : NodeBase /// Gets or sets the primary index. /// [Property(Priority = -1200, IsImmutable = true)] - public PrimaryIndexInfo PrimaryIndex { - get { return primaryIndex; } + public PrimaryIndexInfo PrimaryIndex + { + get => primaryIndex; set { EnsureIsEditable(); using (var scope = LogPropertyChange("PrimaryIndex", value)) { @@ -83,7 +83,7 @@ protected override void Initialize() { base.Initialize(); - if (Columns==null) + if (Columns is null) Columns = new ColumnInfoCollection(this); if (SecondaryIndexes == null) SecondaryIndexes = new SecondaryIndexInfoCollection(this); diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/TableInfoCollection.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/TableInfoCollection.cs index dde50c7d98..aac7413c46 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/TableInfoCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/TableInfoCollection.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// A collection of instances. /// - [Serializable] public sealed class TableInfoCollection : NodeCollectionBase, IUnorderedNodeCollection { diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/ValueColumnRef.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/ValueColumnRef.cs index 639ece5bd4..9d7d7041f5 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/ValueColumnRef.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/ValueColumnRef.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// References to value column. /// - [Serializable] public sealed class ValueColumnRef : ColumnInfoRef { /// diff --git a/Orm/Xtensive.Orm/Orm/Upgrade/Model/ValueColumnRefCollection.cs b/Orm/Xtensive.Orm/Orm/Upgrade/Model/ValueColumnRefCollection.cs index 12199ac4b5..3fc4a066bf 100644 --- a/Orm/Xtensive.Orm/Orm/Upgrade/Model/ValueColumnRefCollection.cs +++ b/Orm/Xtensive.Orm/Orm/Upgrade/Model/ValueColumnRefCollection.cs @@ -13,7 +13,6 @@ namespace Xtensive.Orm.Upgrade.Model /// /// A collection of instances. /// - [Serializable] public sealed class ValueColumnRefCollection : NodeCollectionBase, IUnorderedNodeCollection { diff --git a/Orm/Xtensive.Orm/Orm/UrlInfo.cs b/Orm/Xtensive.Orm/Orm/UrlInfo.cs index 82f49b11fa..8e1f1cc43b 100644 --- a/Orm/Xtensive.Orm/Orm/UrlInfo.cs +++ b/Orm/Xtensive.Orm/Orm/UrlInfo.cs @@ -7,10 +7,7 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.ComponentModel; using System.Diagnostics; -using System.Runtime.Serialization; -using System.Security; using System.Text; using System.Text.RegularExpressions; using Xtensive.Core; @@ -67,13 +64,10 @@ namespace Xtensive.Orm /// /// /// - [Serializable] [DebuggerDisplay("{url}")] - [TypeConverter(typeof(UrlInfoConverter))] - public class UrlInfo : + public class UrlInfo : IEquatable, - IComparable, - ISerializable + IComparable { private static readonly Regex Pattern = new Regex( @"^(?'proto'[^:]*[^sS])(?'secure'[sS]?)://" + @@ -95,6 +89,8 @@ public class UrlInfo : private string password = string.Empty; private ReadOnlyDictionary parameters; + private bool isReady = false; + #region Properties: Url, Protocol, Host, etc... /// @@ -103,7 +99,7 @@ public class UrlInfo : public string Url { [DebuggerStepThrough] - get { return url; } + get => url; } /// @@ -113,7 +109,12 @@ public string Url public string Protocol { [DebuggerStepThrough] - get { return protocol; } + get { + if (!isReady) { + Parse(url, this); + } + return protocol; + } } /// @@ -123,7 +124,12 @@ public string Protocol public bool Secure { [DebuggerStepThrough] - get => secure; + get { + if (!isReady) { + Parse(url, this); + } + return secure; + } } /// @@ -133,7 +139,12 @@ public bool Secure public string Host { [DebuggerStepThrough] - get { return host; } + get { + if (!isReady) { + Parse(url, this); + } + return host; + } } /// @@ -143,7 +154,12 @@ public string Host public int Port { [DebuggerStepThrough] - get { return port; } + get { + if (!isReady) { + Parse(url, this); + } + return port; + } } /// @@ -153,7 +169,12 @@ public int Port public string Resource { [DebuggerStepThrough] - get { return resource; } + get { + if (!isReady) { + Parse(url, this); + } + return resource; + } } /// @@ -163,7 +184,12 @@ public string Resource public string User { [DebuggerStepThrough] - get { return user; } + get { + if (!isReady) { + Parse(url, this); + } + return user; + } } /// @@ -173,7 +199,12 @@ public string User public string Password { [DebuggerStepThrough] - get { return password; } + get { + if (!isReady) { + Parse(url, this); + } + return password; + } } /// @@ -188,7 +219,12 @@ public string Password public IReadOnlyDictionary Params { [DebuggerStepThrough] - get { return parameters; } + get { + if (!isReady) { + Parse(url, this); + } + return parameters; + } } #endregion @@ -250,6 +286,7 @@ private static void Parse(string url, UrlInfo info) info.secure = !string.IsNullOrEmpty(result.Result("${secure}")); info.port = @port; info.parameters = new ReadOnlyDictionary(@params); + info.isReady = true; } catch (Exception e) { if (e is ArgumentException || e is InvalidOperationException) @@ -264,10 +301,10 @@ private static void Parse(string url, UrlInfo info) private class UrlDecoder { // Fields - private int m_bufferSize; + private readonly int m_bufferSize; + private readonly char[] m_charBuffer; + private readonly Encoding m_encoding; private byte[] m_byteBuffer; - private char[] m_charBuffer; - private Encoding m_encoding; private int m_numBytes; private int m_numChars; @@ -441,35 +478,8 @@ public override string ToString() // Constructors - private UrlInfo() { } - - #region ISerializable members, deserializing constructor - - /// - /// Deserilizing constructor. - /// - /// The source (see ) for this deserialization. - /// The to populate the data from. - protected UrlInfo(SerializationInfo info, StreamingContext context) - { - Parse(info.GetString("Url"), this); - } - - /// - /// Populates a with the data needed to serialize the target object. - /// - /// The destination (see ) for this serialization. - /// The to populate with data. - /// The caller does not have the required permission. - [SecurityCritical] - public virtual void GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue("Url", url); - } - - #endregion } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/Validation/Exceptions/ValidationFailedException.cs b/Orm/Xtensive.Orm/Orm/Validation/Exceptions/ValidationFailedException.cs index 929acc3d74..8db540549c 100644 --- a/Orm/Xtensive.Orm/Orm/Validation/Exceptions/ValidationFailedException.cs +++ b/Orm/Xtensive.Orm/Orm/Validation/Exceptions/ValidationFailedException.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Runtime.Serialization; using Xtensive.Core; namespace Xtensive.Orm.Validation @@ -8,10 +7,8 @@ namespace Xtensive.Orm.Validation /// /// Validation failure error. /// - [Serializable] - public class ValidationFailedException : StorageException + public sealed class ValidationFailedException : StorageException { - [NonSerialized] private IList validationErrors; /// @@ -46,18 +43,5 @@ public ValidationFailedException(string message, Exception inner) : base(message, inner) { } - - /// - /// Performs deserialization. - /// - /// Serialization info. - /// Streaming context. -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - protected ValidationFailedException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Orm/VersionInfo.cs b/Orm/Xtensive.Orm/Orm/VersionInfo.cs index 68c0c120ed..c2233b5adf 100644 --- a/Orm/Xtensive.Orm/Orm/VersionInfo.cs +++ b/Orm/Xtensive.Orm/Orm/VersionInfo.cs @@ -5,13 +5,10 @@ // Created: 2009.08.13 using System; -using System.Collections; using System.Diagnostics; using Xtensive.Core; - using Xtensive.Tuples; using Tuple = Xtensive.Tuples.Tuple; -using System.Runtime.Serialization; namespace Xtensive.Orm { @@ -19,36 +16,32 @@ namespace Xtensive.Orm /// Contains information about entity version. /// [DebuggerDisplay("{Value}")] - [Serializable] public struct VersionInfo : IEquatable { private static VersionInfo @void = default; private readonly Tuple value; - [NonSerialized] private int cachedHashCode; /// /// Gets the void object. /// - public static VersionInfo Void { - get { return @void; } - } + public static VersionInfo Void => @void; /// /// Gets a value indicating whether this instance is not contains version. /// - public bool IsVoid { + public bool IsVoid + { [DebuggerStepThrough] - get { return Value==null; } + get => Value is null; } - internal Tuple Value { + internal Tuple Value + { [DebuggerStepThrough] - get { - return value; - } + get => value; } /// @@ -62,7 +55,7 @@ internal VersionInfo Concat(Key key, VersionInfo versionInfo) ArgumentNullException.ThrowIfNull(key); Tuple resultVersion = Value; - if (resultVersion==null) + if (resultVersion is null) resultVersion = key.Value; else resultVersion = resultVersion.Concat(key.Value); @@ -88,16 +81,16 @@ public bool ConflictsWith(VersionInfo other) var tuple = Value; var otherTuple = other.Value; - if (tuple==null) { - if (otherTuple==null) + if (tuple is null) { + if (otherTuple is null) return false; else return true; } - else if (otherTuple==null) + else if (otherTuple is null) return true; - if (tuple.Count!=otherTuple.Count) + if (tuple.Count != otherTuple.Count) return true; int count = tuple.Count; diff --git a/Orm/Xtensive.Orm/Orm/VersionSet.cs b/Orm/Xtensive.Orm/Orm/VersionSet.cs index 973d20c3dc..cc3d3eebc2 100644 --- a/Orm/Xtensive.Orm/Orm/VersionSet.cs +++ b/Orm/Xtensive.Orm/Orm/VersionSet.cs @@ -16,26 +16,18 @@ namespace Xtensive.Orm /// /// Describes a set of key-version pairs used to validate versions. /// - [Serializable] public sealed class VersionSet : IEnumerable> { - private Dictionary, VersionInfo> versions = - new Dictionary, VersionInfo>(); + private readonly Dictionary, VersionInfo> versions = new(); /// - public long Count { - get { return versions.Count; } - } + public long Count => versions.Count; /// /// Gets the by the specified key. /// If there is no such , it returns . /// - public VersionInfo this[Key key] { - get { - return Get(key); - } - } + public VersionInfo this[Key key] => Get(key); /// /// Gets the for the specified @@ -45,10 +37,7 @@ public VersionInfo this[Key key] { /// The entity to get associated for. /// Associated , if found; /// otherwise, . - public VersionInfo Get(Entity entity) - { - return Get(entity!=null ? entity.Key : null); - } + public VersionInfo Get(Entity entity) => Get(entity is not null ? entity.Key : null); /// /// Gets the by the specified key. @@ -57,38 +46,22 @@ public VersionInfo Get(Entity entity) /// The key to get associated for. /// Associated , if found; /// otherwise, . - public VersionInfo Get(Key key) - { - VersionInfo result; - if (versions.TryGetValue(key, out result)) - return result; - else - return VersionInfo.Void; - } + public VersionInfo Get(Key key) => + versions.TryGetValue(key, out var result) ? result : VersionInfo.Void; /// /// Determines whether this set contains the key of the specified entity. /// /// The entity to check the key for containment. /// Check result. - public bool Contains(Entity entity) - { - if (entity==null) - return false; - return Contains(entity.Key); - } + public bool Contains(Entity entity) => entity is not null && versions.ContainsKey(entity.Key); /// /// Determines whether this set contains the specified key. /// /// The key to check for containment. /// Check result. - public bool Contains(Key key) - { - if (key==null) - return false; - return versions.ContainsKey(key); - } + public bool Contains(Key key) => key is not null && versions.ContainsKey(key); #region Validate methods @@ -209,7 +182,7 @@ public bool Add(Key key, VersionInfo version, bool overwrite) } else if (overwrite) { if (version.IsVoid) - versions.Remove(key); + _ = versions.Remove(key); else versions[key] = version; return true; diff --git a/Orm/Xtensive.Orm/Reflection/InterfaceMapping.cs b/Orm/Xtensive.Orm/Reflection/InterfaceMapping.cs index cf161f4969..1c98b4207f 100644 --- a/Orm/Xtensive.Orm/Reflection/InterfaceMapping.cs +++ b/Orm/Xtensive.Orm/Reflection/InterfaceMapping.cs @@ -16,28 +16,27 @@ namespace Xtensive.Reflection /// /// Faster analogue. /// - [Serializable] public readonly struct InterfaceMapping { /// /// Gets the target type of this mapping. /// - public Type TargetType { get; } + public readonly Type TargetType; /// /// Gets the interface type of this mapping. /// - public Type InterfaceType { get; } + public readonly Type InterfaceType; /// /// Gets the type members of this mapping. /// - public IReadOnlyList TargetMethods { get; } + public readonly IReadOnlyList TargetMethods; /// /// Gets the interface members of this mapping. /// - public IReadOnlyList InterfaceMethods { get; } + public readonly IReadOnlyList InterfaceMethods; // Constructors diff --git a/Orm/Xtensive.Orm/Reflection/TypeHelper.cs b/Orm/Xtensive.Orm/Reflection/TypeHelper.cs index bba78bf9b7..b188289d13 100644 --- a/Orm/Xtensive.Orm/Reflection/TypeHelper.cs +++ b/Orm/Xtensive.Orm/Reflection/TypeHelper.cs @@ -390,6 +390,29 @@ private static T CreateAssociateInternal(Type originalForType, foundForType = currentForType; return result; } + + // Trying to find non-generic variation of array converters + // e.g for byte[] search for ByteArrayAdvancedConverter instead of ArrayAdvancedConverter`1 by generics + if (currentForType.IsArray && genericArguments.Length == 1) { + var itemType = genericArguments[0]; + if (itemType.IsPrimitive || (itemType.IsValueType && !itemType.IsGenericType)) { + var nonGenericArrayName = $"{itemType.Name}Array"; + associateTypeName = AddSuffix($"{location.Second}.{nonGenericArrayName}", associateTypeSuffix); + suffix = CorrectGenericSuffix(associateTypeName, 0); + if (Activate(location.First, suffix, null, constructorParams) is T result1) { + foundForType = currentForType; + return result1; + } + nonGenericArrayName = $"ArrayOf{itemType.Name}"; + associateTypeName = AddSuffix($"{location.Second}.{nonGenericArrayName}", associateTypeSuffix); + suffix = CorrectGenericSuffix(associateTypeName, 0); + if (Activate(location.First, suffix, null, constructorParams) is T result2) { + foundForType = currentForType; + return result2; + } + + } + } } } diff --git a/Orm/Xtensive.Orm/Sorting/ConnectionType.cs b/Orm/Xtensive.Orm/Sorting/ConnectionType.cs index 9eb8912c40..16ee5f00cd 100644 --- a/Orm/Xtensive.Orm/Sorting/ConnectionType.cs +++ b/Orm/Xtensive.Orm/Sorting/ConnectionType.cs @@ -11,7 +11,6 @@ namespace Xtensive.Sorting /// /// Type of connection. /// - [Serializable] public enum ConnectionType { /// diff --git a/Orm/Xtensive.Orm/Sorting/Node.cs b/Orm/Xtensive.Orm/Sorting/Node.cs index 5158f3ac41..29f25638a9 100644 --- a/Orm/Xtensive.Orm/Sorting/Node.cs +++ b/Orm/Xtensive.Orm/Sorting/Node.cs @@ -18,7 +18,6 @@ namespace Xtensive.Sorting /// /// Type of node item. /// Type of connection item. - [Serializable] public class Node { private List> incomingConnections; @@ -56,12 +55,12 @@ public IReadOnlyList> OutgoingConnect /// /// Gets count of outgoing connections. /// - public int OutgoingConnectionCount { get{ return outgoingConnections==null ? 0 : outgoingConnections.Count;} } + public int OutgoingConnectionCount => outgoingConnections is null ? 0 : outgoingConnections.Count; /// /// Gets count of breakable outgoing connections. /// - public int BreakableOutgoingConnectionCount { get{ return outgoingConnections==null ? 0 : outgoingConnections.Count - PermanentOutgoingConnectionCount;} } + public int BreakableOutgoingConnectionCount => outgoingConnections is null ? 0 : outgoingConnections.Count - PermanentOutgoingConnectionCount; /// /// Gets count of permanent outgoing connections. @@ -71,12 +70,12 @@ public IReadOnlyList> OutgoingConnect /// /// Gets count of breakable incoming connections. /// - public int BreakableIncomingConnectionCount { get{ return incomingConnections==null ? 0 : incomingConnections.Count - PermanentIncomingConnectionCount;} } + public int BreakableIncomingConnectionCount => incomingConnections is null ? 0 : incomingConnections.Count - PermanentIncomingConnectionCount; /// /// Gets count of breakable incoming connections. /// - public int IncomingConnectionCount { get{ return incomingConnections==null ? 0 : incomingConnections.Count;} } + public int IncomingConnectionCount { get{ return incomingConnections is null ? 0 : incomingConnections.Count;} } /// /// Gets count of permanent incoming connections. @@ -101,8 +100,8 @@ internal void AddIncomingConnection(NodeConnection c internal void RemoveOutgoingConnection(NodeConnection connection) { - if (outgoingConnections!=null) { - outgoingConnections.Remove(connection); + if (outgoingConnections is not null) { + _ = outgoingConnections.Remove(connection); if (connection.ConnectionType==ConnectionType.Permanent) PermanentOutgoingConnectionCount --; } @@ -110,8 +109,8 @@ internal void RemoveOutgoingConnection(NodeConnection connection) { - if (incomingConnections!=null) { - incomingConnections.Remove(connection); + if (incomingConnections is not null) { + _ = incomingConnections.Remove(connection); if (connection.ConnectionType==ConnectionType.Permanent) PermanentIncomingConnectionCount --; } @@ -150,7 +149,7 @@ public NodeConnection AddConnection(Node> RemoveConnections(Node destination) { ArgumentNullException.ThrowIfNull(destination); - if (outgoingConnections==null) + if (outgoingConnections is null) return Enumerable.Empty>(); var nodesToRemove = outgoingConnections.Where(connection => connection.Destination==destination).ToList(); @@ -163,7 +162,7 @@ public IEnumerable> RemoveConnections private void EnsureIncomingConnections() { - if (incomingConnectionsReadOnlyList==null) { + if (incomingConnectionsReadOnlyList is null) { incomingConnections = new List>(); incomingConnectionsReadOnlyList = incomingConnections.AsReadOnly(); } @@ -171,7 +170,7 @@ private void EnsureIncomingConnections() private void EnsureOutgoingConnections() { - if (outgoingConnectionsReadOnlyList==null) { + if (outgoingConnectionsReadOnlyList is null) { outgoingConnections = new List>(); outgoingConnectionsReadOnlyList = outgoingConnections.AsReadOnly(); } diff --git a/Orm/Xtensive.Orm/Sorting/NodeConnection.cs b/Orm/Xtensive.Orm/Sorting/NodeConnection.cs index e362bd84f3..eab4ee5361 100644 --- a/Orm/Xtensive.Orm/Sorting/NodeConnection.cs +++ b/Orm/Xtensive.Orm/Sorting/NodeConnection.cs @@ -15,7 +15,6 @@ namespace Xtensive.Sorting /// /// Type of node item. /// Type of connection item. - [Serializable] public class NodeConnection { /// diff --git a/Orm/Xtensive.Orm/Sorting/TopologicalSortResult{TNodeItem, TConnectionItem}.cs b/Orm/Xtensive.Orm/Sorting/TopologicalSortResult{TNodeItem, TConnectionItem}.cs index 845fbbe7f6..768c0ec3d8 100644 --- a/Orm/Xtensive.Orm/Sorting/TopologicalSortResult{TNodeItem, TConnectionItem}.cs +++ b/Orm/Xtensive.Orm/Sorting/TopologicalSortResult{TNodeItem, TConnectionItem}.cs @@ -16,7 +16,6 @@ namespace Xtensive.Sorting /// /// The type of the node item. /// The type of the connection item. - [Serializable] public class TopologicalSortResult : TopologicalSortResult { /// diff --git a/Orm/Xtensive.Orm/Sorting/TopologicalSortResult{TNodeItem}.cs b/Orm/Xtensive.Orm/Sorting/TopologicalSortResult{TNodeItem}.cs index b63a181d28..62bb5a4976 100644 --- a/Orm/Xtensive.Orm/Sorting/TopologicalSortResult{TNodeItem}.cs +++ b/Orm/Xtensive.Orm/Sorting/TopologicalSortResult{TNodeItem}.cs @@ -14,7 +14,6 @@ namespace Xtensive.Sorting /// Base type for . /// /// The type of the node item. - [Serializable] public class TopologicalSortResult { /// diff --git a/Orm/Xtensive.Orm/Sql/Compiler/SqlCompilerException.cs b/Orm/Xtensive.Orm/Sql/Compiler/SqlCompilerException.cs index 5beadfb401..2ac93fc0b8 100644 --- a/Orm/Xtensive.Orm/Sql/Compiler/SqlCompilerException.cs +++ b/Orm/Xtensive.Orm/Sql/Compiler/SqlCompilerException.cs @@ -3,7 +3,6 @@ // For conditions of distribution and use, see license. using System; -using System.Runtime.Serialization; namespace Xtensive.Sql.Compiler @@ -11,31 +10,11 @@ namespace Xtensive.Sql.Compiler /// /// An exception. /// - [Serializable] - public class SqlCompilerException : Exception + /// + /// Initializes new instance of this type. + /// + /// The message. + public class SqlCompilerException(string message) : Exception(message) { - /// - /// Initializes new instance of this type. - /// - /// The message. - public SqlCompilerException(string message) - : base(message) - { - } - - // Serialization - - /// - /// Deserializes instance of this type. - /// - /// - /// -#if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] -#endif - protected SqlCompilerException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Sql/Compiler/SqlCompilerNamingScope.cs b/Orm/Xtensive.Orm/Sql/Compiler/SqlCompilerNamingScope.cs index 62f20089c5..f3ae1f8580 100644 --- a/Orm/Xtensive.Orm/Sql/Compiler/SqlCompilerNamingScope.cs +++ b/Orm/Xtensive.Orm/Sql/Compiler/SqlCompilerNamingScope.cs @@ -11,12 +11,11 @@ namespace Xtensive.Sql.Compiler /// /// SQL compiler naming scope. /// - [Serializable] public class SqlCompilerNamingScope : IDisposable { private readonly SqlCompilerContext context; - internal SqlCompilerNamingOptions ParentOptions { get; private set; } + internal SqlCompilerNamingOptions ParentOptions { get; } /// public void Dispose() diff --git a/Orm/Xtensive.Orm/Sql/Compiler/SqlParameterNameProvider.cs b/Orm/Xtensive.Orm/Sql/Compiler/SqlParameterNameProvider.cs index f3b814e70a..4622e0b6c7 100644 --- a/Orm/Xtensive.Orm/Sql/Compiler/SqlParameterNameProvider.cs +++ b/Orm/Xtensive.Orm/Sql/Compiler/SqlParameterNameProvider.cs @@ -12,14 +12,13 @@ namespace Xtensive.Sql.Compiler /// /// SQL parameter name provider. /// - [Serializable] public class SqlParameterNameProvider { private const string DefaultPrefix = "p"; - private int nextParameter; private readonly string prefix; - - internal Dictionary NameTable { get; private set; } + private int nextParameter; + + internal Dictionary NameTable { get; } /// /// Gets the name for the specified . @@ -28,8 +27,7 @@ public class SqlParameterNameProvider /// Name for the specified parameter. public string GetName(object parameter) { - string result; - if (!NameTable.TryGetValue(parameter, out result)) { + if (!NameTable.TryGetValue(parameter, out var result)) { result = prefix + nextParameter++; NameTable.Add(parameter, result); } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlAction.cs b/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlAction.cs index 4d14e86679..4fe860c47d 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlAction.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlAction.cs @@ -6,7 +6,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public abstract class SqlAction : SqlNode { public override void AcceptVisitor(ISqlVisitor visitor) diff --git a/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlAddColumn.cs b/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlAddColumn.cs index f5d1e3eda0..2be237b864 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlAddColumn.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlAddColumn.cs @@ -7,10 +7,9 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlAddColumn : SqlAction { - public TableColumn Column { get; private set; } + public TableColumn Column { get; } internal override SqlAddColumn Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => diff --git a/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlAddConstraint.cs b/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlAddConstraint.cs index 973acbd559..7bb34b3e52 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlAddConstraint.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlAddConstraint.cs @@ -7,10 +7,9 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlAddConstraint : SqlAction { - public Constraint Constraint { get; private set; } + public Constraint Constraint { get; } internal override SqlAddConstraint Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => diff --git a/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlAlterIdentityInfo.cs b/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlAlterIdentityInfo.cs index a7f7db158b..a90c525bc1 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlAlterIdentityInfo.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlAlterIdentityInfo.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlAlterIdentityInfo : SqlAction { public TableColumn Column { get; private set; } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlCascadableAction.cs b/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlCascadableAction.cs index 006b6aa884..3cb761359a 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlCascadableAction.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlCascadableAction.cs @@ -8,10 +8,9 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public abstract class SqlCascadableAction : SqlAction { - public bool Cascade { get; private set; } + public bool Cascade { get; } // Constructors diff --git a/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlDropColumn.cs b/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlDropColumn.cs index d038de2899..2621ac9299 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlDropColumn.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlDropColumn.cs @@ -7,10 +7,9 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlDropColumn : SqlCascadableAction { - public TableColumn Column { get; private set; } + public TableColumn Column { get; } internal override SqlDropColumn Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => diff --git a/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlDropConstraint.cs b/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlDropConstraint.cs index 8ebe342c92..ee20d86a14 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlDropConstraint.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlDropConstraint.cs @@ -7,11 +7,10 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlDropConstraint : SqlCascadableAction { - public Constraint Constraint { get; private set; } - + public Constraint Constraint { get; } + internal override SqlDropConstraint Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => new SqlDropConstraint(t.Constraint, t.Cascade)); diff --git a/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlDropDefault.cs b/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlDropDefault.cs index bb3cfa5c44..ae3ef04c94 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlDropDefault.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlDropDefault.cs @@ -7,10 +7,9 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlDropDefault : SqlAction { - public TableColumn Column { get; private set; } + public TableColumn Column { get; } internal override SqlDropDefault Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => diff --git a/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlRenameColumn.cs b/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlRenameColumn.cs index 34f2f4717e..8b5a09e0c7 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlRenameColumn.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlRenameColumn.cs @@ -9,11 +9,10 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlRenameColumn : SqlAction { - public TableColumn Column { get; private set; } - public string NewName { get; private set; } + public TableColumn Column { get; } + public string NewName { get; } internal override SqlRenameColumn Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => diff --git a/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlSetDefault.cs b/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlSetDefault.cs index 7e0029a438..fd565469f8 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlSetDefault.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/Actions/SqlSetDefault.cs @@ -8,11 +8,10 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlSetDefault : SqlAction { - public TableColumn Column { get; private set; } - public SqlExpression DefaultValue { get; private set; } + public TableColumn Column { get; } + public SqlExpression DefaultValue { get; } internal override SqlSetDefault Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => diff --git a/Orm/Xtensive.Orm/Sql/Ddl/Misc/SqlAlterIdentityInfoOptions.cs b/Orm/Xtensive.Orm/Sql/Ddl/Misc/SqlAlterIdentityInfoOptions.cs index f15147d49e..44a1fa0620 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/Misc/SqlAlterIdentityInfoOptions.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/Misc/SqlAlterIdentityInfoOptions.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Ddl { [Flags] - [Serializable] public enum SqlAlterIdentityInfoOptions { None = 0x0, diff --git a/Orm/Xtensive.Orm/Sql/Ddl/Misc/SqlAlterPartitionFunctionOption.cs b/Orm/Xtensive.Orm/Sql/Ddl/Misc/SqlAlterPartitionFunctionOption.cs index 309a3da986..7499ce2259 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/Misc/SqlAlterPartitionFunctionOption.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/Misc/SqlAlterPartitionFunctionOption.cs @@ -6,7 +6,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public enum SqlAlterPartitionFunctionOption { Split = 1, diff --git a/Orm/Xtensive.Orm/Sql/Ddl/Misc/SqlCommandType.cs b/Orm/Xtensive.Orm/Sql/Ddl/Misc/SqlCommandType.cs index 39fc8462a9..81ed2ed445 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/Misc/SqlCommandType.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/Misc/SqlCommandType.cs @@ -8,7 +8,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public enum SqlCommandType { SetConstraintsAllDeferred, diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlAlterDomain.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlAlterDomain.cs index 5d5b2bbe3a..6a3c3adeaa 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlAlterDomain.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlAlterDomain.cs @@ -7,27 +7,15 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlAlterDomain : SqlStatement, ISqlCompileUnit { - private SqlAction action; - private Domain domain; + public SqlAction Action { get; } - public SqlAction Action { - get { - return action; - } - } - - public Domain Domain { - get { - return domain; - } - } + public Domain Domain { get; } internal override SqlAlterDomain Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => - new SqlAlterDomain(t.domain, (SqlAction)t.action.Clone(c))); + new SqlAlterDomain(t.Domain, (SqlAction)t.Action.Clone(c))); public override void AcceptVisitor(ISqlVisitor visitor) { @@ -37,8 +25,8 @@ public override void AcceptVisitor(ISqlVisitor visitor) internal SqlAlterDomain(Domain domain, SqlAction action) : base(SqlNodeType.Alter) { - this.action = action; - this.domain = domain; + Action = action; + Domain = domain; } } } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlAlterPartitionFunction.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlAlterPartitionFunction.cs index a1230c958b..e6aec6dad9 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlAlterPartitionFunction.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlAlterPartitionFunction.cs @@ -7,33 +7,20 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlAlterPartitionFunction: SqlStatement, ISqlCompileUnit { - private PartitionFunction partitionFunction; - private string boundary; private SqlAlterPartitionFunctionOption option; - public PartitionFunction PartitionFunction - { - get { return partitionFunction; } - } + public PartitionFunction PartitionFunction { get; } - public string Boundary - { - get { return boundary; } - } + public string Boundary { get; } - public SqlAlterPartitionFunctionOption Option - { - get { return option; } - set { option = value; } - } + public SqlAlterPartitionFunctionOption Option { get; } internal override SqlAlterPartitionFunction Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => - new SqlAlterPartitionFunction(t.partitionFunction, t.boundary, t.option)); + new SqlAlterPartitionFunction(t.PartitionFunction, t.Boundary, t.option)); public override void AcceptVisitor(ISqlVisitor visitor) { @@ -44,8 +31,8 @@ internal SqlAlterPartitionFunction( PartitionFunction partitionFunction, string boundary, SqlAlterPartitionFunctionOption option) : base(SqlNodeType.Alter) { - this.partitionFunction = partitionFunction; - this.boundary = boundary; + PartitionFunction = partitionFunction; + Boundary = boundary; this.option = option; } } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlAlterPartitionScheme.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlAlterPartitionScheme.cs index 932ac7655b..33bd09d6b3 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlAlterPartitionScheme.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlAlterPartitionScheme.cs @@ -7,19 +7,15 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlAlterPartitionScheme : SqlStatement, ISqlCompileUnit { - private readonly PartitionSchema partitionSchema; - private readonly string filegroup; + public PartitionSchema PartitionSchema { get; } - public PartitionSchema PartitionSchema => partitionSchema; - - public string Filegroup => filegroup; + public string Filegroup { get; } internal override SqlAlterPartitionScheme Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => - new SqlAlterPartitionScheme(t.partitionSchema, t.filegroup)); + new SqlAlterPartitionScheme(t.PartitionSchema, t.Filegroup)); public override void AcceptVisitor(ISqlVisitor visitor) { @@ -29,8 +25,8 @@ public override void AcceptVisitor(ISqlVisitor visitor) internal SqlAlterPartitionScheme(PartitionSchema partitionSchema, string filegroup) : base(SqlNodeType.Alter) { - this.partitionSchema = partitionSchema; - this.filegroup = filegroup; + PartitionSchema = partitionSchema; + Filegroup = filegroup; } } } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlAlterSequence.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlAlterSequence.cs index ce3fc9cd4c..89c3ad99dd 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlAlterSequence.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlAlterSequence.cs @@ -7,26 +7,17 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlAlterSequence : SqlStatement, ISqlCompileUnit { - private readonly Sequence sequence; - private readonly SequenceDescriptor sequenceDescriptor; - private SqlAlterIdentityInfoOptions infoOption = SqlAlterIdentityInfoOptions.All; + public Sequence Sequence { get; } - public Sequence Sequence => sequence; + public SequenceDescriptor SequenceDescriptor { get; } - public SequenceDescriptor SequenceDescriptor => sequenceDescriptor; - - public SqlAlterIdentityInfoOptions InfoOption - { - get => infoOption; - set => infoOption = value; - } + public SqlAlterIdentityInfoOptions InfoOption { get; } internal override SqlAlterSequence Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => - new SqlAlterSequence(t.sequence, t.sequenceDescriptor.Clone(), t.infoOption)); + new SqlAlterSequence(t.Sequence, (SequenceDescriptor)t.SequenceDescriptor.Clone(), t.InfoOption)); public override void AcceptVisitor(ISqlVisitor visitor) { @@ -36,9 +27,9 @@ public override void AcceptVisitor(ISqlVisitor visitor) internal SqlAlterSequence(Sequence sequence, SequenceDescriptor sequenceDescriptor, SqlAlterIdentityInfoOptions infoOption) : base(SqlNodeType.Alter) { - this.sequence = sequence; - this.sequenceDescriptor = sequenceDescriptor; - this.infoOption = infoOption; + Sequence = sequence; + SequenceDescriptor = sequenceDescriptor; + InfoOption = infoOption; } } } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlAlterTable.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlAlterTable.cs index a94cbff113..ece1988833 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlAlterTable.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlAlterTable.cs @@ -7,20 +7,16 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlAlterTable : SqlStatement, ISqlCompileUnit { - private readonly SqlAction action; - private readonly Table table; + public SqlAction Action { get; } - public SqlAction Action => action; - - public Table Table => table; + public Table Table { get; } internal override SqlAlterTable Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => - new SqlAlterTable(t.table, (SqlAction)t.action.Clone(c))); + new SqlAlterTable(t.Table, (SqlAction)t.Action.Clone(c))); public override void AcceptVisitor(ISqlVisitor visitor) { @@ -30,8 +26,8 @@ public override void AcceptVisitor(ISqlVisitor visitor) internal SqlAlterTable(Table table, SqlAction action) : base(SqlNodeType.Alter) { - this.action = action; - this.table = table; + Action = action; + Table = table; } } } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlCommand.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlCommand.cs index 4223534383..2c04071aa1 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlCommand.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlCommand.cs @@ -8,10 +8,9 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlCommand : SqlStatement, ISqlCompileUnit { - public SqlCommandType CommandType { get; private set; } + public SqlCommandType CommandType { get; } internal override SqlCommand Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateAssertion.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateAssertion.cs index 85c82b3064..f7b6fc9359 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateAssertion.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateAssertion.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlCreateAssertion : SqlStatement, ISqlCompileUnit { public Assertion Assertion { get; } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateCharcterSet.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateCharcterSet.cs index 85e9a13060..764feaa3e3 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateCharcterSet.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateCharcterSet.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlCreateCharacterSet : SqlStatement, ISqlCompileUnit { public CharacterSet CharacterSet { get; } @@ -23,7 +22,7 @@ public override void AcceptVisitor(ISqlVisitor visitor) internal SqlCreateCharacterSet(CharacterSet characterSet) : base(SqlNodeType.Create) { - this.CharacterSet = characterSet; + CharacterSet = characterSet; } } } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateCollation.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateCollation.cs index b218dc9c92..3ff6bd0087 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateCollation.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateCollation.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlCreateCollation : SqlStatement, ISqlCompileUnit { public Collation Collation { get; } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateDomain.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateDomain.cs index fb53644ee6..8761e35183 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateDomain.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateDomain.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlCreateDomain : SqlStatement, ISqlCompileUnit { public Domain Domain { get; } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateIndex.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateIndex.cs index 28c3e3a395..f049061ba3 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateIndex.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateIndex.cs @@ -8,7 +8,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlCreateIndex : SqlStatement, ISqlCompileUnit { public Index Index { get; } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreatePartitionFunction.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreatePartitionFunction.cs index 554a6a2109..983dc5d0b2 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreatePartitionFunction.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreatePartitionFunction.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlCreatePartitionFunction : SqlStatement, ISqlCompileUnit { public PartitionFunction PartitionFunction { get; } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreatePartitionScheme.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreatePartitionScheme.cs index 271a40f468..b60be2de54 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreatePartitionScheme.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreatePartitionScheme.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlCreatePartitionScheme : SqlStatement, ISqlCompileUnit { public PartitionSchema PartitionSchema { get; } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateSchema.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateSchema.cs index 80d42b42b2..797097f7c4 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateSchema.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateSchema.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlCreateSchema : SqlStatement, ISqlCompileUnit { public Schema Schema { get; } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateSequence.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateSequence.cs index ca9275c02e..2d721d292c 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateSequence.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateSequence.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlCreateSequence : SqlStatement, ISqlCompileUnit { public Sequence Sequence { get; } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateTable.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateTable.cs index 966967a9dc..f3d0c65eec 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateTable.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateTable.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlCreateTable : SqlStatement, ISqlCompileUnit { public Table Table { get; } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateTranslation.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateTranslation.cs index b3fb5ac938..24b7397baf 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateTranslation.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateTranslation.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlCreateTranslation : SqlStatement, ISqlCompileUnit { public Translation Translation { get; } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateView.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateView.cs index 9ecead7958..b8f9c01374 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateView.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlCreateView.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlCreateView : SqlStatement, ISqlCompileUnit { public View View { get; } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropAssertion.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropAssertion.cs index c4b4e0d4ce..caf51f4f00 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropAssertion.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropAssertion.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlDropAssertion : SqlStatement, ISqlCompileUnit { public Assertion Assertion { get; } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropCharacterSet.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropCharacterSet.cs index 99ccac1535..5891f8cf70 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropCharacterSet.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropCharacterSet.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlDropCharacterSet : SqlStatement, ISqlCompileUnit { public CharacterSet CharacterSet { get; } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropCollation.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropCollation.cs index 54849d394d..3c22d11293 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropCollation.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropCollation.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlDropCollation : SqlStatement, ISqlCompileUnit { public Collation Collation { get; } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropDomain.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropDomain.cs index 5c553937e4..01ba5fec07 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropDomain.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropDomain.cs @@ -7,30 +7,15 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlDropDomain : SqlStatement, ISqlCompileUnit { - private Domain domain; - private bool cascade = true; + public Domain Domain { get; } - public Domain Domain { - get { - return domain; - } - } - - public bool Cascade { - get { - return cascade; - } - set { - cascade = value; - } - } + public bool Cascade { get; set; } = true; internal override SqlDropDomain Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => - new SqlDropDomain(t.domain)); + new SqlDropDomain(t.Domain)); public override void AcceptVisitor(ISqlVisitor visitor) { @@ -39,13 +24,13 @@ public override void AcceptVisitor(ISqlVisitor visitor) internal SqlDropDomain(Domain domain) : base(SqlNodeType.Drop) { - this.domain = domain; + Domain = domain; } internal SqlDropDomain(Domain domain, bool cascade) : base(SqlNodeType.Drop) { - this.domain = domain; - this.cascade = cascade; + Domain = domain; + Cascade = cascade; } } } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropIndex.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropIndex.cs index a151c43f8b..1d8a87b2b4 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropIndex.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropIndex.cs @@ -8,7 +8,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlDropIndex : SqlStatement, ISqlCompileUnit { //private bool? online; diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropPartitionFunction.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropPartitionFunction.cs index a66407d47b..c75c160ea7 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropPartitionFunction.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropPartitionFunction.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlDropPartitionFunction : SqlStatement, ISqlCompileUnit { public PartitionFunction PartitionFunction { get; } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropPartitionScheme.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropPartitionScheme.cs index 29aa661cf9..28724f7bd1 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropPartitionScheme.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropPartitionScheme.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlDropPartitionScheme : SqlStatement, ISqlCompileUnit { public PartitionSchema PartitionSchema { get; } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropSchema.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropSchema.cs index 0e62a998b4..8d1374ff98 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropSchema.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropSchema.cs @@ -7,21 +7,11 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlDropSchema : SqlStatement, ISqlCompileUnit { - private bool cascade = true; - public Schema Schema { get; } - public bool Cascade { - get { - return cascade; - } - set { - cascade = value; - } - } + public bool Cascade { get; set; } = true; internal override SqlDropSchema Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => @@ -40,7 +30,7 @@ internal SqlDropSchema(Schema schema) : base(SqlNodeType.Drop) internal SqlDropSchema(Schema schema, bool cascade) : base(SqlNodeType.Drop) { Schema = schema; - this.cascade = cascade; + Cascade = cascade; } } } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropSequence.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropSequence.cs index 1a2c5bbff8..32967aa262 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropSequence.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropSequence.cs @@ -7,21 +7,11 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlDropSequence : SqlStatement, ISqlCompileUnit { - private bool cascade = true; - public Sequence Sequence { get; } - public bool Cascade { - get { - return cascade; - } - set { - cascade = value; - } - } + public bool Cascade { get; set; } = true; internal override SqlDropSequence Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => @@ -42,7 +32,7 @@ internal SqlDropSequence(Sequence sequence, bool cascade) : base(SqlNodeType.Drop) { Sequence = sequence; - this.cascade = cascade; + Cascade = cascade; } } } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropTable.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropTable.cs index 0cedb190d4..f292e8b353 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropTable.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropTable.cs @@ -7,25 +7,15 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlDropTable : SqlStatement, ISqlCompileUnit { - private bool cascade = true; - public Table Table { get; } - public bool Cascade { - get { - return cascade; - } - set { - cascade = value; - } - } + public bool Cascade { get; set; } = true; internal override SqlDropTable Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => - new SqlDropTable(t.Table, t.cascade)); + new SqlDropTable(t.Table, t.Cascade)); public override void AcceptVisitor(ISqlVisitor visitor) { @@ -40,7 +30,7 @@ internal SqlDropTable(Table table) : base(SqlNodeType.Drop) internal SqlDropTable(Table table, bool cascade) : base(SqlNodeType.Drop) { Table = table; - this.cascade = cascade; + Cascade = cascade; } } } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropTranslation.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropTranslation.cs index 7a3f0e0652..bcdc130a07 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropTranslation.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropTranslation.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlDropTranslation : SqlStatement, ISqlCompileUnit { public Translation Translation { get; } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropView.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropView.cs index ea8f898b22..59791c5574 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlDropView.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlDropView.cs @@ -7,25 +7,15 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlDropView : SqlStatement, ISqlCompileUnit { - private bool cascade = true; - public View View { get; } - public bool Cascade { - get { - return cascade; - } - set { - cascade = value; - } - } + public bool Cascade { get; set; } = true; internal override SqlDropView Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => - new SqlDropView(t.View)); + new SqlDropView(t.View, t.Cascade)); public override void AcceptVisitor(ISqlVisitor visitor) { @@ -40,7 +30,7 @@ internal SqlDropView(View view) : base(SqlNodeType.Drop) internal SqlDropView(View view, bool cascade) : base(SqlNodeType.Drop) { View = view; - this.cascade = cascade; + Cascade = cascade; } } } diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlRenameTable.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlRenameTable.cs index 0b7083ffda..44c955b30f 100644 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlRenameTable.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlRenameTable.cs @@ -9,11 +9,10 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlRenameTable : SqlStatement, ISqlCompileUnit { - public Table Table { get; private set; } - public string NewName { get; private set; } + public Table Table { get; } + public string NewName { get; } internal override SqlRenameTable Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => diff --git a/Orm/Xtensive.Orm/Sql/Ddl/SqlTruncateTable.cs b/Orm/Xtensive.Orm/Sql/Ddl/SqlTruncateTable.cs index 857b19c9b9..11ecb98797 100755 --- a/Orm/Xtensive.Orm/Sql/Ddl/SqlTruncateTable.cs +++ b/Orm/Xtensive.Orm/Sql/Ddl/SqlTruncateTable.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Ddl { - [Serializable] public class SqlTruncateTable : SqlStatement, ISqlCompileUnit { public Table Table { get; } diff --git a/Orm/Xtensive.Orm/Sql/Dml/Collections/SqlColumnCollection.cs b/Orm/Xtensive.Orm/Sql/Dml/Collections/SqlColumnCollection.cs index 5692cb60c6..2d94a3fc46 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Collections/SqlColumnCollection.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Collections/SqlColumnCollection.cs @@ -13,7 +13,6 @@ namespace Xtensive.Sql.Dml /// /// Represents collection of s. /// - [Serializable] public class SqlColumnCollection : ICollection, IReadOnlyList { private static readonly StringComparer Comparer = StringComparer.OrdinalIgnoreCase; diff --git a/Orm/Xtensive.Orm/Sql/Dml/Collections/SqlOrderCollection.cs b/Orm/Xtensive.Orm/Sql/Dml/Collections/SqlOrderCollection.cs index 4e3dd31afb..e059e58e0c 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Collections/SqlOrderCollection.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Collections/SqlOrderCollection.cs @@ -10,27 +10,14 @@ namespace Xtensive.Sql.Dml /// /// Represents collection of s. /// - [Serializable] public class SqlOrderCollection : Collection { - public void Add(SqlExpression expression) - { - Add(SqlDml.Order(expression)); - } + public void Add(SqlExpression expression) => Add(SqlDml.Order(expression)); - public void Add(SqlExpression expression, bool ascending) - { - Add(SqlDml.Order(expression, ascending)); - } - - public void Add(int position) - { - Add(SqlDml.Order(position)); - } + public void Add(SqlExpression expression, bool ascending) => Add(SqlDml.Order(expression, ascending)); - public void Add(int position, bool ascending) - { - Add(SqlDml.Order(position, ascending)); - } + public void Add(int position) => Add(SqlDml.Order(position)); + + public void Add(int position, bool ascending) => Add(SqlDml.Order(position, ascending)); } } diff --git a/Orm/Xtensive.Orm/Sql/Dml/Collections/SqlTableColumnCollection.cs b/Orm/Xtensive.Orm/Sql/Dml/Collections/SqlTableColumnCollection.cs index e03d3eaa45..63a580d5fd 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Collections/SqlTableColumnCollection.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Collections/SqlTableColumnCollection.cs @@ -12,7 +12,6 @@ namespace Xtensive.Sql.Dml /// /// Represents collection of s. /// - [Serializable] public class SqlTableColumnCollection : IReadOnlyList { private static readonly StringComparer Comparer = StringComparer.OrdinalIgnoreCase; diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlAggregate.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlAggregate.cs index d879a4dd64..37cb63e055 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlAggregate.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlAggregate.cs @@ -7,47 +7,38 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlAggregate : SqlExpression { - private bool distinct; - private SqlExpression expression; /// /// Gets a value indicating whether this is distinct. /// /// if distinct; otherwise, . - public bool Distinct - { - get { return distinct; } - } + public bool Distinct { get; private set; } /// /// Gets the expression. /// /// The expression. - public SqlExpression Expression - { - get { return expression; } - } + public SqlExpression Expression { get; private set; } public override void ReplaceWith(SqlExpression expression) { var replacingExpression = ArgumentValidator.EnsureArgumentIs(expression); NodeType = replacingExpression.NodeType; - distinct = replacingExpression.Distinct; - this.expression = replacingExpression.Expression; + Distinct = replacingExpression.Distinct; + Expression = replacingExpression.Expression; } internal override SqlAggregate Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => new SqlAggregate(t.NodeType, - t.expression?.Clone(c), t.distinct)); + t.Expression?.Clone(c), t.Distinct)); internal SqlAggregate(SqlNodeType nodeType, SqlExpression expression, bool distinct) : base(nodeType) { - this.expression = expression; - this.distinct = distinct; + Expression = expression; + Distinct = distinct; } public override void AcceptVisitor(ISqlVisitor visitor) diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlArray.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlArray.cs index 983735ee01..c9231590be 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlArray.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlArray.cs @@ -8,7 +8,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public abstract class SqlArray : SqlExpression { public abstract Type ItemType { get; } diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlArray{T}.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlArray{T}.cs index fe55c454b7..d18280668e 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlArray{T}.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlArray{T}.cs @@ -12,7 +12,6 @@ namespace Xtensive.Sql.Dml /// /// Represents generic array expression. /// - [Serializable] public class SqlArray : SqlArray { /// @@ -21,9 +20,9 @@ public class SqlArray : SqlArray /// The values. public T[] Values { get; private set; } - public override Type ItemType { get { return typeof (T); } } + public override Type ItemType => typeof(T); - public override int Length { get { return Values.Length; } } + public override int Length => Values.Length; public override object[] GetValues() { diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlBetween.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlBetween.cs index aab696dafe..9f2e12f38a 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlBetween.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlBetween.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Dml /// /// Represents between expression. /// - [Serializable] public class SqlBetween: SqlExpression { private SqlExpression left; @@ -21,28 +20,19 @@ public class SqlBetween: SqlExpression /// Gets the left boundary of the between predicate. /// /// The left boundary of the between predicate. - public SqlExpression Left - { - get { return left; } - } + public SqlExpression Left => left; /// /// Gets the right boundary of the between predicate. /// /// The right boundary of the between predicate. - public SqlExpression Right - { - get { return right; } - } + public SqlExpression Right => right; /// /// Gets the expression to compare. /// /// The expression to compare. - public SqlExpression Expression - { - get { return expression; } - } + public SqlExpression Expression => expression; public override void ReplaceWith(SqlExpression expression) { @@ -50,7 +40,7 @@ public override void ReplaceWith(SqlExpression expression) NodeType = replacingExpression.NodeType; left = replacingExpression.Left; right = replacingExpression.Right; - expression = replacingExpression.Expression; + this.expression = replacingExpression.Expression; } internal override SqlBetween Clone(SqlNodeCloneContext context) => diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlBinary.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlBinary.cs index 5b047a15c2..264bc5a2eb 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlBinary.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlBinary.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Dml /// /// Represents binary expression. /// - [Serializable] public class SqlBinary : SqlExpression { /// diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlCase.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlCase.cs index 1f29081392..3096d56fc3 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlCase.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlCase.cs @@ -9,54 +9,17 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlCase: SqlExpression, IEnumerable> { + private readonly IList> cases = new List>(); private SqlExpression value; - private IList> cases = new List>(); private SqlExpression @else; - public SqlCase Add(SqlExpression key, SqlExpression value) - { - ArgumentNullException.ThrowIfNull(key); - ArgumentNullException.ThrowIfNull(value); - cases.Add(new KeyValuePair(key, value)); - return this; - } - - public void Clear() - { - cases.Clear(); - value = null; - @else = null; - } - - public bool Remove(SqlExpression key) - { - for(int i = 0; i < cases.Count; i++) - if ((object)cases[i] == (object)key) { - cases.RemoveAt(i); - return true; - } - return false; - } - public int Count { get { return cases.Count; } } - public int IndexOf(SqlExpression key) - { - int result = 0; - foreach (KeyValuePair pair in cases) { - if ((object)pair.Key == (object)key) - return result; - result++; - } - return -1; - } - public SqlExpression this[SqlExpression key] { get @@ -93,6 +56,42 @@ public SqlExpression Else set { @else = value; } } + public SqlCase Add(SqlExpression key, SqlExpression value) + { + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(value); + cases.Add(new KeyValuePair(key, value)); + return this; + } + + public int IndexOf(SqlExpression key) + { + int result = 0; + foreach (KeyValuePair pair in cases) { + if ((object) pair.Key == (object) key) + return result; + result++; + } + return -1; + } + + public void Clear() + { + cases.Clear(); + value = null; + @else = null; + } + + public bool Remove(SqlExpression key) + { + for (int i = 0; i < cases.Count; i++) + if ((object) cases[i] == (object) key) { + cases.RemoveAt(i); + return true; + } + return false; + } + public override void ReplaceWith(SqlExpression expression) { var replacingExpression = ArgumentValidator.EnsureArgumentIs(expression); diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlCast.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlCast.cs index 82b84316ff..37f6043762 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlCast.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlCast.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlCast : SqlExpression { public SqlExpression Operand { get; private set; } diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlCollate.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlCollate.cs index f687ffaa3f..40db2c5053 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlCollate.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlCollate.cs @@ -8,7 +8,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlCollate : SqlExpression { private Collation collation; @@ -18,21 +17,13 @@ public class SqlCollate : SqlExpression /// Gets the collation. /// /// The collation. - public Collation Collation { - get { - return collation; - } - } + public Collation Collation => collation; /// /// Gets the operand. /// /// The operand. - public SqlExpression Operand { - get { - return operand; - } - } + public SqlExpression Operand => operand; public override void ReplaceWith(SqlExpression expression) { diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlColumn.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlColumn.cs index aa2cc9aad4..e580cadce7 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlColumn.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlColumn.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public abstract class SqlColumn : SqlExpression { private string name; @@ -17,19 +16,13 @@ public abstract class SqlColumn : SqlExpression /// Gets or sets the name of this instance. /// /// The alias. - public virtual string Name - { - get { return name; } - } + public virtual string Name => name; /// /// Gets the table reference. /// /// The table reference. - public SqlTable SqlTable - { - get { return sqlTable; } - } + public SqlTable SqlTable => sqlTable; public override void ReplaceWith(SqlExpression expression) { @@ -59,6 +52,5 @@ internal SqlColumn(SqlTable sqlTable) : base(SqlNodeType.Column) internal SqlColumn() : base(SqlNodeType.Column) { } - } } diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlColumnRef.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlColumnRef.cs index 602e783c5b..dfc39e7b1b 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlColumnRef.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlColumnRef.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Dml /// /// Represents a reference to a SQL column. /// - [Serializable] public class SqlColumnRef : SqlColumn { /// diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlColumnStub.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlColumnStub.cs index 4115029945..e9536fd9c2 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlColumnStub.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlColumnStub.cs @@ -8,7 +8,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlColumnStub : SqlColumn { public SqlColumn Column { get; set; } diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlComment.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlComment.cs index 8f501e8ce5..3dec2f01cc 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlComment.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlComment.cs @@ -9,7 +9,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlComment : SqlExpression { /// @@ -37,10 +36,10 @@ public static SqlComment Join(SqlComment comment1, SqlComment comment2) if (ReferenceEquals(comment1, comment2)) return comment1; - if (comment1 == null && comment2 == null) + if (comment1 is null && comment2 is null) return null; - if (comment1 != null) { - if (comment2 != null) + if (comment1 is not null) { + if (comment2 is not null) comment1.Text += $" {comment2.Text}"; return comment1; } diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlConcat.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlConcat.cs index 0a33f02feb..1e8c286b06 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlConcat.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlConcat.cs @@ -6,12 +6,10 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using Xtensive.Core; namespace Xtensive.Sql.Dml { - [Serializable] public class SqlConcat : SqlExpressionList { internal override SqlConcat Clone(SqlNodeCloneContext context) diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlCursor.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlCursor.cs index d40f8da4bd..0c776ae1d5 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlCursor.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlCursor.cs @@ -7,26 +7,16 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlCursor: SqlExpression { - private readonly string name; - private bool insensitive; - private bool scroll; - private ISqlQueryExpression query; - private bool readOnly = false; private readonly SqlColumnCollection columns = new SqlColumnCollection(); - private bool withHold; - private bool withReturn; + private ISqlQueryExpression query; /// /// Gets the name of the cursor. /// /// The name of the cursor. - public string Name - { - get { return name; } - } + public string Name { get; } /// /// Gets or sets a value indicating whether this @@ -34,21 +24,13 @@ public string Name /// /// if this makes a temporary /// copy of the data to be used; otherwise, . - public bool Insensitive - { - get { return insensitive; } - set { insensitive = value; } - } + public bool Insensitive { get; set; } /// /// Gets or sets a value indicating whether all fetch options are available for this cursor. /// /// if all fetch options are available; otherwise, . - public bool Scroll - { - get { return scroll; } - set { scroll = value; } - } + public bool Scroll { get; set; } /// /// Gets or sets the select statement that defines the result set of the cursor. @@ -56,32 +38,21 @@ public bool Scroll /// The select statement that defines the result set of the cursor. public ISqlQueryExpression Query { - get { return query; } - set - { - ArgumentNullException.ThrowIfNull(value); - query = value; - } + get => query; + set => query = value ?? throw new ArgumentNullException(nameof(value)); } /// /// Gets or sets a value indicating whether cursor is read only. /// /// if cursor is read only; otherwise, . - public bool ReadOnly - { - get { return readOnly; } - set { readOnly = value; } - } + public bool ReadOnly { get; set; } = false; /// /// Gets updatable columns within the cursor. /// /// Updatable columns within the cursor. - public SqlColumnCollection Columns - { - get { return columns; } - } + public SqlColumnCollection Columns => columns; /// /// Gets or sets a value indicating whether this is holdable cursor. @@ -89,11 +60,7 @@ public SqlColumnCollection Columns /// /// if this instance is a holdable cursor; otherwise, . /// - public bool WithHold - { - get { return withHold; } - set { withHold = value; } - } + public bool WithHold { get; set; } /// /// Gets or sets a value indicating whether this instance is result set cursor. @@ -101,11 +68,7 @@ public bool WithHold /// /// if this instance is result set cursor; otherwise, . /// - public bool WithReturn - { - get { return withReturn; } - set { withReturn = value; } - } + public bool WithReturn { get; set; } public SqlDeclareCursor Declare() { @@ -181,7 +144,7 @@ public override void AcceptVisitor(ISqlVisitor visitor) internal SqlCursor(string name, ISqlQueryExpression query) : base(SqlNodeType.Cursor) { - this.name = name; + Name = name; this.query = query; } } diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlCustomFunctionCall.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlCustomFunctionCall.cs index 6eb3c68089..6aa07b3f4f 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlCustomFunctionCall.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlCustomFunctionCall.cs @@ -6,13 +6,11 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Linq; using Xtensive.Core; namespace Xtensive.Sql.Dml { - [Serializable] public class SqlCustomFunctionCall : SqlFunctionCallBase { /// diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlDefaultValue.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlDefaultValue.cs index a575d9d5e7..926d466554 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlDefaultValue.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlDefaultValue.cs @@ -7,13 +7,12 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlDefaultValue : SqlExpression { public override void ReplaceWith(SqlExpression expression) { ArgumentNullException.ThrowIfNull(expression); - ArgumentValidator.EnsureArgumentIs(expression); + _ = ArgumentValidator.EnsureArgumentIs(expression); } internal override SqlDefaultValue Clone(SqlNodeCloneContext context) diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlExpression.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlExpression.cs index a205dcf7ae..408afc84cd 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlExpression.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlExpression.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Dml /// /// Defines base class for any sql expression. /// - [Serializable] public abstract class SqlExpression : SqlNode { public static bool operator true(SqlExpression operand) diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlFunctionCall.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlFunctionCall.cs index 1802269cb8..0fb5a20361 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlFunctionCall.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlFunctionCall.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlFunctionCall : SqlFunctionCallBase { /// diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlFunctionCallBase.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlFunctionCallBase.cs index 680fb1c61b..6fae150456 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlFunctionCallBase.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlFunctionCallBase.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public abstract class SqlFunctionCallBase : SqlExpression { /// diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlLike.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlLike.cs index 1e76b22984..99caf9c422 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlLike.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlLike.cs @@ -10,71 +10,50 @@ namespace Xtensive.Sql.Dml /// /// Represents LIKE predicat. /// - [Serializable] public class SqlLike : SqlExpression { - private SqlExpression expression; - private SqlExpression pattern; - private SqlExpression escape; - private bool not = false; /// /// Gets the expression. /// /// The expression. - public SqlExpression Expression { - get { - return expression; - } - } + public SqlExpression Expression { get; private set; } /// /// Gets the pattern expression. /// /// The pattern. - public SqlExpression Pattern { - get { - return pattern; - } - } + public SqlExpression Pattern { get; private set; } /// /// Gets the escape character expression. /// /// The escape. - public SqlExpression Escape { - get { - return escape; - } - } + public SqlExpression Escape { get; private set; } - public bool Not { - get { - return not; - } - } + public bool Not { get; private set; } = false; public override void ReplaceWith(SqlExpression expression) { var replacingExpression = ArgumentValidator.EnsureArgumentIs(expression); - this.expression = replacingExpression.expression; - pattern = replacingExpression.Pattern; - escape = replacingExpression.Escape; - not = replacingExpression.Not; + Expression = replacingExpression.Expression; + Pattern = replacingExpression.Pattern; + Escape = replacingExpression.Escape; + Not = replacingExpression.Not; } internal override SqlLike Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => - new SqlLike(t.expression.Clone(c), - t.pattern.Clone(c), - t.escape?.Clone(c), t.not)); + new SqlLike(t.Expression.Clone(c), + t.Pattern.Clone(c), + t.Escape?.Clone(c), t.Not)); internal SqlLike(SqlExpression expression, SqlExpression pattern, SqlExpression escape, bool not) : base (SqlNodeType.Like) { - this.expression = expression; - this.pattern = pattern; - this.escape = escape; - this.not = not; + Expression = expression; + Pattern = pattern; + Escape = escape; + Not = not; } public override void AcceptVisitor(ISqlVisitor visitor) diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlLiteral.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlLiteral.cs index 95b6815fe6..5a92b7612a 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlLiteral.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlLiteral.cs @@ -8,7 +8,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public abstract class SqlLiteral : SqlExpression { public abstract Type LiteralType { get; } diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlLiteral{T}.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlLiteral{T}.cs index 1d6360729a..2116b64739 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlLiteral{T}.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlLiteral{T}.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Dml /// /// Represents literal value expression. /// - [Serializable] public class SqlLiteral : SqlLiteral { /// @@ -19,7 +18,7 @@ public class SqlLiteral : SqlLiteral /// The value. public T Value { get; private set; } - public override Type LiteralType { get { return typeof (T); } } + public override Type LiteralType => typeof(T); public override object GetValue() { diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlMatch.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlMatch.cs index 8604da11ea..655bd382c5 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlMatch.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlMatch.cs @@ -10,69 +10,51 @@ namespace Xtensive.Sql.Dml /// /// Represents MATCH SQL statement. /// - [Serializable] public class SqlMatch: SqlExpression { - private SqlExpression value; - private SqlSubQuery subQuery; - private bool unique = false; - private SqlMatchType matchType = SqlMatchType.None; - /// /// Gets the value which will be tested for matching. /// - public SqlExpression Value - { - get { return value; } - } + public SqlExpression Value { get; private set; } /// /// Gets the sub query to search of matching. /// - public SqlSubQuery SubQuery - { - get { return subQuery; } - } + public SqlSubQuery SubQuery { get; private set; } /// /// Gets a value indicating whether unique sub query rows for search matching will be used only. /// - public bool Unique - { - get { return unique; } - } + public bool Unique { get; private set; } = false; /// /// Gets the type of the match. /// - public SqlMatchType MatchType - { - get { return matchType; } - } + public SqlMatchType MatchType { get; private set; } = SqlMatchType.None; public override void ReplaceWith(SqlExpression expression) { var replacingExpression = ArgumentValidator.EnsureArgumentIs(expression); - value = replacingExpression.Value; - subQuery = replacingExpression.SubQuery; - matchType = replacingExpression.MatchType; - unique = replacingExpression.Unique; + Value = replacingExpression.Value; + SubQuery = replacingExpression.SubQuery; + MatchType = replacingExpression.MatchType; + Unique = replacingExpression.Unique; } internal override SqlMatch Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => - new SqlMatch(t.value.Clone(c), - t.subQuery.Clone(c), - t.unique, - t.matchType)); + new SqlMatch(t.Value.Clone(c), + t.SubQuery.Clone(c), + t.Unique, + t.MatchType)); internal SqlMatch(SqlExpression value, SqlSubQuery subQuery, bool unique, SqlMatchType matchType) : base(SqlNodeType.Match) { - this.value = value; - this.subQuery = subQuery; - this.unique = unique; - this.matchType = matchType; + Value = value; + SubQuery = subQuery; + Unique = unique; + MatchType = matchType; } public override void AcceptVisitor(ISqlVisitor visitor) diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlNative.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlNative.cs index ad717c14b2..d146a623a9 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlNative.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlNative.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlNative : SqlExpression, IConvertible { /// diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlNextValue.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlNextValue.cs index 88e09d70d3..16bcf42e7c 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlNextValue.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlNextValue.cs @@ -11,50 +11,41 @@ namespace Xtensive.Sql.Dml /// /// Represents NEXT VALUE FOR expression. /// - [Serializable] public class SqlNextValue : SqlExpression { - private Sequence sequence; - private int increment = 1; /// /// Gets the increment. /// /// The increment. - public int Increment - { - get { return increment; } - } + public int Increment { get; private set; } = 1; /// /// Gets the sequence. /// /// The sequence. - public Sequence Sequence - { - get { return sequence; } - } + public Sequence Sequence { get; private set; } public override void ReplaceWith(SqlExpression expression) { var replacingExpression = ArgumentValidator.EnsureArgumentIs(expression); - sequence = replacingExpression.Sequence; - increment = replacingExpression.Increment; + Sequence = replacingExpression.Sequence; + Increment = replacingExpression.Increment; } internal override SqlNextValue Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => - new SqlNextValue(t.sequence, t.increment)); + new SqlNextValue(t.Sequence, t.Increment)); internal SqlNextValue(Sequence sequence) : base(SqlNodeType.NextValue) { - this.sequence = sequence; + Sequence = sequence; } internal SqlNextValue(Sequence sequence, int increment) : base(SqlNodeType.NextValue) { - this.sequence = sequence; - this.increment = increment; + Sequence = sequence; + Increment = increment; } public override void AcceptVisitor(ISqlVisitor visitor) diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlNull.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlNull.cs index 9dfade6104..097aaee9e9 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlNull.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlNull.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlNull : SqlExpression { public override void ReplaceWith(SqlExpression expression) diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlParameterRef.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlParameterRef.cs index cd6d7fba15..9e5b1160b7 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlParameterRef.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlParameterRef.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Dml /// /// Represents a Sql parameter. /// - [Serializable] public class SqlParameterRef : SqlExpression, ISqlCursorFetchTarget { public object Parameter { get; private set; } diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlRound.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlRound.cs index b92e3c48b8..ba58eee3d7 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlRound.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlRound.cs @@ -9,7 +9,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public sealed class SqlRound : SqlExpression { public SqlExpression Argument { get; private set; } diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlRow.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlRow.cs index ccb483b4e9..e927840963 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlRow.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlRow.cs @@ -4,12 +4,10 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using Xtensive.Core; namespace Xtensive.Sql.Dml { - [Serializable] public class SqlRow: SqlExpressionList { internal override SqlRow Clone(SqlNodeCloneContext context) diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlSubQuery.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlSubQuery.cs index 5bd2713d09..1b3fc3d4e3 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlSubQuery.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlSubQuery.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Dml /// /// Represents sub query expression. /// - [Serializable] public class SqlSubQuery: SqlExpression { private ISqlQueryExpression query; diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlTableColumn.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlTableColumn.cs index 758cf8f240..4fc22af617 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlTableColumn.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlTableColumn.cs @@ -11,7 +11,6 @@ namespace Xtensive.Sql.Dml /// /// Defines a reference to object /// - [Serializable] public class SqlTableColumn : SqlColumn, ISqlLValue { public override void ReplaceWith(SqlExpression expression) diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlTrim.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlTrim.cs index e21d333539..e00eecc993 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlTrim.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlTrim.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Dml /// /// Represents Trim function call. /// - [Serializable] public class SqlTrim : SqlExpression { private SqlExpression expression; diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlUnary.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlUnary.cs index 7ec9b9e5ad..1bb579958e 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlUnary.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlUnary.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Dml /// /// Represents unary expression. /// - [Serializable] public class SqlUnary : SqlExpression { /// diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlUserColumn.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlUserColumn.cs index 5eb5df17bc..9c7eb69edb 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlUserColumn.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlUserColumn.cs @@ -7,35 +7,29 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlUserColumn : SqlColumn { - private SqlExpression expression; - /// /// Gets the column expression. /// /// The expression. - public SqlExpression Expression - { - get { return expression; } - } + public SqlExpression Expression { get; private set; } public override void ReplaceWith(SqlExpression expression) { var replacingExpression = ArgumentValidator.EnsureArgumentIs(expression); - this.expression = replacingExpression.Expression; + Expression = replacingExpression.Expression; } internal override SqlUserColumn Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => - new SqlUserColumn(t.expression.Clone(c))); + new SqlUserColumn(t.Expression.Clone(c))); // Constructor internal SqlUserColumn(SqlExpression expression) { - this.expression = expression; + Expression = expression; } public override void AcceptVisitor(ISqlVisitor visitor) diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlUserFunctionCall.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlUserFunctionCall.cs index 45f796530b..36f7f4bc4b 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlUserFunctionCall.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlUserFunctionCall.cs @@ -4,13 +4,11 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Linq; using Xtensive.Core; namespace Xtensive.Sql.Dml { - [Serializable] public class SqlUserFunctionCall : SqlFunctionCall { /// diff --git a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlVariable.cs b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlVariable.cs index 81ade76f2d..3979099af7 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlVariable.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Expressions/SqlVariable.cs @@ -7,50 +7,37 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlVariable : SqlExpression, ISqlCursorFetchTarget { - private string name; - private readonly SqlValueType type; - /// /// Gets the name. /// /// The name. - public string Name - { - get { return name;} - } + public string Name { get; private set; } /// /// Gets the type. /// /// The type. - public SqlValueType Type - { - get { return type; } - } + public SqlValueType Type { get; } - public SqlDeclareVariable Declare() - { - return new SqlDeclareVariable(this); - } + public SqlDeclareVariable Declare() => new SqlDeclareVariable(this); public override void ReplaceWith(SqlExpression expression) { var replacingExpression = ArgumentValidator.EnsureArgumentIs(expression); - name = replacingExpression.Name; + Name = replacingExpression.Name; } internal override SqlVariable Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => - new SqlVariable(t.name, t.type)); + new SqlVariable(t.Name, t.Type)); internal SqlVariable(string name, SqlValueType type) : base(SqlNodeType.Variable) { - this.name = name; - this.type = type; + Name = name; + Type = type; } public override void AcceptVisitor(ISqlVisitor visitor) diff --git a/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlFastFirstRowsHint.cs b/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlFastFirstRowsHint.cs index b84c5b4ad9..6e33c9535e 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlFastFirstRowsHint.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlFastFirstRowsHint.cs @@ -6,7 +6,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlFastFirstRowsHint : SqlHint { /// diff --git a/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlForceJoinOrderHint.cs b/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlForceJoinOrderHint.cs index 6a151f5038..c468878a71 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlForceJoinOrderHint.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlForceJoinOrderHint.cs @@ -9,10 +9,9 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlForceJoinOrderHint : SqlHint { - private SqlTable[] tables; + private readonly SqlTable[] tables; /// /// Gets the corresponding tables. diff --git a/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlHint.cs b/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlHint.cs index 0604b84565..74e47aba32 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlHint.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlHint.cs @@ -6,7 +6,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public abstract class SqlHint : SqlNode { /// diff --git a/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlJoinHint.cs b/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlJoinHint.cs index 5b44d48d6f..d488fd144d 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlJoinHint.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlJoinHint.cs @@ -9,7 +9,6 @@ namespace Xtensive.Sql.Dml /// /// Represents a join option (hint) for a query optimizer. /// - [Serializable] public class SqlJoinHint : SqlHint { /// diff --git a/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlJoinMethod.cs b/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlJoinMethod.cs index 07eb3f7096..5c6a946a42 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlJoinMethod.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlJoinMethod.cs @@ -14,7 +14,6 @@ namespace Xtensive.Sql.Dml /// and methods. /// Oracle supports all methods except method. /// - [Serializable] public enum SqlJoinMethod { /// diff --git a/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlNativeHint.cs b/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlNativeHint.cs index 36ff6d8c21..e2c344e637 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlNativeHint.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Hints/SqlNativeHint.cs @@ -6,7 +6,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlNativeHint : SqlHint { /// diff --git a/Orm/Xtensive.Orm/Sql/Dml/SqlContainsTable.cs b/Orm/Xtensive.Orm/Sql/Dml/SqlContainsTable.cs index e2d84cb178..dcd29455d9 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/SqlContainsTable.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/SqlContainsTable.cs @@ -1,12 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; -using Xtensive.Collections; using Xtensive.Sql.Model; namespace Xtensive.Sql.Dml { - [Serializable] public class SqlContainsTable: SqlTable, ISqlQueryExpression { public SqlTableRef TargetTable { get; private set; } diff --git a/Orm/Xtensive.Orm/Sql/Dml/SqlCustomFunctionType.cs b/Orm/Xtensive.Orm/Sql/Dml/SqlCustomFunctionType.cs index a2d26d7dbc..ce5631fa81 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/SqlCustomFunctionType.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/SqlCustomFunctionType.cs @@ -15,7 +15,6 @@ namespace Xtensive.Sql.Dml /// supported by majority of providers. Such functions should be /// handleded by the provider within which they are declared. /// - [Serializable] public sealed class SqlCustomFunctionType : IEquatable { public string Name { get; private set; } diff --git a/Orm/Xtensive.Orm/Sql/Dml/SqlDatePart.cs b/Orm/Xtensive.Orm/Sql/Dml/SqlDatePart.cs index 9a80a01cf2..35b53fcccf 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/SqlDatePart.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/SqlDatePart.cs @@ -29,8 +29,6 @@ namespace Xtensive.Sql.Dml // UtcDateTime = 15, // Offset = 16, // Nothing = 25, - - [Serializable] public enum SqlDatePart { Year = 0, diff --git a/Orm/Xtensive.Orm/Sql/Dml/SqlDateTimeOffsetPart.cs b/Orm/Xtensive.Orm/Sql/Dml/SqlDateTimeOffsetPart.cs index c1d0b61a9c..13dc403b6b 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/SqlDateTimeOffsetPart.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/SqlDateTimeOffsetPart.cs @@ -29,8 +29,6 @@ namespace Xtensive.Sql.Dml // UtcDateTime = 15, // Offset = 16, // Nothing = 25, - - [Serializable] public enum SqlDateTimeOffsetPart { Year = 0, diff --git a/Orm/Xtensive.Orm/Sql/Dml/SqlDateTimePart.cs b/Orm/Xtensive.Orm/Sql/Dml/SqlDateTimePart.cs index e431858e08..ada01ef4da 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/SqlDateTimePart.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/SqlDateTimePart.cs @@ -29,8 +29,6 @@ namespace Xtensive.Sql.Dml // UtcDateTime = 15, // Offset = 16, // Nothing = 25, - - [Serializable] public enum SqlDateTimePart { Year = 0, diff --git a/Orm/Xtensive.Orm/Sql/Dml/SqlFetchOption.cs b/Orm/Xtensive.Orm/Sql/Dml/SqlFetchOption.cs index 2d7b4523d5..162eec1aae 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/SqlFetchOption.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/SqlFetchOption.cs @@ -6,7 +6,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public enum SqlFetchOption { Next = 0, diff --git a/Orm/Xtensive.Orm/Sql/Dml/SqlFreeTextTable.cs b/Orm/Xtensive.Orm/Sql/Dml/SqlFreeTextTable.cs index 4dcb18621d..ff6e7ea830 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/SqlFreeTextTable.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/SqlFreeTextTable.cs @@ -7,12 +7,10 @@ using System; using System.Linq; using System.Collections.Generic; -using Xtensive.Collections; using Xtensive.Sql.Model; namespace Xtensive.Sql.Dml { - [Serializable] public class SqlFreeTextTable : SqlTable, ISqlQueryExpression { public SqlTableRef TargetTable { get; private set; } diff --git a/Orm/Xtensive.Orm/Sql/Dml/SqlFunctionType.cs b/Orm/Xtensive.Orm/Sql/Dml/SqlFunctionType.cs index a54c7e0456..0f3701bb81 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/SqlFunctionType.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/SqlFunctionType.cs @@ -6,7 +6,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public enum SqlFunctionType { Concat, diff --git a/Orm/Xtensive.Orm/Sql/Dml/SqlIntervalPart.cs b/Orm/Xtensive.Orm/Sql/Dml/SqlIntervalPart.cs index 45e6a7dbb4..a2dda55fc7 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/SqlIntervalPart.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/SqlIntervalPart.cs @@ -31,8 +31,6 @@ namespace Xtensive.Sql.Dml // UtcDateTime = 15, // Offset = 16, // Nothing = 25, - - [Serializable] public enum SqlIntervalPart { Day = 2, diff --git a/Orm/Xtensive.Orm/Sql/Dml/SqlJoinExpression.cs b/Orm/Xtensive.Orm/Sql/Dml/SqlJoinExpression.cs index 1e62d3ee9d..d01c5c5554 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/SqlJoinExpression.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/SqlJoinExpression.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlJoinExpression : SqlNode { /// diff --git a/Orm/Xtensive.Orm/Sql/Dml/SqlJoinType.cs b/Orm/Xtensive.Orm/Sql/Dml/SqlJoinType.cs index 26c9be5935..5f67e146ba 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/SqlJoinType.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/SqlJoinType.cs @@ -6,7 +6,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public enum SqlJoinType { CrossJoin, diff --git a/Orm/Xtensive.Orm/Sql/Dml/SqlJoinedTable.cs b/Orm/Xtensive.Orm/Sql/Dml/SqlJoinedTable.cs index 9c33bf30f6..6716ca584f 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/SqlJoinedTable.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/SqlJoinedTable.cs @@ -7,19 +7,13 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlJoinedTable : SqlTable { - private SqlJoinExpression joinExpression; - /// /// Gets the join expression. /// /// The join expression. - public SqlJoinExpression JoinExpression - { - get { return joinExpression; } - } + public SqlJoinExpression JoinExpression { get; } /// /// Gets or sets the aliased columns. @@ -29,19 +23,19 @@ public SqlJoinExpression JoinExpression internal override SqlJoinedTable Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => - new SqlJoinedTable(t.joinExpression.Clone(c)) { + new SqlJoinedTable(t.JoinExpression.Clone(c)) { AliasedColumns = new SqlColumnCollection(new List(t.AliasedColumns)) }); public override void AcceptVisitor(ISqlVisitor visitor) { - joinExpression.AcceptVisitor(visitor); + JoinExpression.AcceptVisitor(visitor); } /// public override IEnumerator GetEnumerator() { - return joinExpression.GetEnumerator(); + return JoinExpression.GetEnumerator(); } @@ -54,7 +48,7 @@ internal SqlJoinedTable(SqlJoinExpression joinExpression) internal SqlJoinedTable(SqlJoinExpression joinExpression, IReadOnlyList leftColumns, IReadOnlyList rightColumns) { - this.joinExpression = joinExpression; + JoinExpression = joinExpression; var allLeftColumns = joinExpression.Left.Columns; var allRightColumns = joinExpression.Right.Columns; diff --git a/Orm/Xtensive.Orm/Sql/Dml/SqlMatchType.cs b/Orm/Xtensive.Orm/Sql/Dml/SqlMatchType.cs index abdc1feac4..b6a6202d8a 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/SqlMatchType.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/SqlMatchType.cs @@ -9,7 +9,6 @@ namespace Xtensive.Sql.Dml /// /// Enums types of search of matching in MATCH SQL statement. /// - [Serializable] public enum SqlMatchType { /// diff --git a/Orm/Xtensive.Orm/Sql/Dml/SqlOrder.cs b/Orm/Xtensive.Orm/Sql/Dml/SqlOrder.cs index c8157c6e52..fc5df8fff9 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/SqlOrder.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/SqlOrder.cs @@ -9,7 +9,6 @@ namespace Xtensive.Sql.Dml /// /// Represents order specification. /// - [Serializable] public class SqlOrder : SqlNode { /// diff --git a/Orm/Xtensive.Orm/Sql/Dml/SqlQueryRef.cs b/Orm/Xtensive.Orm/Sql/Dml/SqlQueryRef.cs index f7dacf2daa..7a1e80dbee 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/SqlQueryRef.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/SqlQueryRef.cs @@ -8,25 +8,19 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlQueryRef : SqlTable { - private readonly ISqlQueryExpression query; - /// /// Gets the query statement. /// /// The query statement. - public ISqlQueryExpression Query - { - get { return query; } - } + public ISqlQueryExpression Query { get; } internal override SqlQueryRef Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => - t.query is SqlSelect ss + t.Query is SqlSelect ss ? new SqlQueryRef(ss.Clone(c), t.Name) - : new SqlQueryRef(((SqlQueryExpression) t.query).Clone(c), t.Name)); + : new SqlQueryRef(((SqlQueryExpression) t.Query).Clone(c), t.Name)); public override void AcceptVisitor(ISqlVisitor visitor) { @@ -41,7 +35,7 @@ internal SqlQueryRef(ISqlQueryExpression query) internal SqlQueryRef(ISqlQueryExpression query, string name) : base(name) { - this.query = query; + Query = query; var queryColumns = new List(); foreach (var queryExpression in query) { if (queryExpression is SqlSelect sqlSelect) { diff --git a/Orm/Xtensive.Orm/Sql/Dml/SqlTable.cs b/Orm/Xtensive.Orm/Sql/Dml/SqlTable.cs index ad33aa6756..0ad19c002a 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/SqlTable.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/SqlTable.cs @@ -12,7 +12,6 @@ namespace Xtensive.Sql.Dml /// /// Describes a reference to object; /// - [Serializable] public abstract class SqlTable : SqlNode, IEnumerable diff --git a/Orm/Xtensive.Orm/Sql/Dml/SqlTableRef.cs b/Orm/Xtensive.Orm/Sql/Dml/SqlTableRef.cs index b8524cd0b6..64315c7d3b 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/SqlTableRef.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/SqlTableRef.cs @@ -5,8 +5,6 @@ using System; using System.Linq; using System.Collections.Generic; -using System.Collections.ObjectModel; -using Xtensive.Collections; using Xtensive.Sql.Model; namespace Xtensive.Sql.Dml @@ -14,7 +12,6 @@ namespace Xtensive.Sql.Dml /// /// Describes a reference to object; /// - [Serializable] public class SqlTableRef : SqlTable { /// diff --git a/Orm/Xtensive.Orm/Sql/Dml/SqlTimePart.cs b/Orm/Xtensive.Orm/Sql/Dml/SqlTimePart.cs index 87923501a7..5f0a6e0e56 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/SqlTimePart.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/SqlTimePart.cs @@ -29,7 +29,6 @@ namespace Xtensive.Sql.Dml // UtcDateTime = 15, // Offset = 16, // Nothing = 25, - [Serializable] public enum SqlTimePart { Hour = 3, diff --git a/Orm/Xtensive.Orm/Sql/Dml/SqlTrimType.cs b/Orm/Xtensive.Orm/Sql/Dml/SqlTrimType.cs index 9fb89bb6d9..6796cdfc34 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/SqlTrimType.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/SqlTrimType.cs @@ -6,7 +6,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public enum SqlTrimType { Leading = 0, diff --git a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlAssignment.cs b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlAssignment.cs index a736acf6c0..0a9ceac21b 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlAssignment.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlAssignment.cs @@ -6,39 +6,28 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlAssignment : SqlStatement { - private readonly ISqlLValue left; - private readonly SqlExpression right; /// /// Gets the left operand of the assign statement. /// - public ISqlLValue Left { - get { - return left; - } - } + public ISqlLValue Left { get; } /// /// Gets the right operand of the assign statement. /// - public SqlExpression Right { - get { - return right; - } - } + public SqlExpression Right { get; } internal override SqlAssignment Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => - new SqlAssignment((ISqlLValue)t.left.Clone(), t.right.Clone(c))); + new SqlAssignment((ISqlLValue)t.Left.Clone(), t.Right.Clone(c))); internal SqlAssignment(ISqlLValue left, SqlExpression right) : base(SqlNodeType.Assign) { - this.right = right; - this.left = left; + Right = right; + Left = left; } public override void AcceptVisitor(ISqlVisitor visitor) diff --git a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlBatch.cs b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlBatch.cs index 1cfffdca8c..d030dc5eeb 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlBatch.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlBatch.cs @@ -9,7 +9,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlBatch: SqlStatement, IList, ISqlCompileUnit @@ -19,10 +18,7 @@ public class SqlBatch: SqlStatement, #region IList Members /// - public void Add(SqlStatement item) - { - statements.Add(item); - } + public void Add(SqlStatement item) => statements.Add(item); public void AddRange(IEnumerable items) { @@ -31,28 +27,16 @@ public void AddRange(IEnumerable items) } /// - public void Clear() - { - statements.Clear(); - } + public void Clear() => statements.Clear(); /// - public bool Contains(SqlStatement item) - { - return statements.Contains(item); - } + public bool Contains(SqlStatement item) => statements.Contains(item); /// - public void CopyTo(SqlStatement[] array, int arrayIndex) - { - statements.CopyTo(array, arrayIndex); - } + public void CopyTo(SqlStatement[] array, int arrayIndex) => statements.CopyTo(array, arrayIndex); /// - public bool Remove(SqlStatement item) - { - return statements.Remove(item); - } + public bool Remove(SqlStatement item) => statements.Remove(item); /// public int Count => statements.Count; @@ -61,22 +45,13 @@ public bool Remove(SqlStatement item) public bool IsReadOnly => false; /// - public int IndexOf(SqlStatement item) - { - return statements.IndexOf(item); - } + public int IndexOf(SqlStatement item) => statements.IndexOf(item); /// - public void Insert(int index, SqlStatement item) - { - statements.Insert(index, item); - } + public void Insert(int index, SqlStatement item) => statements.Insert(index, item); /// - public void RemoveAt(int index) - { - statements.RemoveAt(index); - } + public void RemoveAt(int index) => statements.RemoveAt(index); /// public SqlStatement this[int index] @@ -86,16 +61,10 @@ public SqlStatement this[int index] } /// - IEnumerator IEnumerable.GetEnumerator() - { - return statements.GetEnumerator(); - } + IEnumerator IEnumerable.GetEnumerator() => statements.GetEnumerator(); /// - IEnumerator IEnumerable.GetEnumerator() - { - return statements.GetEnumerator(); - } + IEnumerator IEnumerable.GetEnumerator() => statements.GetEnumerator(); #endregion diff --git a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlBreak.cs b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlBreak.cs index 43fa616ea2..7f5b59c596 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlBreak.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlBreak.cs @@ -6,7 +6,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlBreak : SqlStatement { internal override SqlBreak Clone(SqlNodeCloneContext context) => this; diff --git a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlCloseCursor.cs b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlCloseCursor.cs index 6cbedc1c78..bc72fae1ed 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlCloseCursor.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlCloseCursor.cs @@ -6,20 +6,13 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlCloseCursor : SqlStatement, ISqlCompileUnit { - private SqlCursor cursor; - /// /// Gets the cursor. /// /// The cursor. - public SqlCursor Cursor { - get { - return cursor; - } - } + public SqlCursor Cursor { get; } internal override SqlCloseCursor Clone(SqlNodeCloneContext context) => throw new NotImplementedException(); @@ -31,7 +24,7 @@ public override void AcceptVisitor(ISqlVisitor visitor) public SqlCloseCursor(SqlCursor cursor) : base(SqlNodeType.CloseCursor) { - this.cursor = cursor; + Cursor = cursor; } } } diff --git a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlContinue.cs b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlContinue.cs index 3b1ef9a5cc..0f628aa993 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlContinue.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlContinue.cs @@ -6,7 +6,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlContinue : SqlStatement { internal override SqlContinue Clone(SqlNodeCloneContext context) => this; diff --git a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlDeclareCursor.cs b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlDeclareCursor.cs index 9508ff5bee..79c8884565 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlDeclareCursor.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlDeclareCursor.cs @@ -6,16 +6,9 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlDeclareCursor : SqlStatement, ISqlCompileUnit { - private SqlCursor cursor; - - public SqlCursor Cursor { - get { - return cursor; - } - } + public SqlCursor Cursor { get; } internal override SqlDeclareCursor Clone(SqlNodeCloneContext context) => throw new NotImplementedException(); @@ -27,7 +20,7 @@ public override void AcceptVisitor(ISqlVisitor visitor) internal SqlDeclareCursor(SqlCursor cursor) : base(SqlNodeType.DeclareCursor) { - this.cursor = cursor; + Cursor = cursor; } } } diff --git a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlDeclareVariable.cs b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlDeclareVariable.cs index f097dc6f1d..64ffa410c1 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlDeclareVariable.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlDeclareVariable.cs @@ -6,7 +6,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlDeclareVariable : SqlStatement, ISqlCompileUnit { /// diff --git a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlDelete.cs b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlDelete.cs index 415ee8ea77..7859700e5c 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlDelete.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlDelete.cs @@ -9,23 +9,15 @@ namespace Xtensive.Sql.Dml /// /// Describes SQL DELETE statement. /// - [Serializable] public class SqlDelete : SqlQueryStatement, ISqlCompileUnit { private SqlExpression where; - private SqlTableRef delete; - private SqlTable from; - private SqlExpression limit; /// /// Gets or sets the table. /// /// The table to change. - public SqlTableRef Delete - { - get { return delete; } - set { delete = value; } - } + public SqlTableRef Delete { get; set; } /// /// Gets or sets the WHERE clause expression. @@ -45,28 +37,20 @@ public SqlExpression Where { /// /// Gets or sets the FROM clause expression. /// - public SqlTable From - { - get { return from;} - set { from = value; } - } + public SqlTable From { get; set; } /// /// Gets or sets the LIMIT clause expression /// - public SqlExpression Limit - { - get { return limit; } - set { limit = value; } - } + public SqlExpression Limit { get; set; } internal override SqlDelete Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => { SqlDelete clone = new SqlDelete(); if (t.Delete != null) clone.Delete = t.Delete.Clone(c); - if (t.from != null) - clone.From = (SqlQueryRef) t.from.Clone(c); + if (t.From != null) + clone.From = (SqlQueryRef) t.From.Clone(c); if (t.where is not null) clone.Where = t.where.Clone(c); @@ -85,7 +69,7 @@ internal SqlDelete(): base(SqlNodeType.Delete) internal SqlDelete(SqlTableRef table) : this() { - delete = table; + Delete = table; } public override void AcceptVisitor(ISqlVisitor visitor) diff --git a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlFetch.cs b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlFetch.cs index 84adf61b29..a20a9758b9 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlFetch.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlFetch.cs @@ -8,50 +8,33 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlFetch: SqlStatement, ISqlCompileUnit { - private readonly SqlCursor cursor; - private readonly SqlFetchOption option = SqlFetchOption.Next; - private readonly SqlExpression rowCount; - private readonly IList targets = new Collection(); /// /// Gets the cursor. /// /// The cursor. - public SqlCursor Cursor - { - get { return cursor; } - } + public SqlCursor Cursor { get; } /// /// Gets the fetch option. /// /// The fetch option. - public SqlFetchOption Option - { - get { return option; } - } + public SqlFetchOption Option { get; } = SqlFetchOption.Next; /// /// Gets the row count. /// /// The row count. - public SqlExpression RowCount - { - get { return rowCount; } - } + public SqlExpression RowCount { get; } /// /// Gets the targets. /// /// The targets. - public IList Targets - { - get { return targets; } - } + public IList Targets { get; } = new Collection(); internal override SqlFetch Clone(SqlNodeCloneContext context) => throw new NotImplementedException(); @@ -64,12 +47,12 @@ internal SqlFetch(SqlFetchOption option, SqlExpression rowCount, SqlCursor curso params ISqlCursorFetchTarget[] targets) : base(SqlNodeType.Fetch) { - this.option = option; + Option = option; if (targets != null) for (int i = 0, l = targets.Length; i < l; i++) - this.targets.Add(targets[i]); - this.cursor = cursor; - this.rowCount = rowCount; + Targets.Add(targets[i]); + Cursor = cursor; + RowCount = rowCount; } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlIf.cs b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlIf.cs index 2369cb1ea9..15ed22a6b8 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlIf.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlIf.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Dml /// /// Represents SQL IF...ELSE statement. /// - [Serializable] public class SqlIf: SqlStatement, ISqlCompileUnit { private SqlStatement trueStatement; diff --git a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlInsert.cs b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlInsert.cs index bcefeba871..67b95012e5 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlInsert.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlInsert.cs @@ -9,7 +9,6 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlInsert : SqlQueryStatement, ISqlCompileUnit { /// @@ -21,7 +20,7 @@ public class SqlInsert : SqlQueryStatement, ISqlCompileUnit /// /// Gets rows of values. /// - public SqlInsertValuesCollection ValueRows { get; private set; } = new SqlInsertValuesCollection(); + public SqlInsertValuesCollection ValueRows { get; private set; } = new(); /// /// Gets or sets the FROM clause expression. diff --git a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlOpenCursor.cs b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlOpenCursor.cs index ba33a97afe..d27ecc70bf 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlOpenCursor.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlOpenCursor.cs @@ -6,20 +6,13 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlOpenCursor : SqlStatement, ISqlCompileUnit { - private SqlCursor cursor; - /// /// Gets the cursor. /// /// The cursor. - public SqlCursor Cursor { - get { - return cursor; - } - } + public SqlCursor Cursor { get; } internal override SqlOpenCursor Clone(SqlNodeCloneContext context) => throw new NotImplementedException(); @@ -30,7 +23,7 @@ public override void AcceptVisitor(ISqlVisitor visitor) public SqlOpenCursor(SqlCursor cursor) : base(SqlNodeType.OpenCursor) { - this.cursor = cursor; + Cursor = cursor; } } } diff --git a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlQueryExpression.cs b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlQueryExpression.cs index 2c7371ae32..98dc8b9413 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlQueryExpression.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlQueryExpression.cs @@ -8,44 +8,30 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlQueryExpression : SqlStatement, ISqlQueryExpression { - private readonly ISqlQueryExpression left; - private readonly ISqlQueryExpression right; - private readonly bool all; + public ISqlQueryExpression Left { get; } - public ISqlQueryExpression Left - { - get { return left; } - } + public ISqlQueryExpression Right { get; } - public ISqlQueryExpression Right - { - get { return right; } - } - - public bool All - { - get { return all; } - } + public bool All { get; } internal override SqlQueryExpression Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => new SqlQueryExpression(t.NodeType, - (ISqlQueryExpression)((SqlNode) t.left).Clone(c), - (ISqlQueryExpression)((SqlNode) t.right).Clone(c), t.all)); + (ISqlQueryExpression)((SqlNode) t.Left).Clone(c), + (ISqlQueryExpression)((SqlNode) t.Right).Clone(c), t.All)); #region IEnumerable Members public IEnumerator GetEnumerator() { - foreach (ISqlQueryExpression expression in left) + foreach (ISqlQueryExpression expression in Left) yield return expression; - foreach (ISqlQueryExpression expression in right) + foreach (ISqlQueryExpression expression in Right) yield return expression; yield break; @@ -106,9 +92,9 @@ public SqlQueryExpression UnionAll(ISqlQueryExpression operand) internal SqlQueryExpression(SqlNodeType nodeType, ISqlQueryExpression left, ISqlQueryExpression right, bool all) : base(nodeType) { - this.left = left; - this.right = right; - this.all = all; + Left = left; + Right = right; + All = all; } } } \ No newline at end of file diff --git a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlQueryStatement.cs b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlQueryStatement.cs index 81a13268ff..cf6c1d90e7 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlQueryStatement.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlQueryStatement.cs @@ -11,7 +11,6 @@ namespace Xtensive.Sql.Dml /// /// Base class for DML statements. /// - [Serializable] public abstract class SqlQueryStatement : SqlStatement { private IList hints; diff --git a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlSelect.cs b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlSelect.cs index 322b791f62..5699db84d8 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlSelect.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlSelect.cs @@ -11,66 +11,44 @@ namespace Xtensive.Sql.Dml /// /// Represents SQL SELECT statement. /// - [Serializable] public class SqlSelect : SqlQueryStatement, ISqlQueryExpression { private readonly SqlUserColumn asterisk = SqlDml.Column(SqlDml.Asterisk); private readonly SqlColumnCollection columns = new SqlColumnCollection(); - private SqlLockType _lock; - private bool distinct; - private SqlTable from; private SqlColumnCollection groupBy = new SqlColumnCollection(); private SqlExpression having; private SqlOrderCollection orderBy; private SqlExpression where; private SqlExpression limit; private SqlExpression offset; - private SqlComment comment; - public SqlComment Comment - { - get { return comment; } - set { comment = value; } - } + public SqlComment Comment { get; set; } /// /// Gets the collection of columns to select. /// /// The collection of columns. - public SqlColumnCollection Columns - { - get { return columns; } - } + public SqlColumnCollection Columns => columns; /// /// An indexer that provides access to collection items by their names. /// Returns if there is no such item. /// - public SqlColumn this[string name] - { - get { return columns[name]; } - } + public SqlColumn this[string name] => columns[name]; /// /// An indexer that provides access to collection items by their index. /// Returns if there is no such item. /// - public SqlColumn this[int index] - { - get { return columns[index]; } - } + public SqlColumn this[int index] => columns[index]; /// /// Gets or sets from clause. /// /// The from clause. - public SqlTable From - { - get { return from; } - set { from = value; } - } + public SqlTable From { get; set; } /// /// Gets or sets the where clause. @@ -95,7 +73,7 @@ public SqlColumnCollection GroupBy { get { - if (groupBy == null) + if (groupBy is null) groupBy = new SqlColumnCollection(); return groupBy; } @@ -124,7 +102,7 @@ public SqlOrderCollection OrderBy { get { - if (orderBy == null) + if (orderBy is null) orderBy = new SqlOrderCollection(); return orderBy; } @@ -134,22 +112,11 @@ public SqlOrderCollection OrderBy /// Gets or sets a value indicating whether this is distinct. /// /// if distinct is set; otherwise, . - public bool Distinct - { - get { return distinct; } - set { distinct = value; } - } + public bool Distinct { get; set; } - public SqlUserColumn Asterisk - { - get { return asterisk; } - } + public SqlUserColumn Asterisk => asterisk; - public SqlLockType Lock - { - get { return _lock; } - set { _lock = value; } - } + public SqlLockType Lock { get; set; } /// /// Gets or sets the limit. @@ -189,7 +156,7 @@ public SqlExpression Offset internal override SqlSelect Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => { - SqlSelect clone = new SqlSelect(t.from==null ? null : t.from.Clone(c)); + SqlSelect clone = new SqlSelect(t.From==null ? null : t.From.Clone(c)); foreach (SqlColumn column in t.columns) clone.Columns.Add((SqlColumn)column.Clone(c)); @@ -203,7 +170,7 @@ internal override SqlSelect Clone(SqlNodeCloneContext context) => if (t.orderBy != null) foreach (SqlOrder so in t.orderBy) clone.OrderBy.Add(so.Clone(c)); - clone.Distinct = t.distinct; + clone.Distinct = t.Distinct; clone.Limit = t.Limit; clone.Offset = t.Offset; clone.Lock = t.Lock; @@ -300,7 +267,7 @@ IEnumerator IEnumerable.GetEnumerator() internal SqlSelect(SqlTable from) : this() { - this.from = from; + From = from; } internal SqlSelect() diff --git a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlStatementBlock.cs b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlStatementBlock.cs index ffb680fe06..ecb028af52 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlStatementBlock.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlStatementBlock.cs @@ -9,99 +9,62 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlStatementBlock : SqlStatement, IList { - private IList statements = new Collection(); + private readonly IList statements = new Collection(); #region IList Members /// - public void Add(SqlStatement item) - { - statements.Add(item); - } + public void Add(SqlStatement item) => statements.Add(item); /// - public void Clear() - { - statements.Clear(); - } + public void Clear() => statements.Clear(); /// - public bool Contains(SqlStatement item) - { - return statements.Contains(item); - } + public bool Contains(SqlStatement item) => statements.Contains(item); /// - public void CopyTo(SqlStatement[] array, int arrayIndex) - { - statements.CopyTo(array, arrayIndex); - } + public void CopyTo(SqlStatement[] array, int arrayIndex) => statements.CopyTo(array, arrayIndex); /// - public bool Remove(SqlStatement item) - { - return statements.Remove(item); - } + public bool Remove(SqlStatement item) => statements.Remove(item); /// - public int Count - { - get { return statements.Count; } - } + public int Count => statements.Count; /// - public bool IsReadOnly - { - get { return false; } - } + public bool IsReadOnly => false; /// - public int IndexOf(SqlStatement item) - { - return statements.IndexOf(item); - } + public int IndexOf(SqlStatement item) => statements.IndexOf(item); /// - public void Insert(int index, SqlStatement item) - { - statements.Insert(index, item); - } + public void Insert(int index, SqlStatement item) => statements.Insert(index, item); /// - public void RemoveAt(int index) - { - statements.RemoveAt(index); - } + public void RemoveAt(int index) => statements.RemoveAt(index); /// public SqlStatement this[int index] { - get { return statements[index]; } - set { statements[index] = value; } + get => statements[index]; + set => statements[index] = value; } /// - IEnumerator IEnumerable.GetEnumerator() - { - return statements.GetEnumerator(); - } + IEnumerator IEnumerable.GetEnumerator() => statements.GetEnumerator(); /// - public IEnumerator GetEnumerator() - { - return statements.GetEnumerator(); - } + public IEnumerator GetEnumerator() => statements.GetEnumerator(); #endregion internal override SqlStatementBlock Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => { - SqlStatementBlock clone = new SqlStatementBlock(); - foreach (SqlStatement s in t.statements) + var clone = new SqlStatementBlock(); + foreach (var s in t.statements) clone.Add((SqlStatement) s.Clone(c)); return clone; }); diff --git a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlUpdate.cs b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlUpdate.cs index 0f306e2b05..b53c44ecf9 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlUpdate.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlUpdate.cs @@ -7,34 +7,22 @@ namespace Xtensive.Sql.Dml { - [Serializable] public class SqlUpdate : SqlQueryStatement, ISqlCompileUnit { + private readonly Dictionary values = new(); private SqlExpression where; - private readonly Dictionary values = new Dictionary(); - private SqlTable from; - private SqlTableRef update; - private SqlExpression limit; /// /// Gets or sets the table. /// /// The table to change. - public SqlTableRef Update - { - get { return update; } - set { update = value; } - } + public SqlTableRef Update { get; set; } /// /// Gets the values. /// /// The values. - public Dictionary Values { - get { - return values; - } - } + public Dictionary Values => values; /// /// Gets or sets the WHERE clause expression. @@ -52,34 +40,26 @@ public SqlExpression Where { /// /// Gets or sets the FROM clause expression. /// - public SqlTable From - { - get { return from;} - set { from = value; } - } + public SqlTable From { get; set; } /// /// Gets or sets the LIMIT clause expression. /// - public SqlExpression Limit - { - get { return limit; } - set { limit = value; } - } + public SqlExpression Limit { get; set; } internal override SqlUpdate Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => { var clone = new SqlUpdate(); - if (t.update != null) + if (t.Update != null) clone.Update = t.Update.Clone(c); - if (t.from != null) - clone.From = (SqlQueryRef) t.from.Clone(c); + if (t.From != null) + clone.From = (SqlQueryRef) t.From.Clone(c); foreach (KeyValuePair p in t.values) clone.Values[(ISqlLValue) ((SqlExpression) p.Key).Clone(c)] = p.Value?.Clone(c); if (t.where is not null) clone.Where = t.where.Clone(c); - if (t.limit is not null) + if (t.Limit is not null) clone.Limit = t.where.Clone(c); if (t.Hints.Count > 0) foreach (SqlHint hint in t.Hints) @@ -96,7 +76,7 @@ internal SqlUpdate(): base(SqlNodeType.Update) internal SqlUpdate(SqlTableRef table) : this() { - update = table; + Update = table; } public override void AcceptVisitor(ISqlVisitor visitor) diff --git a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlWhile.cs b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlWhile.cs index 617f6d050c..57d74b5a5c 100644 --- a/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlWhile.cs +++ b/Orm/Xtensive.Orm/Sql/Dml/Statements/SqlWhile.cs @@ -10,23 +10,14 @@ namespace Xtensive.Sql.Dml /// /// Represents SQL while loop. /// - [Serializable] public class SqlWhile : SqlStatement { - private SqlStatement statement; private SqlExpression condition; /// /// Gets or sets the statement to execute. /// - public SqlStatement Statement { - get { - return statement; - } - set { - statement = value; - } - } + public SqlStatement Statement { get; set; } /// /// Gets or sets the condition for the repeated execution @@ -46,8 +37,8 @@ public SqlExpression Condition { internal override SqlWhile Clone(SqlNodeCloneContext context) => context.GetOrAdd(this, static (t, c) => { SqlWhile clone = new SqlWhile(t.condition.Clone(c)); - if (t.statement!=null) - clone.Statement = (SqlStatement) t.statement.Clone(c); + if (t.Statement!=null) + clone.Statement = (SqlStatement) t.Statement.Clone(c); return clone; }); diff --git a/Orm/Xtensive.Orm/Sql/Model/Action.cs b/Orm/Xtensive.Orm/Sql/Model/Action.cs index 95200cfa25..5662dae83b 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Action.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Action.cs @@ -7,7 +7,6 @@ namespace Xtensive.Sql { [Flags] - [Serializable] public enum Action { All = 0x01, diff --git a/Orm/Xtensive.Orm/Sql/Model/BoundaryType.cs b/Orm/Xtensive.Orm/Sql/Model/BoundaryType.cs index 7b39da0ea1..d75f4ebc9e 100644 --- a/Orm/Xtensive.Orm/Sql/Model/BoundaryType.cs +++ b/Orm/Xtensive.Orm/Sql/Model/BoundaryType.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql /// Specifies to which side of each boundary value interval, left or right, the boundary value /// belongs. /// - [Serializable] public enum BoundaryType { /// diff --git a/Orm/Xtensive.Orm/Sql/Model/Catalog.cs b/Orm/Xtensive.Orm/Sql/Model/Catalog.cs index c81feb7dd5..9f2d836370 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Catalog.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Catalog.cs @@ -11,11 +11,10 @@ namespace Xtensive.Sql.Model /// /// Represents a single database catalog that can contain multiple database schemas. /// - [Serializable] public class Catalog : Node { + private readonly PairedNodeCollection schemas; private Schema defaultSchema; - private PairedNodeCollection schemas; private PairedNodeCollection partitionFunctions; private PairedNodeCollection partitionSchemas; diff --git a/Orm/Xtensive.Orm/Sql/Model/CatalogNode.cs b/Orm/Xtensive.Orm/Sql/Model/CatalogNode.cs index 8d0f58cb1f..ea91e63246 100644 --- a/Orm/Xtensive.Orm/Sql/Model/CatalogNode.cs +++ b/Orm/Xtensive.Orm/Sql/Model/CatalogNode.cs @@ -11,7 +11,6 @@ namespace Xtensive.Sql.Model /// /// Represents a bound object. /// - [Serializable] public abstract class CatalogNode : Node, IPairedNode { private Catalog catalog; diff --git a/Orm/Xtensive.Orm/Sql/Model/CharacterSet.cs b/Orm/Xtensive.Orm/Sql/Model/CharacterSet.cs index f173e786d3..c466c0f745 100644 --- a/Orm/Xtensive.Orm/Sql/Model/CharacterSet.cs +++ b/Orm/Xtensive.Orm/Sql/Model/CharacterSet.cs @@ -9,7 +9,6 @@ namespace Xtensive.Sql.Model /// /// Represents a character set object. /// - [Serializable] public class CharacterSet : SchemaNode { #region SchemaNode Members diff --git a/Orm/Xtensive.Orm/Sql/Model/CheckOptions.cs b/Orm/Xtensive.Orm/Sql/Model/CheckOptions.cs index 4967498c5e..1d5da09966 100644 --- a/Orm/Xtensive.Orm/Sql/Model/CheckOptions.cs +++ b/Orm/Xtensive.Orm/Sql/Model/CheckOptions.cs @@ -9,7 +9,6 @@ namespace Xtensive.Sql /// /// Levels of checking to be done when inserting or updating data through a view. /// - [Serializable] public enum CheckOptions { /// diff --git a/Orm/Xtensive.Orm/Sql/Model/Collation.cs b/Orm/Xtensive.Orm/Sql/Model/Collation.cs index 5038e26887..439bb06f12 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Collation.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Collation.cs @@ -11,7 +11,6 @@ namespace Xtensive.Sql.Model /// of character data are sorted and compared, based on the norms of /// particular languages and locales. /// - [Serializable] public class Collation : SchemaNode { #region SchemaNode Members diff --git a/Orm/Xtensive.Orm/Sql/Model/Constraints/Assertion.cs b/Orm/Xtensive.Orm/Sql/Model/Constraints/Assertion.cs index 48f6713161..64ec8dcb7d 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Constraints/Assertion.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Constraints/Assertion.cs @@ -12,10 +12,9 @@ namespace Xtensive.Sql.Model /// of individual rows of a table, to the entire contents of a table, /// or to a state required to exist among a number of tables. /// - [Serializable] public class Assertion : SchemaNode { - private Constraint constraint; + private readonly Constraint constraint; /// /// Gets or sets the check condition for this instance. diff --git a/Orm/Xtensive.Orm/Sql/Model/Constraints/Constraint.cs b/Orm/Xtensive.Orm/Sql/Model/Constraints/Constraint.cs index 4723e2dca7..87339896e6 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Constraints/Constraint.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Constraints/Constraint.cs @@ -11,7 +11,6 @@ namespace Xtensive.Sql.Model /// /// Represents integrity constraint object. /// - [Serializable] public class Constraint : Node { private bool? isDeferrable; @@ -75,7 +74,6 @@ internal protected Constraint(string name, SqlExpression condition, bool? isDefe /// /// Represents integrity constraint object. /// - [Serializable] public abstract class Constraint : Constraint, IPairedNode where T: Node, IConstrainable { private T owner; diff --git a/Orm/Xtensive.Orm/Sql/Model/Constraints/DefaultConstraint.cs b/Orm/Xtensive.Orm/Sql/Model/Constraints/DefaultConstraint.cs index d26ac46846..3e3f9747de 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Constraints/DefaultConstraint.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Constraints/DefaultConstraint.cs @@ -12,7 +12,6 @@ namespace Xtensive.Sql.Model /// /// Represents default constraint. /// - [Serializable] public sealed class DefaultConstraint : TableConstraint { /// diff --git a/Orm/Xtensive.Orm/Sql/Model/Constraints/DomainConstraint.cs b/Orm/Xtensive.Orm/Sql/Model/Constraints/DomainConstraint.cs index ab2502749d..76e14aa61b 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Constraints/DomainConstraint.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Constraints/DomainConstraint.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Model /// /// Represents a constraint object. /// - [Serializable] public class DomainConstraint : Constraint { /// diff --git a/Orm/Xtensive.Orm/Sql/Model/Constraints/ForeignKey.cs b/Orm/Xtensive.Orm/Sql/Model/Constraints/ForeignKey.cs index a411e1bbcb..0168578b72 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Constraints/ForeignKey.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Constraints/ForeignKey.cs @@ -15,7 +15,6 @@ namespace Xtensive.Sql.Model /// each value in the column exists in the corresponding referenced column or columns /// in the referenced table. /// - [Serializable] public class ForeignKey : TableConstraint { private NodeCollection columns = new NodeCollection(); diff --git a/Orm/Xtensive.Orm/Sql/Model/Constraints/PrimaryKey.cs b/Orm/Xtensive.Orm/Sql/Model/Constraints/PrimaryKey.cs index 9ca9d85ef9..cc23f44d04 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Constraints/PrimaryKey.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Constraints/PrimaryKey.cs @@ -9,7 +9,6 @@ namespace Xtensive.Sql.Model /// /// Represents primary key constraint. /// - [Serializable] public class PrimaryKey : UniqueConstraint { diff --git a/Orm/Xtensive.Orm/Sql/Model/Constraints/TableConstraint.cs b/Orm/Xtensive.Orm/Sql/Model/Constraints/TableConstraint.cs index 5b10514197..1728a342a5 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Constraints/TableConstraint.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Constraints/TableConstraint.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Model /// /// Represents a base constraint object. /// - [Serializable] public abstract class TableConstraint : Constraint
{ diff --git a/Orm/Xtensive.Orm/Sql/Model/Constraints/UniqueConstraint.cs b/Orm/Xtensive.Orm/Sql/Model/Constraints/UniqueConstraint.cs index bbaabde174..93d63c90aa 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Constraints/UniqueConstraint.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Constraints/UniqueConstraint.cs @@ -12,7 +12,6 @@ namespace Xtensive.Sql.Model /// /// Represents unique table constraint. /// - [Serializable] public class UniqueConstraint : TableConstraint { private NodeCollection columns; diff --git a/Orm/Xtensive.Orm/Sql/Model/DataTable.cs b/Orm/Xtensive.Orm/Sql/Model/DataTable.cs index dd1826e8d8..4d65f38390 100644 --- a/Orm/Xtensive.Orm/Sql/Model/DataTable.cs +++ b/Orm/Xtensive.Orm/Sql/Model/DataTable.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Model /// /// An base class for and types. /// - [Serializable] public abstract class DataTable : SchemaNode { private PairedNodeCollection indexes; diff --git a/Orm/Xtensive.Orm/Sql/Model/DataTableColumn.cs b/Orm/Xtensive.Orm/Sql/Model/DataTableColumn.cs index bebaf04825..e3ad065bd9 100644 --- a/Orm/Xtensive.Orm/Sql/Model/DataTableColumn.cs +++ b/Orm/Xtensive.Orm/Sql/Model/DataTableColumn.cs @@ -9,7 +9,6 @@ namespace Xtensive.Sql.Model /// /// Represent a bound column. /// - [Serializable] public abstract class DataTableColumn : DataTableNode { #region Constructors diff --git a/Orm/Xtensive.Orm/Sql/Model/DataTableNode.cs b/Orm/Xtensive.Orm/Sql/Model/DataTableNode.cs index f6595ab3c7..ccb5f2ee49 100644 --- a/Orm/Xtensive.Orm/Sql/Model/DataTableNode.cs +++ b/Orm/Xtensive.Orm/Sql/Model/DataTableNode.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Model /// /// Represents a bound object. /// - [Serializable] public abstract class DataTableNode : Node, IPairedNode { private DataTable dataTable; diff --git a/Orm/Xtensive.Orm/Sql/Model/Domain.cs b/Orm/Xtensive.Orm/Sql/Model/Domain.cs index 2ad096c533..e4ff601a9b 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Domain.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Domain.cs @@ -15,7 +15,6 @@ namespace Xtensive.Sql.Model /// The purpose of a domain is to constrain the set of valid values /// that can be stored in SQL-data by various operations. /// - [Serializable] public class Domain : SchemaNode,IConstrainable { private SqlValueType dataType; diff --git a/Orm/Xtensive.Orm/Sql/Model/FullTextIndex.cs b/Orm/Xtensive.Orm/Sql/Model/FullTextIndex.cs index 968e04aa50..b711c21d5a 100644 --- a/Orm/Xtensive.Orm/Sql/Model/FullTextIndex.cs +++ b/Orm/Xtensive.Orm/Sql/Model/FullTextIndex.cs @@ -12,7 +12,6 @@ namespace Xtensive.Sql.Model /// /// Represents full-text index. /// - [Serializable] public class FullTextIndex : Index { private string fullTextCatalog; diff --git a/Orm/Xtensive.Orm/Sql/Model/Index.cs b/Orm/Xtensive.Orm/Sql/Model/Index.cs index b52b98f503..beca5303bc 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Index.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Index.cs @@ -11,7 +11,6 @@ namespace Xtensive.Sql.Model /// /// Represents an index. /// - [Serializable] public class Index : DataTableNode, IPartitionable { private PairedNodeCollection columns; diff --git a/Orm/Xtensive.Orm/Sql/Model/IndexColumn.cs b/Orm/Xtensive.Orm/Sql/Model/IndexColumn.cs index 28ae805d1e..509797ae7f 100644 --- a/Orm/Xtensive.Orm/Sql/Model/IndexColumn.cs +++ b/Orm/Xtensive.Orm/Sql/Model/IndexColumn.cs @@ -11,7 +11,6 @@ namespace Xtensive.Sql.Model /// /// Represent a bound column. /// - [Serializable] public class IndexColumn : Node, IPairedNode { private DataTableColumn column; diff --git a/Orm/Xtensive.Orm/Sql/Model/Language.cs b/Orm/Xtensive.Orm/Sql/Model/Language.cs index 2c6ec0ae49..c77a98e568 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Language.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Language.cs @@ -8,7 +8,6 @@ namespace Xtensive.Sql.Model { - [Serializable] public class Language : Node { public Language(string name) diff --git a/Orm/Xtensive.Orm/Sql/Model/Node.cs b/Orm/Xtensive.Orm/Sql/Model/Node.cs index 07927af311..0d70185b2c 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Node.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Node.cs @@ -11,7 +11,6 @@ namespace Xtensive.Sql.Model /// /// Represents base lockable named node. /// - [Serializable] [DebuggerDisplay("Name = {Name}")] public abstract class Node: LockableBase { diff --git a/Orm/Xtensive.Orm/Sql/Model/NodeCollection.cs b/Orm/Xtensive.Orm/Sql/Model/NodeCollection.cs index cec5820de9..7a8e3a65fc 100644 --- a/Orm/Xtensive.Orm/Sql/Model/NodeCollection.cs +++ b/Orm/Xtensive.Orm/Sql/Model/NodeCollection.cs @@ -14,7 +14,6 @@ namespace Xtensive.Sql.Model /// Represents lockable indexed by collection of s. /// /// Node type - [Serializable] [DebuggerDisplay("Count = {Count}")] public class NodeCollection: CollectionBaseSlim where TNode: Node diff --git a/Orm/Xtensive.Orm/Sql/Model/PairedNodeCollection.cs b/Orm/Xtensive.Orm/Sql/Model/PairedNodeCollection.cs index 37f885f1f0..ff7f16430f 100644 --- a/Orm/Xtensive.Orm/Sql/Model/PairedNodeCollection.cs +++ b/Orm/Xtensive.Orm/Sql/Model/PairedNodeCollection.cs @@ -14,7 +14,6 @@ namespace Xtensive.Sql.Model /// /// Owner node type /// Item node type - [Serializable] public class PairedNodeCollection: NodeCollection where TOwner : Node where TNode : Node, IPairedNode diff --git a/Orm/Xtensive.Orm/Sql/Model/PartitionMethod.cs b/Orm/Xtensive.Orm/Sql/Model/PartitionMethod.cs index 0d4a51e2b0..7b86911d27 100644 --- a/Orm/Xtensive.Orm/Sql/Model/PartitionMethod.cs +++ b/Orm/Xtensive.Orm/Sql/Model/PartitionMethod.cs @@ -9,7 +9,6 @@ namespace Xtensive.Sql.Model /// /// Enumeration of possible partitioning methods. /// - [Serializable] public enum PartitionMethod { /// diff --git a/Orm/Xtensive.Orm/Sql/Model/Partitioning/HashPartition.cs b/Orm/Xtensive.Orm/Sql/Model/Partitioning/HashPartition.cs index 5858acf706..265efe04ac 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Partitioning/HashPartition.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Partitioning/HashPartition.cs @@ -9,7 +9,6 @@ namespace Xtensive.Sql.Model /// /// Represents a hash partition. /// - [Serializable] public class HashPartition : Partition { #region Constructors diff --git a/Orm/Xtensive.Orm/Sql/Model/Partitioning/ListPartition.cs b/Orm/Xtensive.Orm/Sql/Model/Partitioning/ListPartition.cs index 88722254ba..bf6dfd54c7 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Partitioning/ListPartition.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Partitioning/ListPartition.cs @@ -9,7 +9,6 @@ namespace Xtensive.Sql.Model /// /// Represents a list partition. /// - [Serializable] public class ListPartition : Partition { /// diff --git a/Orm/Xtensive.Orm/Sql/Model/Partitioning/Partition.cs b/Orm/Xtensive.Orm/Sql/Model/Partitioning/Partition.cs index 739775ea40..e12c6bbf5f 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Partitioning/Partition.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Partitioning/Partition.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Model /// /// Represents a single partition object. /// - [Serializable] public abstract class Partition : Node, IPairedNode { private PartitionDescriptor partitionDescriptor; diff --git a/Orm/Xtensive.Orm/Sql/Model/Partitioning/PartitionDescriptor.cs b/Orm/Xtensive.Orm/Sql/Model/Partitioning/PartitionDescriptor.cs index d26a9ebecd..a95b158f13 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Partitioning/PartitionDescriptor.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Partitioning/PartitionDescriptor.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Model /// /// Represents a set of information concerning object partitioning. /// - [Serializable] public class PartitionDescriptor : Node { private IPartitionable owner; diff --git a/Orm/Xtensive.Orm/Sql/Model/Partitioning/PartitionFunction.cs b/Orm/Xtensive.Orm/Sql/Model/Partitioning/PartitionFunction.cs index 91a8be6291..08ccc55d99 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Partitioning/PartitionFunction.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Partitioning/PartitionFunction.cs @@ -11,7 +11,6 @@ namespace Xtensive.Sql.Model /// Represents a function in the current catalog that maps the rows of a table or index /// into partitions based on the values of a specified column. /// - [Serializable] public class PartitionFunction : CatalogNode { private SqlValueType dataType; diff --git a/Orm/Xtensive.Orm/Sql/Model/Partitioning/PartitionSchema.cs b/Orm/Xtensive.Orm/Sql/Model/Partitioning/PartitionSchema.cs index f808c31060..ee6702a906 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Partitioning/PartitionSchema.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Partitioning/PartitionSchema.cs @@ -14,7 +14,6 @@ namespace Xtensive.Sql.Model /// partitioned table or index to filegroups. The number and domain of the partitions of a /// partitioned table or index are determined in a . /// - [Serializable] public class PartitionSchema : CatalogNode { private PartitionFunction partitionFunction; diff --git a/Orm/Xtensive.Orm/Sql/Model/Partitioning/RangePartition.cs b/Orm/Xtensive.Orm/Sql/Model/Partitioning/RangePartition.cs index 8bf1bfcf75..2308baa01e 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Partitioning/RangePartition.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Partitioning/RangePartition.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Model /// /// Represents a range partition. /// - [Serializable] public class RangePartition : Partition { private string boundary; diff --git a/Orm/Xtensive.Orm/Sql/Model/ReferentialAction.cs b/Orm/Xtensive.Orm/Sql/Model/ReferentialAction.cs index 398012aa36..995657f950 100644 --- a/Orm/Xtensive.Orm/Sql/Model/ReferentialAction.cs +++ b/Orm/Xtensive.Orm/Sql/Model/ReferentialAction.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql /// Defines all possible actions applicable in the case /// of foreign key conflict. /// - [Serializable] public enum ReferentialAction { /// diff --git a/Orm/Xtensive.Orm/Sql/Model/Schema.cs b/Orm/Xtensive.Orm/Sql/Model/Schema.cs index da71e0a5fc..fe212799f7 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Schema.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Schema.cs @@ -13,7 +13,6 @@ namespace Xtensive.Sql.Model /// the default character set for the schema, /// and the descriptor of every component of the schema. /// - [Serializable] public class Schema : CatalogNode { private CharacterSet defaultCharacterSet; diff --git a/Orm/Xtensive.Orm/Sql/Model/SchemaNode.cs b/Orm/Xtensive.Orm/Sql/Model/SchemaNode.cs index f7d349c3d9..4409c67feb 100644 --- a/Orm/Xtensive.Orm/Sql/Model/SchemaNode.cs +++ b/Orm/Xtensive.Orm/Sql/Model/SchemaNode.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Model /// /// Represents any bound . /// - [Serializable] public abstract class SchemaNode : Node, IPairedNode { private Schema schema; diff --git a/Orm/Xtensive.Orm/Sql/Model/Sequence.cs b/Orm/Xtensive.Orm/Sql/Model/Sequence.cs index dc87d2c129..d5dd46045a 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Sequence.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Sequence.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Model /// /// Represents an object that generates unique numbers, mostly used for primary key values. /// - [Serializable] public class Sequence : SchemaNode, ISequenceable { private SequenceDescriptor sequenceDescriptor; diff --git a/Orm/Xtensive.Orm/Sql/Model/SequenceDescriptor.cs b/Orm/Xtensive.Orm/Sql/Model/SequenceDescriptor.cs index a8479f6139..b1068fde63 100644 --- a/Orm/Xtensive.Orm/Sql/Model/SequenceDescriptor.cs +++ b/Orm/Xtensive.Orm/Sql/Model/SequenceDescriptor.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Model /// /// Represents a set of information concerning sequence. /// - [Serializable] public class SequenceDescriptor : Node, ICloneable { private ISequenceable owner; diff --git a/Orm/Xtensive.Orm/Sql/Model/Table.cs b/Orm/Xtensive.Orm/Sql/Model/Table.cs index d67e421add..e7697a0f6f 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Table.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Table.cs @@ -13,7 +13,6 @@ namespace Xtensive.Sql.Model /// /// Represents a table object. /// - [Serializable] public class Table : DataTable,IConstrainable,IPartitionable { private readonly PairedNodeCollection columns; diff --git a/Orm/Xtensive.Orm/Sql/Model/TableColumn.cs b/Orm/Xtensive.Orm/Sql/Model/TableColumn.cs index 1eb05cf3fe..89e921bfe6 100644 --- a/Orm/Xtensive.Orm/Sql/Model/TableColumn.cs +++ b/Orm/Xtensive.Orm/Sql/Model/TableColumn.cs @@ -11,7 +11,6 @@ namespace Xtensive.Sql.Model /// /// Represents a bound column. /// - [Serializable] public class TableColumn : DataTableColumn, IPairedNode
,ISequenceable { private SqlValueType dataType; diff --git a/Orm/Xtensive.Orm/Sql/Model/TemporaryTable.cs b/Orm/Xtensive.Orm/Sql/Model/TemporaryTable.cs index 7e0b601720..a277856b46 100644 --- a/Orm/Xtensive.Orm/Sql/Model/TemporaryTable.cs +++ b/Orm/Xtensive.Orm/Sql/Model/TemporaryTable.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Model /// /// Represents a temporary table object. /// - [Serializable] public class TemporaryTable : Table { private bool isGlobal; diff --git a/Orm/Xtensive.Orm/Sql/Model/Translation.cs b/Orm/Xtensive.Orm/Sql/Model/Translation.cs index d87f3adc59..47992035d6 100644 --- a/Orm/Xtensive.Orm/Sql/Model/Translation.cs +++ b/Orm/Xtensive.Orm/Sql/Model/Translation.cs @@ -9,7 +9,6 @@ namespace Xtensive.Sql.Model /// /// Represents a characher translation object. /// - [Serializable] public class Translation : SchemaNode { #region SchemaNode Members diff --git a/Orm/Xtensive.Orm/Sql/Model/View.cs b/Orm/Xtensive.Orm/Sql/Model/View.cs index 1a717054f5..e866cf15e5 100644 --- a/Orm/Xtensive.Orm/Sql/Model/View.cs +++ b/Orm/Xtensive.Orm/Sql/Model/View.cs @@ -13,7 +13,6 @@ namespace Xtensive.Sql.Model /// /// Represents a View node. /// - [Serializable] public class View : DataTable { private PairedNodeCollection columns; diff --git a/Orm/Xtensive.Orm/Sql/Model/ViewColumn.cs b/Orm/Xtensive.Orm/Sql/Model/ViewColumn.cs index 350ff69dbe..41f459e6d4 100644 --- a/Orm/Xtensive.Orm/Sql/Model/ViewColumn.cs +++ b/Orm/Xtensive.Orm/Sql/Model/ViewColumn.cs @@ -10,7 +10,6 @@ namespace Xtensive.Sql.Model /// /// Represent a bound column. /// - [Serializable] public class ViewColumn : DataTableColumn, IPairedNode { /// diff --git a/Orm/Xtensive.Orm/Sql/SqlDml.cs b/Orm/Xtensive.Orm/Sql/SqlDml.cs index 3df68d0f5f..749031d867 100644 --- a/Orm/Xtensive.Orm/Sql/SqlDml.cs +++ b/Orm/Xtensive.Orm/Sql/SqlDml.cs @@ -1133,6 +1133,11 @@ public static SqlLiteral Literal(DateTime value) return new SqlLiteral(value); } + public static SqlLiteral Literal(DateTimeOffset value) + { + return new SqlLiteral(value); + } + public static SqlLiteral Literal(DateOnly value) { return new SqlLiteral(value); diff --git a/Orm/Xtensive.Orm/Sql/SqlNode.cs b/Orm/Xtensive.Orm/Sql/SqlNode.cs index 2337c70e21..b60cd78b36 100644 --- a/Orm/Xtensive.Orm/Sql/SqlNode.cs +++ b/Orm/Xtensive.Orm/Sql/SqlNode.cs @@ -9,7 +9,6 @@ namespace Xtensive.Sql /// /// Represents any node in Sql expression tree. /// - [Serializable] public abstract class SqlNode : ISqlNode { /// diff --git a/Orm/Xtensive.Orm/Sql/SqlNodeType.cs b/Orm/Xtensive.Orm/Sql/SqlNodeType.cs index f066f9a8f2..aa8d96f748 100644 --- a/Orm/Xtensive.Orm/Sql/SqlNodeType.cs +++ b/Orm/Xtensive.Orm/Sql/SqlNodeType.cs @@ -6,7 +6,6 @@ namespace Xtensive.Sql { - [Serializable] public enum SqlNodeType { Action, diff --git a/Orm/Xtensive.Orm/Sql/SqlStatement.cs b/Orm/Xtensive.Orm/Sql/SqlStatement.cs index 49a5f7d0d9..df3132f59a 100644 --- a/Orm/Xtensive.Orm/Sql/SqlStatement.cs +++ b/Orm/Xtensive.Orm/Sql/SqlStatement.cs @@ -9,7 +9,6 @@ namespace Xtensive.Sql /// /// Base class for SQL statements. /// - [Serializable] public abstract class SqlStatement : SqlNode { protected SqlStatement(SqlNodeType nodeType) : base(nodeType) diff --git a/Orm/Xtensive.Orm/Sql/SqlType.cs b/Orm/Xtensive.Orm/Sql/SqlType.cs index 895a17a3b5..d6864bd854 100644 --- a/Orm/Xtensive.Orm/Sql/SqlType.cs +++ b/Orm/Xtensive.Orm/Sql/SqlType.cs @@ -9,7 +9,6 @@ namespace Xtensive.Sql /// /// Enumerates supported SQL column types. /// - [Serializable] public struct SqlType : IEquatable { public readonly string Name; diff --git a/Orm/Xtensive.Orm/Sql/SqlValueType.cs b/Orm/Xtensive.Orm/Sql/SqlValueType.cs index 160871d4c9..89397d3521 100644 --- a/Orm/Xtensive.Orm/Sql/SqlValueType.cs +++ b/Orm/Xtensive.Orm/Sql/SqlValueType.cs @@ -11,7 +11,6 @@ namespace Xtensive.Sql /// /// Represents an SQL type with specific , and . /// - [Serializable] public sealed class SqlValueType : IEquatable { diff --git a/Orm/Xtensive.Orm/Tuples/DifferentialTuple.cs b/Orm/Xtensive.Orm/Tuples/DifferentialTuple.cs index 77d75817f4..c581b1b91b 100644 --- a/Orm/Xtensive.Orm/Tuples/DifferentialTuple.cs +++ b/Orm/Xtensive.Orm/Tuples/DifferentialTuple.cs @@ -6,7 +6,6 @@ using System; using System.Diagnostics; -using System.Runtime.Serialization; using Xtensive.Core; @@ -18,7 +17,6 @@ namespace Xtensive.Tuples /// with tuple providing all the /// changes made to . /// - [Serializable] public sealed class DifferentialTuple : Tuple { private Tuple origin; diff --git a/Orm/Xtensive.Orm/Tuples/FastReadOnlyTuple.cs b/Orm/Xtensive.Orm/Tuples/FastReadOnlyTuple.cs index 55c1f452a4..255988b9bc 100644 --- a/Orm/Xtensive.Orm/Tuples/FastReadOnlyTuple.cs +++ b/Orm/Xtensive.Orm/Tuples/FastReadOnlyTuple.cs @@ -14,7 +14,6 @@ namespace Xtensive.Tuples /// /// Fast read-only implementation. /// - [Serializable] public sealed class FastReadOnlyTuple : Tuple { private readonly TupleDescriptor descriptor; diff --git a/Orm/Xtensive.Orm/Tuples/Packed/PackedFieldDescriptor.cs b/Orm/Xtensive.Orm/Tuples/Packed/PackedFieldDescriptor.cs index e97d0d27da..44ab1f2a39 100644 --- a/Orm/Xtensive.Orm/Tuples/Packed/PackedFieldDescriptor.cs +++ b/Orm/Xtensive.Orm/Tuples/Packed/PackedFieldDescriptor.cs @@ -8,13 +8,11 @@ namespace Xtensive.Tuples.Packed { - [Serializable] internal struct PackedFieldDescriptor { internal int DataPosition; internal ushort StatePosition; - [NonSerialized] internal byte AccessorIndex; } } diff --git a/Orm/Xtensive.Orm/Tuples/Packed/PackedTuple.cs b/Orm/Xtensive.Orm/Tuples/Packed/PackedTuple.cs index 3a0d6f8e88..c36a926420 100644 --- a/Orm/Xtensive.Orm/Tuples/Packed/PackedTuple.cs +++ b/Orm/Xtensive.Orm/Tuples/Packed/PackedTuple.cs @@ -8,7 +8,6 @@ namespace Xtensive.Tuples.Packed { - [Serializable] internal sealed class PackedTuple : RegularTuple { public readonly TupleDescriptor PackedDescriptor; diff --git a/Orm/Xtensive.Orm/Tuples/RegularTuple.cs b/Orm/Xtensive.Orm/Tuples/RegularTuple.cs index 05147fdfad..4c7f5057d4 100644 --- a/Orm/Xtensive.Orm/Tuples/RegularTuple.cs +++ b/Orm/Xtensive.Orm/Tuples/RegularTuple.cs @@ -5,7 +5,6 @@ // Created: 2008.01.24 using System; -using System.Runtime.Serialization; namespace Xtensive.Tuples @@ -13,8 +12,6 @@ namespace Xtensive.Tuples /// /// Base class for any regular tuple. /// - [DataContract] - [Serializable] public abstract class RegularTuple : Tuple { // Constructors diff --git a/Orm/Xtensive.Orm/Tuples/Transform/ConcatTransform.cs b/Orm/Xtensive.Orm/Tuples/Transform/ConcatTransform.cs index 3b8974e797..2b4202e39b 100644 --- a/Orm/Xtensive.Orm/Tuples/Transform/ConcatTransform.cs +++ b/Orm/Xtensive.Orm/Tuples/Transform/ConcatTransform.cs @@ -14,7 +14,6 @@ namespace Xtensive.Tuples.Transform /// /// This class is used for concatenation of two s. /// - [Serializable] public sealed class ConcatTransform { private readonly (int first, int second) sourceParts; diff --git a/Orm/Xtensive.Orm/Tuples/Transform/Internals/ConcatTransformTuple.cs b/Orm/Xtensive.Orm/Tuples/Transform/Internals/ConcatTransformTuple.cs index ca29147f87..c7141e67f2 100644 --- a/Orm/Xtensive.Orm/Tuples/Transform/Internals/ConcatTransformTuple.cs +++ b/Orm/Xtensive.Orm/Tuples/Transform/Internals/ConcatTransformTuple.cs @@ -10,7 +10,6 @@ namespace Xtensive.Tuples.Transform.Internals /// /// A result tuple mapping 1 source tuple to a single one (this). /// - [Serializable] internal sealed class ConcatTransformTuple : Tuple, ITransformedTuple { private readonly ConcatTransform transform; diff --git a/Orm/Xtensive.Orm/Tuples/Transform/Internals/MapTransformTuple.cs b/Orm/Xtensive.Orm/Tuples/Transform/Internals/MapTransformTuple.cs index e26be75821..a711594305 100644 --- a/Orm/Xtensive.Orm/Tuples/Transform/Internals/MapTransformTuple.cs +++ b/Orm/Xtensive.Orm/Tuples/Transform/Internals/MapTransformTuple.cs @@ -13,7 +13,6 @@ namespace Xtensive.Tuples.Transform.Internals /// /// A result tuple mapping 1 source tuple to a single one (this). /// - [Serializable] internal sealed class MapTransformTuple : Tuple, ITransformedTuple { private readonly MapTransform transform; diff --git a/Orm/Xtensive.Orm/Tuples/Transform/Internals/SegmentTransformTuple.cs b/Orm/Xtensive.Orm/Tuples/Transform/Internals/SegmentTransformTuple.cs index 1aad9129e8..33740319fd 100644 --- a/Orm/Xtensive.Orm/Tuples/Transform/Internals/SegmentTransformTuple.cs +++ b/Orm/Xtensive.Orm/Tuples/Transform/Internals/SegmentTransformTuple.cs @@ -10,7 +10,6 @@ namespace Xtensive.Tuples.Transform.Internals /// /// A result tuple mapping 1 source tuple to a single one (this). /// - [Serializable] internal sealed class SegmentTransformTuple : Tuple, ITransformedTuple { private readonly SegmentTransform transform; diff --git a/Orm/Xtensive.Orm/Tuples/Transform/MapTransform.cs b/Orm/Xtensive.Orm/Tuples/Transform/MapTransform.cs index d27152adc6..6af2deb087 100644 --- a/Orm/Xtensive.Orm/Tuples/Transform/MapTransform.cs +++ b/Orm/Xtensive.Orm/Tuples/Transform/MapTransform.cs @@ -14,7 +14,6 @@ namespace Xtensive.Tuples.Transform /// /// Maps fields of a destination tuple to the specified fields of of the source tuple. /// - [Serializable] public sealed class MapTransform { private readonly IReadOnlyList map; diff --git a/Orm/Xtensive.Orm/Tuples/Transform/TupleTransformType.cs b/Orm/Xtensive.Orm/Tuples/Transform/TupleTransformType.cs index 2a10b5e8f2..471c65921b 100644 --- a/Orm/Xtensive.Orm/Tuples/Transform/TupleTransformType.cs +++ b/Orm/Xtensive.Orm/Tuples/Transform/TupleTransformType.cs @@ -11,7 +11,6 @@ namespace Xtensive.Tuples.Transform /// /// Enumerates possible tuple transformation types. /// - [Serializable] public enum TupleTransformType { /// diff --git a/Orm/Xtensive.Orm/Tuples/Tuple.cs b/Orm/Xtensive.Orm/Tuples/Tuple.cs index f355c827cf..d92e115991 100644 --- a/Orm/Xtensive.Orm/Tuples/Tuple.cs +++ b/Orm/Xtensive.Orm/Tuples/Tuple.cs @@ -6,10 +6,6 @@ using System; using System.Diagnostics; -using System.Runtime.CompilerServices; -using System.Runtime.Serialization; -using System.Text; -using Xtensive.Comparison; using Xtensive.Core; using Xtensive.Reflection; using Xtensive.Tuples.Packed; @@ -19,8 +15,6 @@ namespace Xtensive.Tuples /// /// A base class for auto generated tuples. /// - [DataContract] - [Serializable] public abstract class Tuple : ITuple, IEquatable { /// @@ -29,11 +23,9 @@ public abstract class Tuple : ITuple, IEquatable public const int HashCodeMultiplier = 397; /// - [IgnoreDataMember] public abstract TupleDescriptor Descriptor { get; } /// - [IgnoreDataMember] public virtual int Count { [DebuggerStepThrough] diff --git a/Orm/Xtensive.Orm/Tuples/TupleDescriptor.cs b/Orm/Xtensive.Orm/Tuples/TupleDescriptor.cs index 5ce635cc2b..4768c20b18 100644 --- a/Orm/Xtensive.Orm/Tuples/TupleDescriptor.cs +++ b/Orm/Xtensive.Orm/Tuples/TupleDescriptor.cs @@ -9,10 +9,8 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Runtime.Serialization; using System.Text; using Xtensive.Core; -using Xtensive.Linq.SerializableExpressions.Internals; using Xtensive.Reflection; using Xtensive.Tuples.Packed; @@ -22,18 +20,15 @@ namespace Xtensive.Tuples /// Tuple descriptor. /// Provides information about structure. /// - [Serializable] - public readonly struct TupleDescriptor : IEquatable, IReadOnlyList, ISerializable + public readonly struct TupleDescriptor : IEquatable, IReadOnlyList { public static readonly TupleDescriptor Empty = new TupleDescriptor(Array.Empty()); internal readonly int ValuesLength; internal readonly int ObjectsLength; - [NonSerialized] internal readonly PackedFieldDescriptor[] FieldDescriptors; - [NonSerialized] private readonly Type[] fieldTypes; #region IReadOnlyList members @@ -176,19 +171,6 @@ public override int GetHashCode() #endregion - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue(nameof(ValuesLength), ValuesLength); - info.AddValue(nameof(ObjectsLength), ObjectsLength); - - var typeNames = new string[fieldTypes.Length]; - for (var i = 0; i < typeNames.Length; i++) - typeNames[i] = fieldTypes[i].ToSerializableForm(); - - info.AddValue(nameof(fieldTypes), typeNames); - info.AddValue(nameof(FieldDescriptors), FieldDescriptors); - } - /// public override string ToString() { @@ -311,21 +293,5 @@ private TupleDescriptor(Type[] fieldTypes) break; } } - - public TupleDescriptor(SerializationInfo info, StreamingContext context) - { - ValuesLength = info.GetInt32(nameof(ValuesLength)); - ObjectsLength = info.GetInt32(nameof(ObjectsLength)); - - var typeNames = (string[]) info.GetValue(nameof(fieldTypes), typeof(string[])); - FieldDescriptors = (PackedFieldDescriptor[])info.GetValue( - nameof(FieldDescriptors), typeof(PackedFieldDescriptor[])); - - fieldTypes = new Type[typeNames.Length]; - for (var i = 0; i < typeNames.Length; i++) { - fieldTypes[i] = typeNames[i].GetTypeFromSerializableForm(); - TupleLayout.ConfigureFieldAccessor(ref FieldDescriptors[i], fieldTypes[i]); - } - } } } diff --git a/Orm/Xtensive.Orm/Tuples/TupleUpdater.cs b/Orm/Xtensive.Orm/Tuples/TupleUpdater.cs index 9cf096c4ef..0252179c49 100644 --- a/Orm/Xtensive.Orm/Tuples/TupleUpdater.cs +++ b/Orm/Xtensive.Orm/Tuples/TupleUpdater.cs @@ -13,7 +13,7 @@ namespace Xtensive.Tuples /// /// Helper type allowing to update tuples using functional style syntax. /// - [Serializable] + [Obsolete("No longer in use.")] public struct TupleUpdater { private readonly Tuple tuple; @@ -22,7 +22,7 @@ public struct TupleUpdater /// Gets the wrapped tuple. /// /// The tuple. - public Tuple Tuple { get { return tuple; } } + public Tuple Tuple => tuple; /// /// Updates the field of with the specified index.