From a4abea672d3b62656bc52fb4bb8d9bb58b52fb60 Mon Sep 17 00:00:00 2001 From: Olmo del Corral Date: Fri, 30 Aug 2019 12:48:41 +0200 Subject: [PATCH] more on .net core 3 --- Signum.Engine/Administrator.cs | 6 +- Signum.Engine/Basics/ExceptionLogic.cs | 12 +- Signum.Engine/Basics/PropertyRouteLogic.cs | 2 +- Signum.Engine/Basics/QueryLogic.cs | 4 +- Signum.Engine/Basics/SemiSymbolLogic.cs | 4 +- Signum.Engine/Basics/SymbolLogic.cs | 6 +- Signum.Engine/Basics/TypeLogic.cs | 2 +- Signum.Engine/CodeGeneration/CodeGenerator.cs | 4 +- .../CodeGeneration/LogicCodeGenerator.cs | 49 ++---- .../CodeGeneration/ReactCodeGenerator.cs | 8 +- Signum.Engine/Connection/Connector.cs | 7 +- Signum.Engine/Connection/FieldReader.cs | 2 +- Signum.Engine/Connection/SqlConnector.cs | 2 +- Signum.Engine/Connection/Transaction.cs | 18 +-- .../DynamicQuery/AutoCompleteUtils.cs | 22 +-- .../DynamicQuery/ColumnDescriptionFactory.cs | 2 +- Signum.Engine/DynamicQuery/DynamicQuery.cs | 2 +- .../DynamicQuery/DynamicQueryContainer.cs | 4 +- .../DynamicQuery/ExpressionContainer.cs | 8 +- Signum.Engine/Engine/ProgressExtensions.cs | 6 +- Signum.Engine/Engine/SchemaGenerator.cs | 2 +- Signum.Engine/Engine/SchemaSynchronizer.cs | 40 ++--- Signum.Engine/Engine/SqlBuilder.cs | 14 +- Signum.Engine/Engine/SqlPreCommand.cs | 2 +- Signum.Engine/Engine/Synchronizer.cs | 4 +- Signum.Engine/EntityCache.cs | 17 +-- Signum.Engine/Exceptions.cs | 12 +- Signum.Engine/Linq/AliasGenerator.cs | 2 +- Signum.Engine/Linq/DbExpressions.Sql.cs | 2 +- .../ChildProjectionFlattener.cs | 4 +- .../Linq/ExpressionVisitor/ColumnProjector.cs | 4 +- .../DbExpressionNominator.cs | 6 +- .../OverloadingSimplifier.cs | 2 +- .../Linq/ExpressionVisitor/QueryBinder.cs | 18 +-- .../Linq/ExpressionVisitor/SmartEqualizer.cs | 2 +- .../ExpressionVisitor/TranslatorBuilder.cs | 5 +- Signum.Engine/Linq/Meta/MetadataVisitor.cs | 2 +- Signum.Engine/Linq/ProjectionReader.cs | 3 +- Signum.Engine/Linq/TranslateResult.cs | 1 + Signum.Engine/LinqExpandHints.cs | 4 +- Signum.Engine/Operations/GraphState.cs | 14 +- Signum.Engine/Operations/OperationLogic.cs | 4 +- Signum.Engine/Retriever.cs | 7 +- Signum.Engine/Schema/EntityEvents.cs | 22 +-- Signum.Engine/Schema/ObjectName.cs | 32 +--- Signum.Engine/Schema/Schema.Basics.cs | 56 +++---- Signum.Engine/Schema/Schema.Expressions.cs | 2 +- Signum.Engine/Schema/Schema.Save.cs | 2 +- Signum.Engine/Schema/Schema.cs | 10 +- .../Schema/SchemaBuilder/SchemaBuilder.cs | 48 +++--- .../SchemaBuilder/SchemaBuilderSettings.cs | 2 +- .../{UniqueIndex.cs => UniqueTableIndex.cs} | 12 +- Signum.Engine/Signum.Engine.csproj | 9 +- Signum.Entities/Basics/Color.cs | 6 +- Signum.Entities/Basics/IUserEntity.cs | 4 +- Signum.Entities/Basics/Symbol.cs | 4 +- Signum.Entities/DynamicQuery/Column.cs | 2 +- Signum.Entities/DynamicQuery/Filter.cs | 2 +- Signum.Entities/DynamicQuery/QueryUtils.cs | 15 +- Signum.Entities/DynamicQuery/Requests.cs | 4 +- Signum.Entities/DynamicQuery/ResultTable.cs | 14 +- .../DynamicQuery/Tokens/CountToken.cs | 2 +- .../Tokens/ExtensionDictionaryToken.cs | 4 +- .../DynamicQuery/Tokens/ExtensionToken.cs | 2 +- .../DynamicQuery/Tokens/QueryToken.cs | 6 +- Signum.Entities/Entity.cs | 4 +- Signum.Entities/EnumEntity.cs | 12 +- Signum.Entities/FieldAttributes.cs | 6 +- Signum.Entities/Lite.cs | 29 +++- Signum.Entities/MList.cs | 30 ++-- Signum.Entities/ModelEntity.cs | 4 +- Signum.Entities/ModifiableEntity.cs | 16 +- Signum.Entities/ObjectDumper.cs | 18 +-- Signum.Entities/Patterns/CorruptEntity.cs | 4 +- Signum.Entities/Patterns/LockeableEntity.cs | 4 +- Signum.Entities/PrimaryKey.cs | 12 +- Signum.Entities/PropertyRoute.cs | 19 +-- .../EntityStructuralEqualityComparer.cs | 14 +- Signum.Entities/Reflection/GraphExplorer.cs | 26 ++-- Signum.Entities/Reflection/ModifyInspector.cs | 15 +- Signum.Entities/Reflection/Reflector.cs | 16 +- Signum.Entities/Signum.Entities.csproj | 62 ++++---- Signum.Entities/TypeAttributes.cs | 6 +- Signum.Entities/Validator.cs | 4 +- Signum.MSBuildTask/Program.cs | 5 +- Signum.MSBuildTask/Signum.MSBuildTask.csproj | 2 +- .../ApiControllers/OperationController.cs | 2 +- Signum.React/Facades/ReflectionServer.cs | 30 ++-- .../Facades/SignumControllerFactory.cs | 8 +- Signum.React/Facades/SignumServer.cs | 10 +- .../Filters/SignumExceptionFilterAttribute.cs | 2 +- Signum.React/Filters/SignumFilters.cs | 4 +- .../Filters/VersionFilterAttribute.cs | 6 +- .../JsonConverters/ArgsJsonConverter.cs | 2 +- .../JsonConverters/EntityJsonConverter.cs | 8 +- Signum.React/JsonModelValidators/Bla.cs | 121 +++++++++++++++ .../DefaultCollectionValidationStrategy.cs | 141 ++++++++++++++++++ .../JsonModelValidators/DefaultValidator.cs | 71 +++++---- .../SignumObjectValidator.cs | 8 +- .../JsonModelValidators/ValidationStack.cs | 73 +++++++++ Signum.React/Signum.React.csproj | 3 +- Signum.Test/Environment/MusicStarter.cs | 2 +- Signum.Test/LinqProvider/JoinGroupTest.cs | 4 +- .../LinqProvider/SelectImplementations.cs | 8 +- Signum.Test/LinqProvider/SqlFunctionsTest.cs | 4 +- Signum.Test/LinqProvider/WhereTest.cs | 2 +- .../DataStructures/RecentsDictionary.cs | 2 +- .../ReferenceEqualityComparer.cs | 5 +- Signum.Utilities/DescriptionManager.cs | 4 +- Signum.Utilities/Disposable.cs | 2 +- .../Extensions/EnumerableExtensions.cs | 12 -- .../Extensions/StreamExtensions.cs | 2 +- Signum.Utilities/Extensions/TreeHelper.cs | 4 +- Signum.Utilities/MyRandom.cs | 14 +- Signum.Utilities/ProgressProxy.cs | 2 +- Signum.Utilities/StartParameters.cs | 6 +- Signum.Utilities/Synchronization/ResetLazy.cs | 2 +- 117 files changed, 896 insertions(+), 577 deletions(-) rename Signum.Engine/Schema/{UniqueIndex.cs => UniqueTableIndex.cs} (95%) create mode 100644 Signum.React/JsonModelValidators/Bla.cs create mode 100644 Signum.React/JsonModelValidators/DefaultCollectionValidationStrategy.cs create mode 100644 Signum.React/JsonModelValidators/ValidationStack.cs diff --git a/Signum.Engine/Administrator.cs b/Signum.Engine/Administrator.cs index 18e3544691..8dac3c0747 100644 --- a/Signum.Engine/Administrator.cs +++ b/Signum.Engine/Administrator.cs @@ -114,8 +114,8 @@ public static void CreateTemporaryIndex(Expression> fields, b IColumn[] columns = IndexKeyColumns.Split(view, fields); var index = unique ? - new UniqueIndex(view, columns) : - new Index(view, columns); + new UniqueTableIndex(view, columns) : + new TableIndex(view, columns); SqlBuilder.CreateIndex(index, checkUnique: null).ExecuteLeaves(); } @@ -478,7 +478,7 @@ from ifk in targetTable.IncommingForeignKeys() }); } - public static IDisposable DisableUniqueIndex(UniqueIndex index) + public static IDisposable DisableUniqueIndex(UniqueTableIndex index) { SafeConsole.WriteLineColor(ConsoleColor.DarkMagenta, " DISABLE Unique Index " + index.IndexName); SqlBuilder.DisableIndex(index.Table.Name, index.IndexName).ExecuteLeaves(); diff --git a/Signum.Engine/Basics/ExceptionLogic.cs b/Signum.Engine/Basics/ExceptionLogic.cs index 76647c935d..9361ffea8b 100644 --- a/Signum.Engine/Basics/ExceptionLogic.cs +++ b/Signum.Engine/Basics/ExceptionLogic.cs @@ -14,7 +14,7 @@ namespace Signum.Engine.Basics { public static class ExceptionLogic { - public static Func GetCurrentVersion; + public static Func? GetCurrentVersion; public static void Start(SchemaBuilder sb) { @@ -111,21 +111,21 @@ static ExceptionEntity SaveForceNew(this ExceptionEntity entity) } } - public static string DefaultEnvironment { get; set; } + public static string? DefaultEnvironment { get; set; } - public static string CurrentEnvironment { get { return overridenEnvironment.Value ?? DefaultEnvironment; } } + public static string? CurrentEnvironment { get { return overridenEnvironment.Value ?? DefaultEnvironment; } } - static readonly Variable overridenEnvironment = Statics.ThreadVariable("exceptionEnviroment"); + static readonly Variable overridenEnvironment = Statics.ThreadVariable("exceptionEnviroment"); public static IDisposable OverrideEnviroment(string newEnviroment) { - string oldEnviroment = overridenEnvironment.Value; + string? oldEnviroment = overridenEnvironment.Value; overridenEnvironment.Value = newEnviroment; return new Disposable(() => overridenEnvironment.Value = oldEnviroment); } - public static event Action DeleteLogs; + public static event Action? DeleteLogs; public static int DeleteLogsTimeOut = 10 * 60 * 1000; diff --git a/Signum.Engine/Basics/PropertyRouteLogic.cs b/Signum.Engine/Basics/PropertyRouteLogic.cs index a341055224..27eab8b31a 100644 --- a/Signum.Engine/Basics/PropertyRouteLogic.cs +++ b/Signum.Engine/Basics/PropertyRouteLogic.cs @@ -16,7 +16,7 @@ public static class PropertyRouteLogic public static bool IsPropertyRoute(this PropertyRouteEntity prdn, PropertyRoute pr) => As.Expression(() => prdn.RootType == pr.RootType.ToTypeEntity() && prdn.Path == pr.PropertyString()); - public static ResetLazy>> Properties; + public static ResetLazy>> Properties = null!; public static void Start(SchemaBuilder sb) { diff --git a/Signum.Engine/Basics/QueryLogic.cs b/Signum.Engine/Basics/QueryLogic.cs index 4968ad0d97..08eb308830 100644 --- a/Signum.Engine/Basics/QueryLogic.cs +++ b/Signum.Engine/Basics/QueryLogic.cs @@ -14,10 +14,10 @@ namespace Signum.Engine.Basics { public static class QueryLogic { - static ResetLazy> queryNamesLazy; + static ResetLazy> queryNamesLazy = null!; public static Dictionary QueryNames => queryNamesLazy.Value; - static ResetLazy> queryNameToEntityLazy; + static ResetLazy> queryNameToEntityLazy = null!; public static Dictionary QueryNameToEntity => queryNameToEntityLazy.Value; public static DynamicQueryContainer Queries { get; } = new DynamicQueryContainer(); diff --git a/Signum.Engine/Basics/SemiSymbolLogic.cs b/Signum.Engine/Basics/SemiSymbolLogic.cs index 63c5a73c71..c2475322bb 100644 --- a/Signum.Engine/Basics/SemiSymbolLogic.cs +++ b/Signum.Engine/Basics/SemiSymbolLogic.cs @@ -11,8 +11,8 @@ namespace Signum.Engine.Extensions.Basics public static class SemiSymbolLogic where T : SemiSymbol { - static ResetLazy> lazy; - static Func> getSemiSymbols; + static ResetLazy> lazy = null!; + static Func> getSemiSymbols = null!; [ThreadStatic] static bool avoidCache; diff --git a/Signum.Engine/Basics/SymbolLogic.cs b/Signum.Engine/Basics/SymbolLogic.cs index ee27736c57..6367890f04 100644 --- a/Signum.Engine/Basics/SymbolLogic.cs +++ b/Signum.Engine/Basics/SymbolLogic.cs @@ -12,7 +12,7 @@ namespace Signum.Engine public static class SymbolLogic { - public static event Action OnLoadAll; + public static event Action? OnLoadAll; public static void LoadAll() { @@ -23,8 +23,8 @@ public static void LoadAll() public static class SymbolLogic where T: Symbol { - static ResetLazy> lazy; - static Func> getSymbols; + static ResetLazy> lazy = null!; + static Func> getSymbols = null!; [ThreadStatic] static bool avoidCache; diff --git a/Signum.Engine/Basics/TypeLogic.cs b/Signum.Engine/Basics/TypeLogic.cs index 7a90ad2bcc..ee4b10b032 100644 --- a/Signum.Engine/Basics/TypeLogic.cs +++ b/Signum.Engine/Basics/TypeLogic.cs @@ -189,7 +189,7 @@ internal static List GenerateSchemaTypes() { TableName = tab.Name.ToString(), CleanName = Reflector.CleanTypeName(type), - Namespace = type.Namespace, + Namespace = type.Namespace!, ClassName = type.Name, }).ToList(); return list; diff --git a/Signum.Engine/CodeGeneration/CodeGenerator.cs b/Signum.Engine/CodeGeneration/CodeGenerator.cs index 5d4100691a..05ffcb0905 100644 --- a/Signum.Engine/CodeGeneration/CodeGenerator.cs +++ b/Signum.Engine/CodeGeneration/CodeGenerator.cs @@ -85,10 +85,10 @@ public static IEnumerable GetModules(Dictionary types, strin foreach (var item in selected) { if (name == null) - name = item.FullName.RemovePrefix(solutionName + ".Entities"); + name = item.FullName!.RemovePrefix(solutionName + ".Entities"); else { - int length = sd.LongestCommonSubstring(name, item.FullName, out int startName, out int rubbish); + int length = sd.LongestCommonSubstring(name, item.FullName!, out int startName, out int rubbish); name = name.Substring(startName, length); diff --git a/Signum.Engine/CodeGeneration/LogicCodeGenerator.cs b/Signum.Engine/CodeGeneration/LogicCodeGenerator.cs index ccdfaa62e1..3fe83ab66a 100644 --- a/Signum.Engine/CodeGeneration/LogicCodeGenerator.cs +++ b/Signum.Engine/CodeGeneration/LogicCodeGenerator.cs @@ -72,7 +72,7 @@ protected virtual IEnumerable GetModules() protected virtual List CandidateTypes() { - var assembly = Assembly.Load(Assembly.GetEntryAssembly().GetReferencedAssemblies().Single(a => a.Name == this.SolutionName + ".Entities")); + var assembly = Assembly.Load(Assembly.GetEntryAssembly()!.GetReferencedAssemblies().Single(a => a.Name == this.SolutionName + ".Entities")); return assembly.GetTypes().Where(t => t.IsEntity() && !t.IsAbstract).ToList(); } @@ -141,7 +141,7 @@ protected virtual List GetUsingNamespaces(Module mod, List e.FromType)).Select(t => t.Namespace).Distinct()); + result.AddRange(mod.Types.Concat(expressions.Select(e => e.FromType)).Select(t => t.Namespace!).Distinct()); return result; } @@ -277,8 +277,7 @@ protected internal class ExpressionInfo public Type ToType; public PropertyInfo Property; public bool IsUnique; - public string? Name; - public string? ExpressionName; + public string Name = null!; public ExpressionInfo(Type fromType, Type toType, PropertyInfo property, bool isUnique) { @@ -309,16 +308,6 @@ where fromType.IsEntity() && !fromType.IsAbstract result = result.Where(ShouldWriteExpression).ToList(); - var groups = result.Select(a => a.Name).GroupCount(); - - foreach (var ei in result) - { - if (groups[ei.Name] == 1) - ei.ExpressionName = ei.Name + "Expression"; - else - ei.ExpressionName = ei.Name + Reflector.CleanTypeName(ei.Property.PropertyType.CleanType()) + "Expresion"; - } - return result; } @@ -357,31 +346,19 @@ protected virtual string WriteExpressionMethod(ExpressionInfo info) string filter = info.Property.PropertyType.IsLite() ? "{t} => {t}.{prop}.Is({f})" : "{t} => {t}.{prop} == {f}"; string str = info.IsUnique? -@"static Expression> {MethodExpression} = - {f} => Database.Query<{to}>().SingleOrDefaultEx({filter}); -[ExpressionField] -public static {to} {Method}(this {from} e) -{ - return {MethodExpression}.Evaluate(e); -} +@"[AutoExpressionField] +public static {to} {Method}(this {from} {f}) => As.Expression(() => Database.Query<{to}>().SingleOrDefaultEx({filter})); " : -@"static Expression>> {MethodExpression} = - {f} => Database.Query<{to}>().Where({filter}); -[ExpressionField] -public static IQueryable<{to}> {Method}(this {from} e) -{ - return {MethodExpression}.Evaluate(e); -} +@"[AutoExpressionField] +public static IQueryable<{to}> {Method}(this {from} {f}) => As.Expression(() => Database.Query<{to}>().Where({filter})); "; - return str.Replace("{filter}", filter) .Replace("{from}", from.Name) .Replace("{to}", info.ToType.Name) .Replace("{t}", varTo) .Replace("{f}", varFrom) .Replace("{prop}", info.Property.Name) - .Replace("{Method}", info.Name) - .Replace("{MethodExpression}", info.ExpressionName); + .Replace("{Method}", info.Name); } protected virtual IEnumerable GetQueryProperties(Type type) @@ -408,7 +385,7 @@ protected virtual string GetWithVirtualMList(Type type, PropertyInfo p, Property if (p1 == p2) p2 += "2"; - var cast = p.DeclaringType == bp.PropertyType.CleanType() ? "" : $"(Lite<{p.DeclaringType.Name}>)"; + var cast = p.DeclaringType == bp.PropertyType.CleanType() ? "" : $"(Lite<{p.DeclaringType!.Name}>)"; return $" .WithVirtualMList({p1} => {p1}.{p.Name}, {p2} => {cast}{p2}.{bp.Name})"; } @@ -426,7 +403,7 @@ protected virtual string GetWithVirtualMList(Type type, PropertyInfo p, Property var t = pi.PropertyType.ElementType()!; - var backProperty = Reflector.PublicInstancePropertiesInOrder(t).SingleOrDefaultEx(bp => IsVirtualMListBackReference(bp, pi.DeclaringType)); + var backProperty = Reflector.PublicInstancePropertiesInOrder(t).SingleOrDefaultEx(bp => IsVirtualMListBackReference(bp, pi.DeclaringType!)); return backProperty; } @@ -537,7 +514,7 @@ private bool ShouldWriteSimpleOperations(IOperationSymbolContainer oper) protected virtual bool IsSave(IOperationSymbolContainer oper) { - return oper.ToString().Contains("Save"); ; + return oper.ToString()!.Contains("Save"); ; } protected virtual string? WriteDeleteOperation(IOperationSymbolContainer oper) @@ -606,7 +583,7 @@ protected virtual string WriteConstructFromMany(IOperationSymbolContainer oper) protected virtual IEnumerable GetOperationsSymbols(Type type) { - string name = type.FullName.RemoveSuffix("Entity") + "Operation"; + string name = type.FullName!.RemoveSuffix("Entity") + "Operation"; var operType = type.Assembly.GetType(name); @@ -614,7 +591,7 @@ protected virtual IEnumerable GetOperationsSymbols(Ty return Enumerable.Empty(); return (from fi in operType.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly) - select (IOperationSymbolContainer)fi.GetValue(null)).ToList(); + select (IOperationSymbolContainer)fi.GetValue(null)!).ToList(); } } } diff --git a/Signum.Engine/CodeGeneration/ReactCodeGenerator.cs b/Signum.Engine/CodeGeneration/ReactCodeGenerator.cs index 6fa2487142..9cbca8b8b7 100644 --- a/Signum.Engine/CodeGeneration/ReactCodeGenerator.cs +++ b/Signum.Engine/CodeGeneration/ReactCodeGenerator.cs @@ -147,7 +147,7 @@ public IEnumerable ReactGetModules(Dictionary types, string if (selectedTypes.IsNullOrEmpty()) yield break; - var directories = Directory.GetDirectories(GetProjectFolder(), "App\\").Select(a => Path.GetFileName(a)); + var directories = Directory.GetDirectories(GetProjectFolder(), "App\\").Select(a => Path.GetFileName(a)!); string? moduleName; if (directories.IsEmpty()) @@ -185,7 +185,7 @@ private static string AskModuleName(string solutionName, Type[] selected) protected virtual List CandidateTypes() { - var assembly = Assembly.Load(Assembly.GetEntryAssembly().GetReferencedAssemblies().Single(a => a.Name == this.SolutionName + ".Entities")); + var assembly = Assembly.Load(Assembly.GetEntryAssembly()!.GetReferencedAssemblies().Single(a => a.Name == this.SolutionName + ".Entities")); return assembly.GetTypes().Where(t => t.IsModifiableEntity() && !t.IsAbstract && !typeof(MixinEntity).IsAssignableFrom(t)).ToList(); } @@ -308,7 +308,7 @@ protected virtual List GetServerUsingNamespaces(Module mod) "Signum.React", }; - result.AddRange(mod.Types.Select(t => t.Namespace).Distinct()); + result.AddRange(mod.Types.Select(t => t.Namespace!).Distinct()); return result; } @@ -497,7 +497,7 @@ protected virtual string WriteMListProperty(PropertyInfo pi, string v) var eka = elementType.GetCustomAttribute(); - if (elementType.IsEmbeddedEntity() || (eka.EntityKind == EntityKind.Part || eka.EntityKind == EntityKind.SharedPart)) + if (elementType.IsEmbeddedEntity() || (eka!.EntityKind == EntityKind.Part || eka!.EntityKind == EntityKind.SharedPart)) if (pi.GetCustomAttribute()?.ImplementedTypes.Length > 1) return " {0}.{1})}} />".FormatWith(v, pi.Name.FirstLower()); else diff --git a/Signum.Engine/Connection/Connector.cs b/Signum.Engine/Connection/Connector.cs index 80132e02fc..efd3513b6f 100644 --- a/Signum.Engine/Connection/Connector.cs +++ b/Signum.Engine/Connection/Connector.cs @@ -33,12 +33,7 @@ public static Connector Current get { return currentConnector.Value ?? Default; } } - static Connector @default; - public static Connector Default - { - get { return @default; } - set { @default = value; } - } + public static Connector Default { get; set; } = null!; static readonly Variable scopeTimeout = Statics.ThreadVariable("scopeTimeout"); public static int? ScopeTimeout { get { return scopeTimeout.Value; } } diff --git a/Signum.Engine/Connection/FieldReader.cs b/Signum.Engine/Connection/FieldReader.cs index 16e10a199f..8ce8de6d26 100644 --- a/Signum.Engine/Connection/FieldReader.cs +++ b/Signum.Engine/Connection/FieldReader.cs @@ -595,7 +595,7 @@ public override string Message get { string text = "{0}\r\nOrdinal: {1}\r\nColumnName: {2}\r\nRow: {3}".FormatWith( - InnerException.Message, Ordinal, ColumnName, Row); + InnerException!.Message, Ordinal, ColumnName, Row); if (Projector != null) { diff --git a/Signum.Engine/Connection/SqlConnector.cs b/Signum.Engine/Connection/SqlConnector.cs index fd113cee9d..0c7188f3db 100644 --- a/Signum.Engine/Connection/SqlConnector.cs +++ b/Signum.Engine/Connection/SqlConnector.cs @@ -401,7 +401,7 @@ protected internal override void BulkCopy(DataTable dt, ObjectName destinationTa { bulkCopy.BulkCopyTimeout = timeout ?? Connector.ScopeTimeout ?? this.CommandTimeout ?? bulkCopy.BulkCopyTimeout; - foreach (DataColumn c in dt.Columns) + foreach (var c in dt.Columns.Cast()) bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(c.ColumnName, c.ColumnName)); bulkCopy.DestinationTableName = destinationTable.ToString(); diff --git a/Signum.Engine/Connection/Transaction.cs b/Signum.Engine/Connection/Transaction.cs index b1e6debd57..31ddd605ef 100644 --- a/Signum.Engine/Connection/Transaction.cs +++ b/Signum.Engine/Connection/Transaction.cs @@ -118,9 +118,9 @@ class RealTransaction : ICoreTransaction public DbTransaction? Transaction { get; private set; } public Exception? IsRolledback { get; private set; } public bool Started { get; private set; } - public event Action?> PostRealCommit; - public event Action?> PreRealCommit; - public event Action?> Rolledback; + public event Action?>? PostRealCommit; + public event Action?>? PreRealCommit; + public event Action?>? Rolledback; IsolationLevel? IsolationLevel; @@ -219,10 +219,10 @@ class NamedTransaction : ICoreTransaction string savePointName; public Exception? IsRolledback { get; private set; } public bool Started { get; private set; } - public event Action?> PostRealCommit; + public event Action?>? PostRealCommit; - public event Action?> PreRealCommit; - public event Action?> Rolledback; + public event Action?>? PreRealCommit; + public event Action?>? Rolledback; public NamedTransaction(ICoreTransaction parent, string savePointName) { @@ -297,9 +297,9 @@ class NoneTransaction : ICoreTransaction public DbTransaction? Transaction { get { return null; } } public Exception? IsRolledback { get; private set; } public bool Started { get; private set; } - public event Action?> PostRealCommit; - public event Action?> PreRealCommit; - public event Action?> Rolledback; + public event Action?>? PostRealCommit; + public event Action?>? PreRealCommit; + public event Action?>? Rolledback; public NoneTransaction(ICoreTransaction? parent) { diff --git a/Signum.Engine/DynamicQuery/AutoCompleteUtils.cs b/Signum.Engine/DynamicQuery/AutoCompleteUtils.cs index b4370f9331..570022104c 100644 --- a/Signum.Engine/DynamicQuery/AutoCompleteUtils.cs +++ b/Signum.Engine/DynamicQuery/AutoCompleteUtils.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; @@ -248,8 +248,8 @@ public static List AutocompleteUntyped(this IQueryable query, Expressio var parts = subString.Trim().SplitNoEmpty(' '); var list = query - .Where(r => entitySelector.Evaluate(r).ToString().ContainsAll(parts)) - .OrderBy(r => entitySelector.Evaluate(r).ToString().Length) + .Where(r => entitySelector.Evaluate(r).ToString()!.ContainsAll(parts)) + .OrderBy(r => entitySelector.Evaluate(r).ToString()!.Length) .Take(count - results.Count) .ToList(); @@ -278,8 +278,8 @@ public static async Task> AutocompleteUntypedAsync(this IQueryable var parts = subString.Trim().SplitNoEmpty(' '); - var list = await query.Where(r => entitySelector.Evaluate(r).ToString().ContainsAll(parts)) - .OrderBy(r => entitySelector.Evaluate(r).ToString().Length) + var list = await query.Where(r => entitySelector.Evaluate(r).ToString()!.ContainsAll(parts)) + .OrderBy(r => entitySelector.Evaluate(r).ToString()!.Length) .Take(count - results.Count) .ToListAsync(); @@ -310,8 +310,8 @@ public static List> Autocomplete(this IQueryable> query, stri var parts = subString.Trim().SplitNoEmpty(' '); - results.AddRange(query.Where(a => a.ToString().ContainsAll(parts)) - .OrderBy(a => a.ToString().Length) + results.AddRange(query.Where(a => a.ToString()!.ContainsAll(parts)) + .OrderBy(a => a.ToString()!.Length) .Take(count - results.Count)); return results; @@ -338,8 +338,8 @@ public static async Task>> AutocompleteAsync(this IQueryable a.ToString().ContainsAll(parts)) - .OrderBy(a => a.ToString().Length) + var list = await query.Where(a => a.ToString()!.ContainsAll(parts)) + .OrderBy(a => a.ToString()!.Length) .Take(count - results.Count) .ToListAsync(token); @@ -369,8 +369,8 @@ public static List> Autocomplete(this IEnumerable> collection var parts = subString.Trim().SplitNoEmpty(' '); - var list = collection.Where(a => a.ToString().ContainsAll(parts)) - .OrderBy(a => a.ToString().Length) + var list = collection.Where(a => a.ToString()!.ContainsAll(parts)) + .OrderBy(a => a.ToString()!.Length) .Take(count - results.Count); results.AddRange(list); diff --git a/Signum.Engine/DynamicQuery/ColumnDescriptionFactory.cs b/Signum.Engine/DynamicQuery/ColumnDescriptionFactory.cs index ec202cbc01..f7922c4d66 100644 --- a/Signum.Engine/DynamicQuery/ColumnDescriptionFactory.cs +++ b/Signum.Engine/DynamicQuery/ColumnDescriptionFactory.cs @@ -68,7 +68,7 @@ public PropertyRoute[]? PropertyRoutes case PropertyRouteType.Root: return null; case PropertyRouteType.FieldOrProperty: - return routes.Select(pr => pr.SimplifyToProperty().PropertyInfo.GetCustomAttribute()?.UnitName).Distinct().Only(); + return routes.Select(pr => pr.SimplifyToProperty().PropertyInfo!.GetCustomAttribute()?.UnitName).Distinct().Only(); case PropertyRouteType.MListItems: return null; } diff --git a/Signum.Engine/DynamicQuery/DynamicQuery.cs b/Signum.Engine/DynamicQuery/DynamicQuery.cs index 28219dcd66..592fd595ba 100644 --- a/Signum.Engine/DynamicQuery/DynamicQuery.cs +++ b/Signum.Engine/DynamicQuery/DynamicQuery.cs @@ -964,7 +964,7 @@ static Expression BuildAggregateExpressionQueryableAsync(Expression collection, var task = func(); - return giCastObject.GetInvoker(task.GetType().BaseType.GetGenericArguments())(task); + return giCastObject.GetInvoker(task.GetType().BaseType!.GetGenericArguments())(task); } static readonly GenericInvoker>> giCastObject = diff --git a/Signum.Engine/DynamicQuery/DynamicQueryContainer.cs b/Signum.Engine/DynamicQuery/DynamicQueryContainer.cs index cf52f9dd01..6624a023b2 100644 --- a/Signum.Engine/DynamicQuery/DynamicQueryContainer.cs +++ b/Signum.Engine/DynamicQuery/DynamicQueryContainer.cs @@ -102,7 +102,7 @@ async Task ExecuteAsync(ExecuteType executeType, object queryName, BaseQue } } - public event Func QueryExecuted; + public event Func? QueryExecuted; public enum ExecuteType { @@ -166,7 +166,7 @@ public DQueryable GetDQueryable(DQueryableRequest request) return Execute(ExecuteType.GetDQueryable, request.QueryName, null, dqb => dqb.Core.Value.GetDQueryable(request)); } - public event Func AllowQuery; + public event Func? AllowQuery; public bool QueryAllowed(object queryName, bool fullScreen) { diff --git a/Signum.Engine/DynamicQuery/ExpressionContainer.cs b/Signum.Engine/DynamicQuery/ExpressionContainer.cs index ba997d27e8..bd4aaf1987 100644 --- a/Signum.Engine/DynamicQuery/ExpressionContainer.cs +++ b/Signum.Engine/DynamicQuery/ExpressionContainer.cs @@ -73,9 +73,11 @@ public ExtensionInfo Register(Expression> lambdaToMethodOrPrope private static void AssertExtensionMethod(MethodInfo mi) { - if (mi.DeclaringType.Assembly == typeof(Enumerable).Assembly || - mi.DeclaringType.Assembly == typeof(Csv).Assembly || - mi.DeclaringType.Assembly == typeof(Lite).Assembly) + var assembly = mi.DeclaringType!.Assembly; + + if (assembly == typeof(Enumerable).Assembly || + assembly == typeof(Csv).Assembly || + assembly == typeof(Lite).Assembly) throw new InvalidOperationException("The parameter 'lambdaToMethod' should be an expression calling a expression method"); } diff --git a/Signum.Engine/Engine/ProgressExtensions.cs b/Signum.Engine/Engine/ProgressExtensions.cs index deb31b983a..4deb7c1d57 100644 --- a/Signum.Engine/Engine/ProgressExtensions.cs +++ b/Signum.Engine/Engine/ProgressExtensions.cs @@ -60,7 +60,7 @@ public static void ProgressForeach(this IEnumerable collection, if (elementID == null) { - elementID = e => e!.ToString(); + elementID = e => e!.ToString()!; } if (writer == null) writer = GetConsoleWriter(); @@ -150,7 +150,7 @@ private static void ProgressForeachSequential(this IEnumerable collection, catch (Exception e) { writer(ConsoleColor.Red, "{0:u} Error in {1}: {2}", DateTime.Now, elementID(item), e.Message); - writer(ConsoleColor.DarkRed, e.StackTrace.Indent(4)); + writer(ConsoleColor.DarkRed, e.StackTrace!.Indent(4)); if (StopOnException != null && StopOnException(elementID(item), e)) throw; @@ -213,7 +213,7 @@ Action action catch (Exception e) { writer(ConsoleColor.Red, "{0:u} Error in {1}: {2}", DateTime.Now, elementID(item), e.Message); - writer(ConsoleColor.DarkRed, e.StackTrace.Indent(4)); + writer(ConsoleColor.DarkRed, e.StackTrace!.Indent(4)); if (StopOnException != null && StopOnException(elementID(item), e)) stopException = e; diff --git a/Signum.Engine/Engine/SchemaGenerator.cs b/Signum.Engine/Engine/SchemaGenerator.cs index ee89dc8b45..718e62f552 100644 --- a/Signum.Engine/Engine/SchemaGenerator.cs +++ b/Signum.Engine/Engine/SchemaGenerator.cs @@ -37,7 +37,7 @@ public static class SchemaGenerator var mainIndices = allIndexes.Select(ix => SqlBuilder.CreateIndex(ix, checkUnique: null)).Combine(Spacing.Simple); var historyIndices = t.SystemVersioned == null ? null : - allIndexes.Where(a => a.GetType() == typeof(Index)).Select(mix => SqlBuilder.CreateIndexBasic(mix, forHistoryTable: true)).Combine(Spacing.Simple); + allIndexes.Where(a => a.GetType() == typeof(TableIndex)).Select(mix => SqlBuilder.CreateIndexBasic(mix, forHistoryTable: true)).Combine(Spacing.Simple); return SqlPreCommand.Combine(Spacing.Double, mainIndices, historyIndices); diff --git a/Signum.Engine/Engine/SchemaSynchronizer.cs b/Signum.Engine/Engine/SchemaSynchronizer.cs index d4245d7e5b..0a352cc6a2 100644 --- a/Signum.Engine/Engine/SchemaSynchronizer.cs +++ b/Signum.Engine/Engine/SchemaSynchronizer.cs @@ -16,7 +16,7 @@ public static class SchemaSynchronizer { public static Func DropSchema = s => !s.Name.Contains(@"\"); - public static Action> SimplifyDiffTables; + public static Action>? SimplifyDiffTables; public static SqlPreCommand? SynchronizeTablesScript(Replacements replacements) { @@ -40,7 +40,7 @@ public static class SchemaSynchronizer databaseTablesHistory = replacements.ApplyReplacementsToOld(databaseTablesHistory, Replacements.KeyTables); - Dictionary> modelIndices = modelTables.Values + Dictionary> modelIndices = modelTables.Values .ToDictionary(t => t, t => t.GeneratAllIndexes().ToDictionaryEx(a => a.IndexName, "Indexes for {0}".FormatWith(t.Name))); //To --> From @@ -136,7 +136,7 @@ public static class SchemaSynchronizer removeOld: (tn, dif) => dif.Indices.Values.Where(ix => !ix.IsPrimary).Select(ix => SqlBuilder.DropIndex(dif.Name, ix)).Combine(Spacing.Simple), mergeBoth: (tn, tab, dif) => { - Dictionary modelIxs = modelIndices[tab]; + Dictionary modelIxs = modelIndices[tab]; var removedColums = dif.Columns.Keys.Except(tab.Columns.Keys).ToHashSet(); @@ -157,12 +157,12 @@ public static class SchemaSynchronizer removeOld: (tn, dif) => dif.Indices.Values.Where(ix => ix.Type != DiffIndexType.Clustered).Select(ix => SqlBuilder.DropIndex(dif.Name, ix)).Combine(Spacing.Simple), mergeBoth: (tn, tab, dif) => { - Dictionary modelIxs = modelIndices[tab]; + Dictionary modelIxs = modelIndices[tab]; var removedColums = dif.Columns.Keys.Except(tab.Columns.Keys).ToHashSet(); var changes = Synchronizer.SynchronizeScript(Spacing.Simple, - modelIxs.Where(kvp => kvp.Value.GetType() == typeof(Index)).ToDictionary(), + modelIxs.Where(kvp => kvp.Value.GetType() == typeof(TableIndex)).ToDictionary(), dif.Indices.Where(kvp => kvp.Value.Type != DiffIndexType.Clustered).ToDictionary(), createNew: null, removeOld: (i, dix) => dix.Columns.Any(c => removedColums.Contains(c.ColumnName)) || dix.IsControlledIndex ? SqlBuilder.DropIndex(dif.Name, dix) : null, @@ -390,12 +390,12 @@ public static class SchemaSynchronizer Func isNew = c => !dif.Columns.ContainsKey(columnReplacements?.TryGetC(c.Name) ?? c.Name); - Dictionary modelIxs = modelIndices[tab]; + Dictionary modelIxs = modelIndices[tab]; var controlledIndexes = Synchronizer.SynchronizeScript(Spacing.Simple, modelIxs.Where(kvp => !(kvp.Value is PrimaryClusteredIndex)).ToDictionary(), dif.Indices.Where(kvp => !kvp.Value.IsPrimary).ToDictionary(), - createNew: (i, mix) => mix is UniqueIndex || mix.Columns.Any(isNew) || (replacements.Interactive ? SafeConsole.Ask(ref createMissingFreeIndexes, "Create missing non-unique index {0} in {1}?".FormatWith(mix.IndexName, tab.Name)) : true) ? SqlBuilder.CreateIndex(mix, checkUnique: replacements) : null, + createNew: (i, mix) => mix is UniqueTableIndex || mix.Columns.Any(isNew) || (replacements.Interactive ? SafeConsole.Ask(ref createMissingFreeIndexes, "Create missing non-unique index {0} in {1}?".FormatWith(mix.IndexName, tab.Name)) : true) ? SqlBuilder.CreateIndex(mix, checkUnique: replacements) : null, removeOld: null, mergeBoth: (i, mix, dix) => !dix.IndexEquals(dif, mix) ? SqlBuilder.CreateIndex(mix, checkUnique: replacements) : mix.IndexName != dix.IndexName ? SqlBuilder.RenameIndex(tab.Name, dix.IndexName, mix.IndexName) : null); @@ -405,7 +405,7 @@ public static class SchemaSynchronizer SqlPreCommand? addIndicesHistory = Synchronizer.SynchronizeScript(Spacing.Double, modelTablesHistory, databaseTablesHistory, - createNew: (tn, tab) => modelIndices[tab].Values.Where(a => a.GetType() == typeof(Index)).Select(mix => SqlBuilder.CreateIndexBasic(mix, forHistoryTable: true)).Combine(Spacing.Simple), + createNew: (tn, tab) => modelIndices[tab].Values.Where(a => a.GetType() == typeof(TableIndex)).Select(mix => SqlBuilder.CreateIndexBasic(mix, forHistoryTable: true)).Combine(Spacing.Simple), removeOld: null, mergeBoth: (tn, tab, dif) => { @@ -413,12 +413,12 @@ public static class SchemaSynchronizer Func isNew = c => !dif.Columns.ContainsKey(columnReplacements?.TryGetC(c.Name) ?? c.Name); - Dictionary modelIxs = modelIndices[tab]; + Dictionary modelIxs = modelIndices[tab]; var controlledIndexes = Synchronizer.SynchronizeScript(Spacing.Simple, - modelIxs.Where(kvp => kvp.Value.GetType() == typeof(Index)).ToDictionary(), + modelIxs.Where(kvp => kvp.Value.GetType() == typeof(TableIndex)).ToDictionary(), dif.Indices.Where(kvp => kvp.Value.Type != DiffIndexType.Clustered).ToDictionary(), - createNew: (i, mix) => mix is UniqueIndex || mix.Columns.Any(isNew) || (replacements.Interactive ? SafeConsole.Ask(ref createMissingFreeIndexes, "Create missing non-unique index {0} in {1}?".FormatWith(mix.IndexName, tab.Name)) : true) ? SqlBuilder.CreateIndexBasic(mix, forHistoryTable: true) : null, + createNew: (i, mix) => mix is UniqueTableIndex || mix.Columns.Any(isNew) || (replacements.Interactive ? SafeConsole.Ask(ref createMissingFreeIndexes, "Create missing non-unique index {0} in {1}?".FormatWith(mix.IndexName, tab.Name)) : true) ? SqlBuilder.CreateIndexBasic(mix, forHistoryTable: true) : null, removeOld: null, mergeBoth: (i, mix, dix) => !dix.IndexEquals(dif, mix) ? SqlBuilder.CreateIndexBasic(mix, forHistoryTable: true) : mix.IndexName != dix.IndexName ? SqlBuilder.RenameIndex(tab.SystemVersioned!.TableName, dix.IndexName, mix.IndexName) : null); @@ -651,7 +651,7 @@ public static string GetDefaultValue(ITable table, IColumn column, Replacements } - private static Dictionary ApplyIndexAutoReplacements(DiffTable diff, ITable tab, Dictionary dictionary) + private static Dictionary ApplyIndexAutoReplacements(DiffTable diff, ITable tab, Dictionary dictionary) { List oldOnly = diff.Indices.Keys.Where(n => !dictionary.ContainsKey(n)).ToList(); List newOnly = dictionary.Keys.Where(n => !diff.Indices.ContainsKey(n)).ToList(); @@ -673,10 +673,10 @@ private static Dictionary ApplyIndexAutoReplacements(DiffTabl if (oldIx.IsPrimary || newIx is PrimaryClusteredIndex) return false; - if (oldIx.IsUnique != (newIx is UniqueIndex)) + if (oldIx.IsUnique != (newIx is UniqueTableIndex)) return false; - if (oldIx.ViewName != null || (newIx is UniqueIndex) && ((UniqueIndex)newIx).ViewName != null) + if (oldIx.ViewName != null || (newIx is UniqueTableIndex) && ((UniqueTableIndex)newIx).ViewName != null) return false; var news = newIx.Columns.Select(c => diff.Columns.TryGetC(c.Name)?.Name).NotNull().ToHashSet(); @@ -990,7 +990,7 @@ from col in t.Columns.Values private static Entity Clone(Entity current) { - var instance = (Entity)Activator.CreateInstance(current.GetType()); + var instance = (Entity)Activator.CreateInstance(current.GetType())!; instance.toStr = current.toStr; instance.id = (int)current.id!.Value + 1000000; return instance; @@ -1123,9 +1123,9 @@ public override string ToString() return "{0} ({1})".FormatWith(IndexName, Columns.ToString(", ")); } - internal bool IndexEquals(DiffTable dif, Index mix) + internal bool IndexEquals(DiffTable dif, Maps.TableIndex mix) { - if (this.ViewName != (mix as UniqueIndex)?.ViewName) + if (this.ViewName != (mix as UniqueTableIndex)?.ViewName) return false; if (this.ColumnsChanged(dif, mix)) @@ -1140,9 +1140,9 @@ internal bool IndexEquals(DiffTable dif, Index mix) return true; } - private static DiffIndexType? GetIndexType(Index mix) + private static DiffIndexType? GetIndexType(TableIndex mix) { - if (mix is UniqueIndex && ((UniqueIndex)mix).ViewName != null) + if (mix is UniqueTableIndex && ((UniqueTableIndex)mix).ViewName != null) return null; if (mix is PrimaryClusteredIndex) @@ -1151,7 +1151,7 @@ internal bool IndexEquals(DiffTable dif, Index mix) return DiffIndexType.NonClustered; } - bool ColumnsChanged(DiffTable dif, Index mix) + bool ColumnsChanged(DiffTable dif, TableIndex mix) { bool sameCols = IdenticalColumns(dif, mix.Columns, this.Columns.Where(a => !a.IsIncluded).ToList()); bool sameIncCols = IdenticalColumns(dif, mix.IncludeColumns, this.Columns.Where(a => a.IsIncluded).ToList()); diff --git a/Signum.Engine/Engine/SqlBuilder.cs b/Signum.Engine/Engine/SqlBuilder.cs index 6321ca4f12..4afbbbd1ae 100644 --- a/Signum.Engine/Engine/SqlBuilder.cs +++ b/Signum.Engine/Engine/SqlBuilder.cs @@ -306,7 +306,7 @@ public static SqlPreCommand DropIndex(ObjectName objectName, string indexName) .FormatWith(objectName.Schema.Database.ToString().SqlEscape(), indexName.SqlEscape(), objectName.OnDatabase(null).ToString())); } - public static SqlPreCommand CreateIndex(Index index, Replacements? checkUnique) + public static SqlPreCommand CreateIndex(TableIndex index, Replacements? checkUnique) { if (index is PrimaryClusteredIndex) { @@ -315,7 +315,7 @@ public static SqlPreCommand CreateIndex(Index index, Replacements? checkUnique) return new SqlPreCommandSimple($"ALTER TABLE {index.Table.Name} ADD CONSTRAINT {index.IndexName} PRIMARY KEY CLUSTERED({columns})"); } - if (index is UniqueIndex uIndex) + if (index is UniqueTableIndex uIndex) { if (uIndex.ViewName != null) { @@ -346,7 +346,7 @@ public static SqlPreCommand CreateIndex(Index index, Replacements? checkUnique) } } - public static int DuplicateCount(UniqueIndex uniqueIndex, Replacements rep) + public static int DuplicateCount(UniqueTableIndex uniqueIndex, Replacements rep) { var primaryKey = uniqueIndex.Table.Columns.Values.Where(a => a.PrimaryKey).Only(); @@ -372,7 +372,7 @@ GROUP BY {oldColumns} ){(string.IsNullOrWhiteSpace(uniqueIndex.Where) ? "" : "AND " + uniqueIndex.Where.Replace(columnReplacement))}")!; } - public static SqlPreCommand? RemoveDuplicatesIfNecessary(UniqueIndex uniqueIndex, Replacements rep) + public static SqlPreCommand? RemoveDuplicatesIfNecessary(UniqueTableIndex uniqueIndex, Replacements rep) { try { @@ -408,7 +408,7 @@ GROUP BY {oldColumns} } } - private static SqlPreCommand RemoveDuplicates(UniqueIndex uniqueIndex, IColumn primaryKey, string columns, bool commentedOut) + private static SqlPreCommand RemoveDuplicates(UniqueTableIndex uniqueIndex, IColumn primaryKey, string columns, bool commentedOut) { return new SqlPreCommandSimple($@"DELETE {uniqueIndex.Table.Name} WHERE {primaryKey.Name} NOT IN @@ -420,9 +420,9 @@ GROUP BY {columns} ){(string.IsNullOrWhiteSpace(uniqueIndex.Where) ? "" : " AND " + uniqueIndex.Where)}".Let(txt => commentedOut ? txt.Indent(2, '-') : txt)); } - public static SqlPreCommand CreateIndexBasic(Index index, bool forHistoryTable) + public static SqlPreCommand CreateIndexBasic(Maps.TableIndex index, bool forHistoryTable) { - var indexType = index is UniqueIndex ? "UNIQUE INDEX" : "INDEX"; + var indexType = index is UniqueTableIndex ? "UNIQUE INDEX" : "INDEX"; var columns = index.Columns.ToString(c => c.Name.SqlEscape(), ", "); var include = index.IncludeColumns.HasItems() ? $" INCLUDE ({index.IncludeColumns.ToString(c => c.Name.SqlEscape(), ", ")})" : null; var where = index.Where.HasText() ? $" WHERE {index.Where}" : ""; diff --git a/Signum.Engine/Engine/SqlPreCommand.cs b/Signum.Engine/Engine/SqlPreCommand.cs index 41387d0ecd..1e9514d904 100644 --- a/Signum.Engine/Engine/SqlPreCommand.cs +++ b/Signum.Engine/Engine/SqlPreCommand.cs @@ -188,7 +188,7 @@ internal static string Encode(object value) if (value is byte[] bytes) return "0x" + BitConverter.ToString(bytes).Replace("-", ""); - return value.ToString(); + return value.ToString()!; } protected internal override void PlainSql(StringBuilder sb) diff --git a/Signum.Engine/Engine/Synchronizer.cs b/Signum.Engine/Engine/Synchronizer.cs index f61fbbce68..11612ff50a 100644 --- a/Signum.Engine/Engine/Synchronizer.cs +++ b/Signum.Engine/Engine/Synchronizer.cs @@ -53,7 +53,7 @@ public static void SynchronizeProgressForeach( HashSet keys = new HashSet(); keys.UnionWith(oldDictionary.Keys); keys.UnionWith(newDictionary.Keys); - keys.ProgressForeach(key => key.ToString(), key => + keys.ProgressForeach(key => key.ToString()!, key => { if (oldDictionary.TryGetValue(key, out var oldVal)) { @@ -327,7 +327,7 @@ public AutoReplacementContext(string replacementKey, string oldValue, List AutoReplacement; + public static Func? AutoReplacement; private static Selection SelectInteractive(string oldValue, List newValues, string replacementsKey, bool interactive) { diff --git a/Signum.Engine/EntityCache.cs b/Signum.Engine/EntityCache.cs index de11500ce6..a200d9c60e 100644 --- a/Signum.Engine/EntityCache.cs +++ b/Signum.Engine/EntityCache.cs @@ -6,6 +6,7 @@ using Signum.Utilities.DataStructures; using Signum.Entities.Reflection; using System.Linq.Expressions; +using System.Diagnostics.CodeAnalysis; namespace Signum.Engine { @@ -80,9 +81,7 @@ internal bool HasRetriever get{return retriever != null; } } - - - internal bool TryGetValue((Type type, PrimaryKey id) tuple, out Entity result) + internal bool TryGetValue((Type type, PrimaryKey id) tuple, [NotNullWhen(true)]out Entity? result) { return dic.TryGetValue(tuple, out result); } @@ -195,16 +194,8 @@ public static T Construct(PrimaryKey id) where T : Entity static class Constructor where T : Entity { - static Func call; - public static Func Call - { - get - { - if (call == null) - call = Expression.Lambda>(Expression.New(typeof(T))).Compile(); - return call; - } - } + static Func? call; + public static Func Call => call ??= Expression.Lambda>(Expression.New(typeof(T))).Compile(); } } diff --git a/Signum.Engine/Exceptions.cs b/Signum.Engine/Exceptions.cs index 8b760437d9..4dc4b88347 100644 --- a/Signum.Engine/Exceptions.cs +++ b/Signum.Engine/Exceptions.cs @@ -19,7 +19,7 @@ public class UniqueKeyException : ApplicationException public Table? Table { get; private set; } public string? IndexName { get; private set; } - public UniqueIndex? Index { get; private set; } + public UniqueTableIndex? Index { get; private set; } public List? Properties { get; private set; } public string? Values { get; private set; } @@ -49,7 +49,7 @@ public UniqueKeyException(Exception inner) : base(null, inner) { var tuple = cachedLookups.GetOrAdd((Table, IndexName), tup=> { - var index = tup.table.GeneratAllIndexes().OfType().FirstOrDefault(ix => ix.IndexName == tup.indexName); + var index = tup.table.GeneratAllIndexes().OfType().FirstOrDefault(ix => ix.IndexName == tup.indexName); if(index == null) return null; @@ -76,15 +76,15 @@ where cols.Any() && cols.All(c => index.Columns.Contains(c)) } static ConcurrentDictionary cachedTables = new ConcurrentDictionary(); - static ConcurrentDictionary<(Table table, string indexName), (UniqueIndex index, List properties)?> cachedLookups = - new ConcurrentDictionary<(Table table, string indexName), (UniqueIndex index, List properties)?>(); + static ConcurrentDictionary<(Table table, string indexName), (UniqueTableIndex index, List properties)?> cachedLookups = + new ConcurrentDictionary<(Table table, string indexName), (UniqueTableIndex index, List properties)?>(); public override string Message { get { if (Table == null) - return InnerException.Message; + return InnerException!.Message; return EngineMessage.TheresAlreadyA0With1EqualsTo2_G.NiceToString().ForGenderAndNumber(Table?.Type.GetGender()).FormatWith( Table == null ? TableName : Table.Type.NiceName(), @@ -160,7 +160,7 @@ public override string Message get { if (TableName == null) - return InnerException.Message; + return InnerException!.Message; if (IsInsert) return (TableType == null || ReferedTableType == null) ? diff --git a/Signum.Engine/Linq/AliasGenerator.cs b/Signum.Engine/Linq/AliasGenerator.cs index 3dd9bff0ad..48b8dce4e0 100644 --- a/Signum.Engine/Linq/AliasGenerator.cs +++ b/Signum.Engine/Linq/AliasGenerator.cs @@ -86,7 +86,7 @@ public bool Equals(Alias other) return this.Name == other.Name && object.Equals(this.ObjectName, other.ObjectName); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is Alias && base.Equals((Alias)obj); } diff --git a/Signum.Engine/Linq/DbExpressions.Sql.cs b/Signum.Engine/Linq/DbExpressions.Sql.cs index c13393c3bd..f9fd68a0e6 100644 --- a/Signum.Engine/Linq/DbExpressions.Sql.cs +++ b/Signum.Engine/Linq/DbExpressions.Sql.cs @@ -239,7 +239,7 @@ public override string ToString() return "{0}.{1}".FormatWith(Alias, Name); } - public override bool Equals(object obj) => obj is ColumnExpression ce && Equals(ce); + public override bool Equals(object? obj) => obj is ColumnExpression ce && Equals(ce); public bool Equals(ColumnExpression other) { return other != null && other.Alias == Alias && other.Name == Name; diff --git a/Signum.Engine/Linq/ExpressionVisitor/ChildProjectionFlattener.cs b/Signum.Engine/Linq/ExpressionVisitor/ChildProjectionFlattener.cs index 37ce37f255..3a7f4c04bc 100644 --- a/Signum.Engine/Linq/ExpressionVisitor/ChildProjectionFlattener.cs +++ b/Signum.Engine/Linq/ExpressionVisitor/ChildProjectionFlattener.cs @@ -67,7 +67,7 @@ protected internal override Expression VisitProjection(ProjectionExpression proj ConstantExpression key = Expression.Constant(0); Type kvpType = typeof(KeyValuePair<,>).MakeGenericType(key.Type, projector.Type); - ConstructorInfo ciKVP = kvpType.GetConstructor(new[] { key.Type, projector.Type }); + ConstructorInfo ciKVP = kvpType.GetConstructor(new[] { key.Type, projector.Type })!; Type projType = proj.UniqueFunction == null ? typeof(IEnumerable<>).MakeGenericType(kvpType) : kvpType; var childProj = new ProjectionExpression(proj.Select, @@ -132,7 +132,7 @@ protected internal override Expression VisitProjection(ProjectionExpression proj Expression key = TupleReflection.TupleChainConstructor(columnsSMExternal.Select(cd => cd.GetReference(aliasSM).Nullify())); Type kvpType = typeof(KeyValuePair<,>).MakeGenericType(key.Type, projector.Type); - ConstructorInfo ciKVP = kvpType.GetConstructor(new[] { key.Type, projector.Type }); + ConstructorInfo ciKVP = kvpType.GetConstructor(new[] { key.Type, projector.Type })!; Type projType = proj.UniqueFunction == null ? typeof(IEnumerable<>).MakeGenericType(kvpType) : kvpType; var childProj = new ProjectionExpression(selectMany, diff --git a/Signum.Engine/Linq/ExpressionVisitor/ColumnProjector.cs b/Signum.Engine/Linq/ExpressionVisitor/ColumnProjector.cs index 57bc2bcb2f..6e5ba0f576 100644 --- a/Signum.Engine/Linq/ExpressionVisitor/ColumnProjector.cs +++ b/Signum.Engine/Linq/ExpressionVisitor/ColumnProjector.cs @@ -66,7 +66,7 @@ public override Expression Visit(Expression expression) return expression; ColumnExpression column = (ColumnExpression)expression; - if (this.map.TryGetValue(column, out ColumnExpression mapped)) + if (this.map.TryGetValue(column, out var mapped)) { return mapped; } @@ -124,7 +124,7 @@ public override Expression Visit(Expression expression) { if (expression is ColumnExpression column) { - if (this.map.TryGetValue(column, out ColumnExpression mapped)) + if (this.map.TryGetValue(column, out var mapped)) { return mapped; } diff --git a/Signum.Engine/Linq/ExpressionVisitor/DbExpressionNominator.cs b/Signum.Engine/Linq/ExpressionVisitor/DbExpressionNominator.cs index cb5e9e432f..fd9ac3ca47 100644 --- a/Signum.Engine/Linq/ExpressionVisitor/DbExpressionNominator.cs +++ b/Signum.Engine/Linq/ExpressionVisitor/DbExpressionNominator.cs @@ -1160,7 +1160,7 @@ protected override Expression VisitMember(MemberExpression m) public Expression? HardCodedMembers(MemberExpression m) { - switch (m.Member.DeclaringType.TypeName() + "." + m.Member.Name) + switch (m.Member.DeclaringType!.TypeName() + "." + m.Member.Name) { case "string.Length": return TrySqlFunction(null, SqlFunction.LEN, m.Type, m.Expression); case "Math.PI": return TrySqlFunction(null, SqlFunction.PI, m.Type); @@ -1217,7 +1217,7 @@ protected override Expression VisitMember(MemberExpression m) if (result != null) return result; - SqlMethodAttribute sma = m.Method.GetCustomAttribute(); + SqlMethodAttribute? sma = m.Method.GetCustomAttribute(); if (sma != null) using (ForceFullNominate()) return TrySqlFunction(m.Object, sma.Name ?? m.Method.Name, m.Type, m.Arguments.ToArray()); @@ -1255,7 +1255,7 @@ protected override Expression VisitMember(MemberExpression m) return VisitBinary(Expression.Equal(obj, arg)); } - switch (m.Method.DeclaringType.TypeName() + "." + m.Method.Name) + switch (m.Method.DeclaringType!.TypeName() + "." + m.Method.Name) { case "string.IndexOf": { diff --git a/Signum.Engine/Linq/ExpressionVisitor/OverloadingSimplifier.cs b/Signum.Engine/Linq/ExpressionVisitor/OverloadingSimplifier.cs index 983bf957a1..0bcf72b3b2 100644 --- a/Signum.Engine/Linq/ExpressionVisitor/OverloadingSimplifier.cs +++ b/Signum.Engine/Linq/ExpressionVisitor/OverloadingSimplifier.cs @@ -95,7 +95,7 @@ internal class OverloadingSimplifier : ExpressionVisitor protected override Expression VisitMethodCall(MethodCallExpression m) { - Type decType = m.Method.DeclaringType; + Type decType = m.Method.DeclaringType!; if (m.Method.IsGenericMethod && (decType == typeof(Queryable) || decType == typeof(Enumerable))) { bool query = decType == typeof(Queryable); diff --git a/Signum.Engine/Linq/ExpressionVisitor/QueryBinder.cs b/Signum.Engine/Linq/ExpressionVisitor/QueryBinder.cs index 5dfbb82cbb..dbb0e43527 100644 --- a/Signum.Engine/Linq/ExpressionVisitor/QueryBinder.cs +++ b/Signum.Engine/Linq/ExpressionVisitor/QueryBinder.cs @@ -184,11 +184,11 @@ public Expression BindQuery(Expression expression) var converted = EntityCasting(entity, Lite.Extract(m.Type)!)!; return MakeLite(converted, toStr); } - else if (m.Method.DeclaringType.IsInstantiationOf(typeof(EnumEntity<>)) && m.Method.Name == "ToEnum") + else if (m.Method.DeclaringType!.IsInstantiationOf(typeof(EnumEntity<>)) && m.Method.Name == "ToEnum") { EntityExpression fi = (EntityExpression)Visit(m.Object); - return Expression.Convert((ColumnExpression)fi.ExternalId.Value, m.Method.DeclaringType.GetGenericArguments()[0]); + return Expression.Convert((ColumnExpression)fi.ExternalId.Value, m.Method.DeclaringType!.GetGenericArguments()[0]); } else if (m.Object != null && typeof(IEnumerable).IsAssignableFrom(m.Method.DeclaringType) && typeof(string) != m.Method.DeclaringType && m.Method.Name == "Contains") { @@ -279,7 +279,7 @@ private Expression ChangeProjector(int index, MemberInfo[] members, Expression p ee = Completed(ee); - var fi = m as FieldInfo ?? Reflector.FindFieldInfo(m.DeclaringType, (PropertyInfo)m); + var fi = m as FieldInfo ?? Reflector.FindFieldInfo(m.DeclaringType!, (PropertyInfo)m); var newBinding = ChangeProjector(index + 1, members, ee.GetBinding(fi), changeExpression); @@ -593,7 +593,7 @@ private Expression BindToString(Expression source, Expression separator, MethodI OverloadingSimplifier.miWhereQ : OverloadingSimplifier.miWhereE; - source = Expression.Call(miWhere.MakeGenericMethod(source.Type.ElementType()), source, selectorOrPredicate); + source = Expression.Call(miWhere.MakeGenericMethod(source.Type.ElementType()!), source, selectorOrPredicate); selectorOrPredicate = null; } @@ -789,7 +789,7 @@ bool ExtractDistinct(Expression? source, out Expression? innerSource) aggregate = (Expression)Expression.Coalesce( new AggregateExpression(GetBasicType(nominated), nominated, aggregateFunction, distinct), - new SqlConstantExpression(Activator.CreateInstance(nominated.Type.UnNullify()))); + new SqlConstantExpression(Activator.CreateInstance(nominated.Type.UnNullify())!)); } else { @@ -1322,7 +1322,7 @@ private ProjectionExpression GetTableValuedFunctionProjection(MethodCallExpressi Expression exp = table.GetProjectorExpression(tableAlias, this); - var functionName = mce.Method.GetCustomAttribute().Name ?? mce.Method.Name; + var functionName = mce.Method.GetCustomAttribute()?.Name ?? mce.Method.Name; var argumens = mce.Arguments.Select(a => DbExpressionNominator.FullNominate(a)!).ToList(); @@ -1600,7 +1600,7 @@ private ConditionalExpression DispatchConditional(MethodCallExpression m, Expres { if (nex.Members == null) { - int index = nex.Constructor.GetParameters().IndexOf(p => p.Name.Equals(m.Member.Name, StringComparison.InvariantCultureIgnoreCase)); + int index = nex.Constructor.GetParameters().IndexOf(p => p.Name!.Equals(m.Member.Name, StringComparison.InvariantCultureIgnoreCase)); if (index == -1) throw new InvalidOperationException("Impossible to bind '{0}' on '{1}'".FormatWith(m.Member.Name, nex.Constructor.ConstructorSignature())); @@ -1609,7 +1609,7 @@ private ConditionalExpression DispatchConditional(MethodCallExpression m, Expres } PropertyInfo pi = (PropertyInfo)m.Member; - return nex.Members.Zip(nex.Arguments).SingleEx(p => ReflectionTools.PropertyEquals((PropertyInfo)p.first, pi)).second; + return nex.Members.Zip(nex.Arguments).SingleEx(p => ReflectionTools.PropertyEquals((PropertyInfo)p.First, pi)).Second; } break; } @@ -2839,7 +2839,7 @@ internal ProjectionExpression MListProjection(MListExpression mle, bool withRowI ); var projectType = withRowId ? - typeof(IEnumerable<>).MakeGenericType(typeof(MList<>.RowIdElement).MakeGenericType(mle.Type.ElementType())) : + typeof(IEnumerable<>).MakeGenericType(typeof(MList<>.RowIdElement).MakeGenericType(mle.Type.ElementType()!)) : mle.Type; var proj = new ProjectionExpression( diff --git a/Signum.Engine/Linq/ExpressionVisitor/SmartEqualizer.cs b/Signum.Engine/Linq/ExpressionVisitor/SmartEqualizer.cs index f5ec035b3a..1ecebea1ad 100644 --- a/Signum.Engine/Linq/ExpressionVisitor/SmartEqualizer.cs +++ b/Signum.Engine/Linq/ExpressionVisitor/SmartEqualizer.cs @@ -167,7 +167,7 @@ private static Expression RemoveConvertChain(Expression exp) var ci = type.GetConstructors().SingleEx(); - return Expression.New(ci, ci.GetParameters().Select(p => Expression.Constant(values.GetOrThrow(p.Name), p.ParameterType))); + return Expression.New(ci, ci.GetParameters().Select(p => Expression.Constant(values.GetOrThrow(p.Name!), p.ParameterType))); } public static Expression? PrimaryKeyEquals(Expression exp1, Expression exp2) diff --git a/Signum.Engine/Linq/ExpressionVisitor/TranslatorBuilder.cs b/Signum.Engine/Linq/ExpressionVisitor/TranslatorBuilder.cs index b84e75fa0e..0462541a29 100644 --- a/Signum.Engine/Linq/ExpressionVisitor/TranslatorBuilder.cs +++ b/Signum.Engine/Linq/ExpressionVisitor/TranslatorBuilder.cs @@ -85,6 +85,7 @@ static IChildProjection BuildChild(ChildProjectionExpression childProj) static readonly GenericInvoker> giLazyChild = new GenericInvoker>((proj, scope, token, sql) => LazyChild(proj, scope, token, sql)); static IChildProjection LazyChild(Expression projector, Scope scope, LookupToken token, SqlPreCommandSimple command) + where K : notnull { var proj = ProjectionBuilder.Build.RowIdElement>>(projector, scope); return new LazyChildProjection(token, command, proj); @@ -457,7 +458,7 @@ protected internal override Expression VisitLiteValue(LiteValueExpression lite) if (toStr != null) return Expression.Call(retriever, miModifiablePostRetrieving.MakeGenericMethod(typeof(LiteImp)), liteConstructor.TryConvert(typeof(LiteImp))).TryConvert(liteConstructor.Type); else - return Expression.Call(retriever, miRequestLite.MakeGenericMethod(Lite.Extract(lite.Type)), liteConstructor); + return Expression.Call(retriever, miRequestLite.MakeGenericMethod(Lite.Extract(lite.Type)!), liteConstructor); } static readonly MethodInfo miLiteCreateParse = ReflectionTools.GetMethodInfo(() => LiteCreateParse(null!, null, null!, null!)); @@ -628,7 +629,7 @@ public Expression LookupMList(Expression row, ChildProjectionExpression cProj, M if (cProj.Projection.UniqueFunction != null) throw new InvalidOperationException("Lazy ChildProyection with UniqueFunction '{0}'".FormatWith(cProj.Projection.UniqueFunction)); - MethodInfo mi = miLookupRequest.MakeGenericMethod(cProj.OuterKey.Type, cProj.Type.ElementType()); + MethodInfo mi = miLookupRequest.MakeGenericMethod(cProj.OuterKey.Type, cProj.Type.ElementType()!); return Expression.Call(row, mi, Expression.Constant(cProj.Token), cProj.OuterKey, field); } diff --git a/Signum.Engine/Linq/Meta/MetadataVisitor.cs b/Signum.Engine/Linq/Meta/MetadataVisitor.cs index bdd6dae2d5..9e9c39f0ac 100644 --- a/Signum.Engine/Linq/Meta/MetadataVisitor.cs +++ b/Signum.Engine/Linq/Meta/MetadataVisitor.cs @@ -433,7 +433,7 @@ static Expression BindMember(Expression source, MemberInfo member, Type memberTy if (nex.Members != null) { PropertyInfo pi = (PropertyInfo)member; - return nex.Members.Zip(nex.Arguments).SingleEx(p => ReflectionTools.PropertyEquals((PropertyInfo)p.first, pi)).second; + return nex.Members.Zip(nex.Arguments).SingleEx(p => ReflectionTools.PropertyEquals((PropertyInfo)p.First, pi)).Second; } break; } diff --git a/Signum.Engine/Linq/ProjectionReader.cs b/Signum.Engine/Linq/ProjectionReader.cs index 0b8f2e4f0b..862b2bfd2a 100644 --- a/Signum.Engine/Linq/ProjectionReader.cs +++ b/Signum.Engine/Linq/ProjectionReader.cs @@ -25,7 +25,7 @@ public interface IProjectionRow IRetriever Retriever { get; } IEnumerable Lookup(LookupToken token, K key); - MList LookupRequest(LookupToken token, K key, MList field); + MList LookupRequest(LookupToken token, K key, MList field) where K :notnull; } internal class ProjectionRowEnumerator : IProjectionRow, IEnumerator @@ -99,6 +99,7 @@ public IEnumerable Lookup(LookupToken token, K key) } public MList LookupRequest(LookupToken token, K key, MList field) + where K : notnull { Dictionary> dictionary = (Dictionary>)lookups.GetOrCreate(token, () => (IEnumerable)new Dictionary>()); diff --git a/Signum.Engine/Linq/TranslateResult.cs b/Signum.Engine/Linq/TranslateResult.cs index 63d8c465b4..ce8f8619ce 100644 --- a/Signum.Engine/Linq/TranslateResult.cs +++ b/Signum.Engine/Linq/TranslateResult.cs @@ -108,6 +108,7 @@ public bool IsLazy class LazyChildProjection : IChildProjection + where K : notnull { public LookupToken Token { get; } diff --git a/Signum.Engine/LinqExpandHints.cs b/Signum.Engine/LinqExpandHints.cs index cf76196200..5e55331cbe 100644 --- a/Signum.Engine/LinqExpandHints.cs +++ b/Signum.Engine/LinqExpandHints.cs @@ -14,7 +14,7 @@ public static IQueryable ExpandLite(this IQueryable source, Expressi if (source == null) throw new ArgumentNullException("query"); - return source.Provider.CreateQuery(Expression.Call(null, ((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(new Type[] { typeof(T), typeof(L) }), new Expression[] { source.Expression, Expression.Quote(liteSelector), Expression.Constant(expandLite) })); + return source.Provider.CreateQuery(Expression.Call(null, ((MethodInfo)MethodBase.GetCurrentMethod()!).MakeGenericMethod(new Type[] { typeof(T), typeof(L) }), new Expression[] { source.Expression, Expression.Quote(liteSelector), Expression.Constant(expandLite) })); } public static IQueryable ExpandEntity(this IQueryable source, Expression> entitySelector, ExpandEntity expandEntity) @@ -23,7 +23,7 @@ public static IQueryable ExpandEntity(this IQueryable source, Expres if (source == null) throw new ArgumentNullException("query"); - return source.Provider.CreateQuery(Expression.Call(null, ((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(new Type[] { typeof(T), typeof(L) }), new Expression[] { source.Expression, Expression.Quote(entitySelector), Expression.Constant(expandEntity) })); + return source.Provider.CreateQuery(Expression.Call(null, ((MethodInfo)MethodBase.GetCurrentMethod()!).MakeGenericMethod(new Type[] { typeof(T), typeof(L) }), new Expression[] { source.Expression, Expression.Quote(entitySelector), Expression.Constant(expandEntity) })); } } diff --git a/Signum.Engine/Operations/GraphState.cs b/Signum.Engine/Operations/GraphState.cs index 677c4a78eb..c68958995f 100644 --- a/Signum.Engine/Operations/GraphState.cs +++ b/Signum.Engine/Operations/GraphState.cs @@ -281,7 +281,7 @@ protected Graph() throw new InvalidOperationException("OperationGraphs should not be instantiated"); } - static Expression> getState; + static Expression> getState = null!; public static Expression> GetState { get { return getState; } @@ -292,11 +292,11 @@ public static Expression> GetState } } - public static Func GetStateFunc{get; private set;} + public static Func GetStateFunc { get; private set; } = null!; - public static Action EnterState { get; set; } - public static Action ExitState { get; set; } + public static Action? EnterState { get; set; } + public static Action? ExitState { get; set; } @@ -328,7 +328,7 @@ void Add(string from, string to, OperationSymbol key) foreach (var f in gOp.FromStates) foreach (var t in gOp.ToStates) - Add(f!.ToString(), t!.ToString(), item.OperationSymbol); + Add(f!.ToString()!, t!.ToString()!, item.OperationSymbol); } break; @@ -336,7 +336,7 @@ void Add(string from, string to, OperationSymbol key) { Delete dOp = (Delete)item; foreach (var f in dOp.FromStates) - Add(f!.ToString(), "[Deleted]", item.OperationSymbol); + Add(f!.ToString()!, "[Deleted]", item.OperationSymbol); } break; @@ -350,7 +350,7 @@ void Add(string from, string to, OperationSymbol key) var dtoState = (IGraphToStateOperation)item; foreach (var t in dtoState.ToStates) - Add(from, t!.ToString(), item.OperationSymbol); + Add(from, t!.ToString()!, item.OperationSymbol); } break; } diff --git a/Signum.Engine/Operations/OperationLogic.cs b/Signum.Engine/Operations/OperationLogic.cs index 437c1a305e..bc9b3d69b3 100644 --- a/Signum.Engine/Operations/OperationLogic.cs +++ b/Signum.Engine/Operations/OperationLogic.cs @@ -205,8 +205,8 @@ static void EntityEventsGlobal_Saving(Entity ident) #region Events - public static event SurroundOperationHandler SurroundOperation; - public static event AllowOperationHandler AllowOperation; + public static event SurroundOperationHandler? SurroundOperation; + public static event AllowOperationHandler? AllowOperation; internal static IDisposable? OnSuroundOperation(IOperation operation, OperationLogEntity log, IEntity? entity, object[]? args) { diff --git a/Signum.Engine/Retriever.cs b/Signum.Engine/Retriever.cs index c398835d20..33a6f1bd35 100644 --- a/Signum.Engine/Retriever.cs +++ b/Signum.Engine/Retriever.cs @@ -9,6 +9,7 @@ using System.Threading; using System.Threading.Tasks; using Signum.Utilities.ExpressionTrees; +using System.Diagnostics.CodeAnalysis; namespace Signum.Engine { @@ -50,9 +51,9 @@ public RealRetriever(EntityCache.RealEntityCache entityCache) Dictionary<(Type type, PrimaryKey id), List>>? liteRequests; List modifiablePostRetrieving = new List(); - bool TryGetRequest((Type type, PrimaryKey id) key, out Entity value) + bool TryGetRequest((Type type, PrimaryKey id) key, [NotNullWhen(true)]out Entity? value) { - if (requests != null && requests.TryGetValue(key.type, out Dictionary dic) && dic.TryGetValue(key.id, out value)) + if (requests != null && requests.TryGetValue(key.type, out var dic) && dic.TryGetValue(key.id, out value)) return true; value = null!; @@ -66,7 +67,7 @@ bool TryGetRequest((Type type, PrimaryKey id) key, out Entity value) var tuple = (typeof(T), id.Value); - if (entityCache.TryGetValue(tuple, out Entity result)) + if (entityCache.TryGetValue(tuple, out var result)) return (T)result; if (retrieved.TryGetValue(tuple, out result)) diff --git a/Signum.Engine/Schema/EntityEvents.cs b/Signum.Engine/Schema/EntityEvents.cs index 8eb35b80fd..f992d943fe 100644 --- a/Signum.Engine/Schema/EntityEvents.cs +++ b/Signum.Engine/Schema/EntityEvents.cs @@ -12,24 +12,24 @@ namespace Signum.Engine.Maps public class EntityEvents : IEntityEvents where T : Entity { - public event PreSavingEventHandler PreSaving; - public event SavingEventHandler Saving; - public event SavedEventHandler Saved; + public event PreSavingEventHandler? PreSaving; + public event SavingEventHandler? Saving; + public event SavedEventHandler? Saved; - public event AlternativeRetriveEventHandler AlternativeRetrive; - public event RetrievedEventHandler Retrieved; + public event AlternativeRetriveEventHandler? AlternativeRetrive; + public event RetrievedEventHandler? Retrieved; public CacheControllerBase? CacheController { get; set; } - public event FilterQueryEventHandler FilterQuery; + public event FilterQueryEventHandler? FilterQuery; - public event PreUnsafeDeleteHandler PreUnsafeDelete; - public event PreUnsafeMListDeleteHandler PreUnsafeMListDelete; + public event PreUnsafeDeleteHandler? PreUnsafeDelete; + public event PreUnsafeMListDeleteHandler? PreUnsafeMListDelete; - public event PreUnsafeUpdateHandler PreUnsafeUpdate; + public event PreUnsafeUpdateHandler? PreUnsafeUpdate; - public event PreUnsafeInsertHandler PreUnsafeInsert; - public event BulkInsetHandler PreBulkInsert; + public event PreUnsafeInsertHandler? PreUnsafeInsert; + public event BulkInsetHandler? PreBulkInsert; public Dictionary? AdditionalBindings { get; private set; } diff --git a/Signum.Engine/Schema/ObjectName.cs b/Signum.Engine/Schema/ObjectName.cs index 5ac881516a..1222980106 100644 --- a/Signum.Engine/Schema/ObjectName.cs +++ b/Signum.Engine/Schema/ObjectName.cs @@ -32,17 +32,12 @@ public override string ToString() return Name.SqlEscape(); } + public override bool Equals(object? obj) => obj is ServerName sn && Equals(sn); public bool Equals(ServerName other) { return other.Name == Name; } - public override bool Equals(object obj) - { - var db = obj as ServerName; - return db != null && Equals(db); - } - public override int GetHashCode() { return Name.GetHashCode(); @@ -84,16 +79,11 @@ public override string ToString() return Server.ToString() + "." + name; } - public bool Equals(DatabaseName other) - { - return other.Name == Name && - object.Equals(Server, other.Server); - } - public override bool Equals(object obj) + public override bool Equals(object? obj) => obj is DatabaseName dn && Equals(dn); + public bool Equals(DatabaseName other) { - var db = obj as DatabaseName; - return db != null && Equals(db); + return other.Name == Name && object.Equals(Server, other.Server); } public override int GetHashCode() @@ -155,18 +145,13 @@ public override string ToString() return Database.ToString() + "." + result; } + public override bool Equals(object? obj) => obj is SchemaName sn && Equals(sn); public bool Equals(SchemaName other) { return other.Name == Name && object.Equals(Database, other.Database); } - public override bool Equals(object obj) - { - var sc = obj as SchemaName; - return sc != null && Equals(sc); - } - public override int GetHashCode() { return Name.GetHashCode() ^ (Database == null ? 0 : Database.GetHashCode()); @@ -201,18 +186,13 @@ public override string ToString() return Schema.ToString() + "." + Name.SqlEscape(); } + public override bool Equals(object? obj) => obj is ObjectName on && Equals(on); public bool Equals(ObjectName other) { return other.Name == Name && object.Equals(Schema, other.Schema); } - public override bool Equals(object obj) - { - var sc = obj as ObjectName; - return sc != null && Equals(sc); - } - public override int GetHashCode() { return Name.GetHashCode() ^ Schema.GetHashCode(); diff --git a/Signum.Engine/Schema/Schema.Basics.cs b/Signum.Engine/Schema/Schema.Basics.cs index 4254de023f..cc15a85eef 100644 --- a/Signum.Engine/Schema/Schema.Basics.cs +++ b/Signum.Engine/Schema/Schema.Basics.cs @@ -28,9 +28,9 @@ public interface ITable Dictionary Columns { get; } - List? MultiColumnIndexes { get; set; } + List? MultiColumnIndexes { get; set; } - List GeneratAllIndexes(); + List GeneratAllIndexes(); void GenerateColumns(); @@ -118,7 +118,7 @@ public partial class Table : IFieldFinder, ITable, ITablePrivate public Dictionary Columns { get; set; } - public List? MultiColumnIndexes { get; set; } + public List? MultiColumnIndexes { get; set; } #pragma warning disable CS8618 // Non-nullable field is uninitialized. public Table(Type type) @@ -215,7 +215,7 @@ public Field GetField(MemberInfo member) return field.Field; } - public List GeneratAllIndexes() + public List GeneratAllIndexes() { IEnumerable fields = Fields.Values.AsEnumerable(); if (Mixins != null) @@ -226,22 +226,22 @@ public List GeneratAllIndexes() if (MultiColumnIndexes != null) result.AddRange(MultiColumnIndexes); - if (result.OfType().Any()) + if (result.OfType().Any()) { var s = Schema.Current.Settings; List attachedFields = fields.Where(f => s.FieldAttributes(PropertyRoute.Root(this.Type).Add(f.FieldInfo)).OfType().Any()) - .SelectMany(f => Index.GetColumnsFromFields(f.Field)) + .SelectMany(f => TableIndex.GetColumnsFromFields(f.Field)) .ToList(); if (attachedFields.Any()) { result = result.Select(ix => { - var ui = ix as UniqueIndex; + var ui = ix as UniqueTableIndex; if (ui == null || ui.AvoidAttachToUniqueIndexes) return ix; - return new UniqueIndex(ui.Table, ui.Columns.Concat(attachedFields).ToArray()) + return new UniqueTableIndex(ui.Table, ui.Columns.Concat(attachedFields).ToArray()) { Where = ui.Where }; @@ -251,7 +251,7 @@ public List GeneratAllIndexes() if(this.SystemVersioned != null) { - result.Add(new Index(this, this.SystemVersioned.Columns().PreAnd(this.PrimaryKey).ToArray())); + result.Add(new TableIndex(this, this.SystemVersioned.Columns().PreAnd(this.PrimaryKey).ToArray())); } return result; @@ -319,7 +319,7 @@ public abstract partial class Field { public Type FieldType { get; private set; } public PropertyRoute Route { get; private set; } - public UniqueIndex? UniqueIndex { get; set; } + public UniqueTableIndex? UniqueIndex { get; set; } public Field(PropertyRoute route, Type? fieldType = null) { @@ -330,20 +330,20 @@ public Field(PropertyRoute route, Type? fieldType = null) public abstract IEnumerable Columns(); - public virtual IEnumerable GenerateIndexes(ITable table) + public virtual IEnumerable GenerateIndexes(ITable table) { if (UniqueIndex == null) - return Enumerable.Empty(); + return Enumerable.Empty(); return new[] { UniqueIndex }; } - public virtual UniqueIndex? GenerateUniqueIndex(ITable table, UniqueIndexAttribute? attribute) + public virtual UniqueTableIndex? GenerateUniqueIndex(ITable table, UniqueIndexAttribute? attribute) { if (attribute == null) return null; - var result = new UniqueIndex(table, Index.GetColumnsFromFields(this)) + var result = new UniqueTableIndex(table, TableIndex.GetColumnsFromFields(this)) { AvoidAttachToUniqueIndexes = attribute.AvoidAttachToUniqueIndexes }; @@ -478,7 +478,7 @@ public override IEnumerable Columns() return new[] { this }; } - public override IEnumerable GenerateIndexes(ITable table) + public override IEnumerable GenerateIndexes(ITable table) { if (this.UniqueIndex != null) throw new InvalidOperationException("Changing IndexType is not allowed for FieldPrimaryKey"); @@ -641,7 +641,7 @@ public override IEnumerable Columns() return result; } - public override IEnumerable GenerateIndexes(ITable table) + public override IEnumerable GenerateIndexes(ITable table) { return this.EmbeddedFields.Values.SelectMany(f => f.Field.GenerateIndexes(table)); } @@ -723,7 +723,7 @@ public override IEnumerable Columns() return result; } - public override IEnumerable GenerateIndexes(ITable table) + public override IEnumerable GenerateIndexes(ITable table) { throw new InvalidOperationException(); } @@ -804,10 +804,10 @@ internal override IEnumerable> GetTables() }); } - public override IEnumerable GenerateIndexes(ITable table) + public override IEnumerable GenerateIndexes(ITable table) { if (UniqueIndex == null) - return new[] { new Index(table, (IColumn)this) }; + return new[] { new TableIndex(table, (IColumn)this) }; return base.GenerateIndexes(table); } @@ -911,9 +911,9 @@ internal override IEnumerable> GetTables() })); } - public override IEnumerable GenerateIndexes(ITable table) + public override IEnumerable GenerateIndexes(ITable table) { - return this.Columns().Select(c => new Index(table, c)).Concat(base.GenerateIndexes(table)); + return this.Columns().Select(c => new TableIndex(table, c)).Concat(base.GenerateIndexes(table)); } bool clearEntityOnSaving; @@ -982,10 +982,10 @@ public bool ClearEntityOnSaving } } - public override IEnumerable GenerateIndexes(ITable table) + public override IEnumerable GenerateIndexes(ITable table) { if (UniqueIndex == null) - return new[] { new Index(table, (IColumn)this.Column, (IColumn)this.ColumnType) }; + return new[] { new TableIndex(table, (IColumn)this.Column, (IColumn)this.ColumnType) }; return base.GenerateIndexes(table); } @@ -1079,12 +1079,12 @@ public override IEnumerable Columns() return new IColumn[0]; } - public override IEnumerable GenerateIndexes(ITable table) + public override IEnumerable GenerateIndexes(ITable table) { if (UniqueIndex != null) throw new InvalidOperationException("Changing IndexType is not allowed for FieldMList"); - return Enumerable.Empty(); + return Enumerable.Empty(); } internal override IEnumerable> GetTables() @@ -1130,7 +1130,7 @@ public PrimaryKeyColumn(Type type, string name) } public Dictionary Columns { get; set; } - public List? MultiColumnIndexes { get; set; } + public List? MultiColumnIndexes { get; set; } public ObjectName Name { get; set; } public PrimaryKeyColumn PrimaryKey { get; set; } @@ -1177,9 +1177,9 @@ public void GenerateColumns() Columns = cols.ToDictionary(a => a.Name); } - public List GeneratAllIndexes() + public List GeneratAllIndexes() { - var result = new List + var result = new List { new PrimaryClusteredIndex(this) }; diff --git a/Signum.Engine/Schema/Schema.Expressions.cs b/Signum.Engine/Schema/Schema.Expressions.cs index c5bf5262a6..a8675539f3 100644 --- a/Signum.Engine/Schema/Schema.Expressions.cs +++ b/Signum.Engine/Schema/Schema.Expressions.cs @@ -42,7 +42,7 @@ internal Expression GetProjectorExpression(Alias tableAlias, QueryBinder binder) } } - internal static ConstructorInfo intervalConstructor = typeof(Interval).GetConstructor(new[] { typeof(DateTime), typeof(DateTime) }); + internal static ConstructorInfo intervalConstructor = typeof(Interval).GetConstructor(new[] { typeof(DateTime), typeof(DateTime) })!; internal NewExpression? GenerateSystemPeriod(Alias tableAlias, QueryBinder binder, bool force = false) { diff --git a/Signum.Engine/Schema/Schema.Save.cs b/Signum.Engine/Schema/Schema.Save.cs index 19d39aff79..6dbbcf2079 100644 --- a/Signum.Engine/Schema/Schema.Save.cs +++ b/Signum.Engine/Schema/Schema.Save.cs @@ -327,7 +327,7 @@ public IColumn? ToStrColumn get { - if (Fields.TryGetValue("toStr", out EntityField entity)) + if (Fields.TryGetValue("toStr", out var entity)) return (IColumn)entity.Field; return null; diff --git a/Signum.Engine/Schema/Schema.cs b/Signum.Engine/Schema/Schema.cs index 86ac830e99..e57e98ad23 100644 --- a/Signum.Engine/Schema/Schema.cs +++ b/Signum.Engine/Schema/Schema.cs @@ -36,7 +36,7 @@ public Version Version set { this.version = value; } } - public event Action OnMetadataInvalidated; + public event Action? OnMetadataInvalidated; public void InvalidateMetadata() { this.OnMetadataInvalidated?.Invoke(); @@ -66,7 +66,7 @@ public Dictionary Tables #region Events - public event Func IsAllowedCallback; + public event Func? IsAllowedCallback; public string? IsAllowed(Type type, bool inUserInterface) { @@ -410,7 +410,7 @@ public Func GetInMemoryFilter(bool userInterface) { try { - SafeConsole.WriteColor(ConsoleColor.White, e.Method.DeclaringType.TypeName()); + SafeConsole.WriteColor(ConsoleColor.White, e.Method.DeclaringType!.TypeName()); Console.Write("."); SafeConsole.WriteColor(ConsoleColor.DarkGray, e.Method.MethodName()); Console.Write("..."); @@ -428,7 +428,7 @@ public Func GetInMemoryFilter(bool userInterface) { SafeConsole.WriteLineColor(ConsoleColor.Red, "Error"); - return new SqlPreCommandSimple("-- Exception on {0}.{1}\r\n{2}".FormatWith(e.Method.DeclaringType.Name, e.Method.Name, ex.Message.Indent(2, '-'))); + return new SqlPreCommandSimple("-- Exception on {0}.{1}\r\n{2}".FormatWith(e.Method.DeclaringType!.Name, e.Method.Name, ex.Message.Indent(2, '-'))); } }) .Combine(Spacing.Triple); @@ -526,7 +526,7 @@ public void Initialize() using (ExecutionMode.Global()) foreach (var item in Initializing.GetInvocationListTyped()) - using (HeavyProfiler.Log("Initialize", () => item.Method.DeclaringType.ToString())) + using (HeavyProfiler.Log("Initialize", () => item.Method.DeclaringType!.ToString())) item(); Initializing = null; diff --git a/Signum.Engine/Schema/SchemaBuilder/SchemaBuilder.cs b/Signum.Engine/Schema/SchemaBuilder/SchemaBuilder.cs index 32bff6dcf5..4be6d0c35f 100644 --- a/Signum.Engine/Schema/SchemaBuilder/SchemaBuilder.cs +++ b/Signum.Engine/Schema/SchemaBuilder/SchemaBuilder.cs @@ -66,7 +66,7 @@ public Schema Schema } - public UniqueIndex AddUniqueIndex(Expression> fields, Expression>? where = null, Expression>? includeFields = null) where T : Entity + public UniqueTableIndex AddUniqueIndex(Expression> fields, Expression>? where = null, Expression>? includeFields = null) where T : Entity { var table = Schema.Table(); @@ -89,7 +89,7 @@ public UniqueIndex AddUniqueIndex(Expression> fields, Expres return index; } - public Index AddIndex(Expression> fields, + public TableIndex AddIndex(Expression> fields, Expression>? where = null, Expression>? includeFields = null) where T : Entity { @@ -97,7 +97,7 @@ public Index AddIndex(Expression> fields, IColumn[] columns = IndexKeyColumns.Split(table, fields); - var index = new Index(table, columns); + var index = new TableIndex(table, columns); if (where != null) index.Where = IndexWhereExpressionVisitor.GetIndexWhere(where, table); @@ -116,7 +116,7 @@ public Index AddIndex(Expression> fields, return index; } - public UniqueIndex AddUniqueIndexMList(Expression>> toMList, + public UniqueTableIndex AddUniqueIndexMList(Expression>> toMList, Expression, object>> fields, Expression, bool>>? where = null, Expression, object>>? includeFields = null) @@ -146,7 +146,7 @@ public UniqueIndex AddUniqueIndexMList(Expression>> toMLi return index; } - public Index AddIndexMList(Expression>> toMList, + public TableIndex AddIndexMList(Expression>> toMList, Expression, object>> fields, Expression, bool>>? where = null, Expression, object>>? includeFields = null) @@ -174,40 +174,40 @@ public Index AddIndexMList(Expression>> toMList, } - public UniqueIndex AddUniqueIndex(ITable table, Field[] fields) + public UniqueTableIndex AddUniqueIndex(ITable table, Field[] fields) { - var index = new UniqueIndex(table, Index.GetColumnsFromFields(fields)); + var index = new UniqueTableIndex(table, TableIndex.GetColumnsFromFields(fields)); AddIndex(index); return index; } - public UniqueIndex AddUniqueIndex(ITable table, IColumn[] columns) + public UniqueTableIndex AddUniqueIndex(ITable table, IColumn[] columns) { - var index = new UniqueIndex(table, columns); + var index = new UniqueTableIndex(table, columns); AddIndex(index); return index; } - public Index AddIndex(ITable table, Field[] fields) + public TableIndex AddIndex(ITable table, Field[] fields) { - var index = new Index(table, Index.GetColumnsFromFields(fields)); + var index = new TableIndex(table, TableIndex.GetColumnsFromFields(fields)); AddIndex(index); return index; } - public Index AddIndex(ITable table, IColumn[] columns) + public TableIndex AddIndex(ITable table, IColumn[] columns) { - var index = new Index(table, columns); + var index = new TableIndex(table, columns); AddIndex(index); return index; } - public void AddIndex(Index index) + public void AddIndex(TableIndex index) { ITable table = index.Table; if (table.MultiColumnIndexes == null) - table.MultiColumnIndexes = new List(); + table.MultiColumnIndexes = new List(); table.MultiColumnIndexes.Add(index); } @@ -227,7 +227,7 @@ public virtual Table Include(Type type) internal protected virtual Table Include(Type type, PropertyRoute? route) { - if (schema.Tables.TryGetValue(type, out Table result)) + if (schema.Tables.TryGetValue(type, out var result)) return result; using (HeavyProfiler.LogNoStackTrace("Include", () => type.TypeName())) @@ -321,9 +321,9 @@ void Complete(Table table) public HashSet<(Type type, string method)> LoadedModules = new HashSet<(Type type, string method)>(); - public bool NotDefined(MethodBase methodBase) + public bool NotDefined(MethodBase? methodBase) { - this.Tracer.Switch(methodBase.DeclaringType.Name); + this.Tracer.Switch(methodBase!.DeclaringType!.Name); var methods = methodBase.DeclaringType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) .Where(m => !m.HasAttribute()) @@ -345,7 +345,7 @@ public bool NotDefined(MethodBase methodBase) public void AssertDefined(MethodBase methodBase) { - var tulpe = (methodBase.DeclaringType, methodBase.Name); + var tulpe = (methodBase.DeclaringType!, methodBase.Name); if (!LoadedModules.Contains(tulpe)) throw new ApplicationException("Call {0} first".FormatWith(tulpe)); @@ -371,7 +371,7 @@ protected Dictionary GenerateFields(PropertyRoute root, ITa result.Add(fiId.Name, new EntityField(type, fiId, field)); } - TicksColumnAttribute t = type.GetCustomAttribute(); + TicksColumnAttribute? t = type.GetCustomAttribute(); if (t == null || t.HasTicks) { PropertyRoute route = root.Add(fiTicks); @@ -773,7 +773,7 @@ public virtual string GenerateCleanTypeName(Type type) { type = CleanType(type); - CleanTypeNameAttribute ctn = type.GetCustomAttribute(); + var ctn = type.GetCustomAttribute(); if (ctn != null) return ctn.Name; @@ -902,11 +902,11 @@ public virtual void AttachInvalidations(SchemaBuilder sb, InvalidateWith invalid { if (Transaction.InTestTransaction) { - invalidate(this, null); - Transaction.Rolledback += dic => invalidate(this, null); + invalidate(this, EventArgs.Empty); + Transaction.Rolledback += dic => invalidate(this, EventArgs.Empty); } - Transaction.PostRealCommit += dic => invalidate(this, null); + Transaction.PostRealCommit += dic => invalidate(this, EventArgs.Empty); }; Schema schema = sb.Schema; diff --git a/Signum.Engine/Schema/SchemaBuilder/SchemaBuilderSettings.cs b/Signum.Engine/Schema/SchemaBuilder/SchemaBuilderSettings.cs index fb5e1788cc..f516a5f563 100644 --- a/Signum.Engine/Schema/SchemaBuilder/SchemaBuilderSettings.cs +++ b/Signum.Engine/Schema/SchemaBuilder/SchemaBuilderSettings.cs @@ -408,7 +408,7 @@ public static bool IsCompatibleWith(Attribute a, AttributeTargets targets) { using (HeavyProfiler.LogNoStackTrace("IsCompatibleWith")) { - var au = AttributeUssageCache.GetOrCreate(a.GetType(), t => t.GetCustomAttribute()); + var au = AttributeUssageCache.GetOrCreate(a.GetType(), t => t.GetCustomAttribute()!); return au != null && (au.ValidOn & targets) != 0; } diff --git a/Signum.Engine/Schema/UniqueIndex.cs b/Signum.Engine/Schema/UniqueTableIndex.cs similarity index 95% rename from Signum.Engine/Schema/UniqueIndex.cs rename to Signum.Engine/Schema/UniqueTableIndex.cs index c145105dbe..4bce6a39e6 100644 --- a/Signum.Engine/Schema/UniqueIndex.cs +++ b/Signum.Engine/Schema/UniqueTableIndex.cs @@ -12,7 +12,7 @@ namespace Signum.Engine.Maps { - public class Index + public class TableIndex { public ITable Table { get; private set; } public IColumn[] Columns { get; private set; } @@ -31,7 +31,7 @@ public static IColumn[] GetColumnsFromFields(params Field[] fields) return fields.SelectMany(f => f.Columns()).ToArray(); } - public Index(ITable table, params IColumn[] columns) + public TableIndex(ITable table, params IColumn[] columns) { if (table == null) throw new ArgumentNullException(nameof(table)); @@ -70,7 +70,7 @@ public string HintText() } } - public class PrimaryClusteredIndex : Index + public class PrimaryClusteredIndex : TableIndex { public PrimaryClusteredIndex(ITable table) : base(table, new[] { table.PrimaryKey }) { @@ -85,9 +85,9 @@ public static string GetPrimaryKeyName(ObjectName tableName) } } - public class UniqueIndex : Index + public class UniqueTableIndex : TableIndex { - public UniqueIndex(ITable table, IColumn[] columns) : base(table, columns) { } + public UniqueTableIndex(ITable table, IColumn[] columns) : base(table, columns) { } public override string IndexName @@ -159,7 +159,7 @@ where type.IsAssignableFrom(ic.Key) select (IColumn)ic.Value).ToArray(); } - return Index.GetColumnsFromFields(f); + return TableIndex.GetColumnsFromFields(f); } static Type? RemoveCasting(ref Expression body) diff --git a/Signum.Engine/Signum.Engine.csproj b/Signum.Engine/Signum.Engine.csproj index 63f9f9498b..507c5cfe73 100644 --- a/Signum.Engine/Signum.Engine.csproj +++ b/Signum.Engine/Signum.Engine.csproj @@ -12,7 +12,7 @@ - + @@ -23,4 +23,11 @@ + + + + + + + diff --git a/Signum.Entities/Basics/Color.cs b/Signum.Entities/Basics/Color.cs index d5aeeff8a6..362586f710 100644 --- a/Signum.Entities/Basics/Color.cs +++ b/Signum.Entities/Basics/Color.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Drawing; using Signum.Utilities; @@ -11,9 +11,9 @@ public ColorEmbedded() { } - public override bool Equals(object color) + public override bool Equals(object? color) { - return this.Argb == ((ColorEmbedded)color).Argb; + return this.Argb == ((ColorEmbedded)color!).Argb; } public override int GetHashCode() diff --git a/Signum.Entities/Basics/IUserEntity.cs b/Signum.Entities/Basics/IUserEntity.cs index d92ceebc0c..fb25d832e7 100644 --- a/Signum.Entities/Basics/IUserEntity.cs +++ b/Signum.Entities/Basics/IUserEntity.cs @@ -1,4 +1,4 @@ -using Signum.Utilities; +using Signum.Utilities; using System; namespace Signum.Entities.Basics @@ -10,7 +10,7 @@ public interface IUserEntity : IEntity public static class UserHolder { public static readonly string UserSessionKey = "user"; - public static event Action CurrentUserChanged; + public static event Action? CurrentUserChanged; public static readonly SessionVariable CurrentUserVariable = Statics.SessionVariable(UserSessionKey); public static IUserEntity Current diff --git a/Signum.Entities/Basics/Symbol.cs b/Signum.Entities/Basics/Symbol.cs index 124a25cf69..7359bf2eb7 100644 --- a/Signum.Entities/Basics/Symbol.cs +++ b/Signum.Entities/Basics/Symbol.cs @@ -20,7 +20,7 @@ public Symbol() { } /// public Symbol(Type declaringType, string fieldName) { - this.fieldInfo = declaringType.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); + this.fieldInfo = declaringType.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)!; if (this.fieldInfo == null) throw new InvalidOperationException(string.Format("No field with name {0} found in {1}", fieldName, declaringType.Name)); @@ -71,7 +71,7 @@ public bool BaseEquals(object obj) return base.Equals(obj); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is Symbol && obj.GetType() == this.GetType() && diff --git a/Signum.Entities/DynamicQuery/Column.cs b/Signum.Entities/DynamicQuery/Column.cs index 1bc2ba2e5b..7044bff2fa 100644 --- a/Signum.Entities/DynamicQuery/Column.cs +++ b/Signum.Entities/DynamicQuery/Column.cs @@ -35,7 +35,7 @@ public override string ToString() return "{0} '{1}'".FormatWith(Token.FullKey(), DisplayName); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is Column && base.Equals((Column)obj); } diff --git a/Signum.Entities/DynamicQuery/Filter.cs b/Signum.Entities/DynamicQuery/Filter.cs index 6f3d69488d..2f5db4656f 100644 --- a/Signum.Entities/DynamicQuery/Filter.cs +++ b/Signum.Entities/DynamicQuery/Filter.cs @@ -135,7 +135,7 @@ private Expression GetConditionExpressionBasic(BuildExpressionContext context) if (Value == null) return Expression.Constant(false); - IList clone = (IList)Activator.CreateInstance(Value.GetType(), Value); + IList clone = (IList)Activator.CreateInstance(Value.GetType(), Value)!; bool hasNull = false; while (clone.Contains(null)) diff --git a/Signum.Entities/DynamicQuery/QueryUtils.cs b/Signum.Entities/DynamicQuery/QueryUtils.cs index 376afe3a4b..b2a7af9e92 100644 --- a/Signum.Entities/DynamicQuery/QueryUtils.cs +++ b/Signum.Entities/DynamicQuery/QueryUtils.cs @@ -16,21 +16,16 @@ public static class QueryUtils { public static string GetKey(object queryName) { - if (queryName is Type) - queryName = EnumEntity.Extract((Type)queryName) ?? (Type)queryName; - - return (queryName is Type ? Reflector.CleanTypeName((Type) queryName) : queryName.ToString()); + return queryName is Type t ? Reflector.CleanTypeName(EnumEntity.Extract(t) ?? t) : + queryName.ToString()!; } public static string GetNiceName(object queryName) { - if (queryName is Type) - queryName = EnumEntity.Extract((Type)queryName) ?? (Type)queryName; - return - queryName is Type ? ((Type)queryName).NicePluralName() : - queryName is Enum ? ((Enum)queryName).NiceToString() : - queryName.ToString(); + queryName is Type t ? (EnumEntity.Extract(t) ?? t).NicePluralName() : + queryName is Enum e ? e.NiceToString() : + queryName.ToString()!; } public static FilterType GetFilterType(Type type) diff --git a/Signum.Entities/DynamicQuery/Requests.cs b/Signum.Entities/DynamicQuery/Requests.cs index c055b14e8d..fcd8d25225 100644 --- a/Signum.Entities/DynamicQuery/Requests.cs +++ b/Signum.Entities/DynamicQuery/Requests.cs @@ -267,7 +267,7 @@ public List Multiplications public int? Count { get; set; } - public override string ToString() => QueryName.ToString(); + public override string ToString() => QueryName.ToString()!; } [Serializable] @@ -302,6 +302,6 @@ public List Multiplications public int? Count { get; set; } - public override string ToString() => QueryName.ToString(); + public override string ToString() => QueryName.ToString()!; } } diff --git a/Signum.Entities/DynamicQuery/ResultTable.cs b/Signum.Entities/DynamicQuery/ResultTable.cs index 8341d198d2..f39098c917 100644 --- a/Signum.Entities/DynamicQuery/ResultTable.cs +++ b/Signum.Entities/DynamicQuery/ResultTable.cs @@ -43,9 +43,9 @@ public ResultColumn(Column column, IList values) { switch (entry.Name) { - case "column": column = (Column)entry.Value; break; - case "valuesList": values = (IList)entry.Value; break; - case "valuesString": values = Split((string)entry.Value, GetValueDeserializer()); break; + case "column": column = (Column)entry.Value!; break; + case "valuesList": values = (IList)entry.Value!; break; + case "valuesString": values = Split((string)entry.Value!, GetValueDeserializer()); break; } } } @@ -158,7 +158,7 @@ Func GetValueDeserializer() }; if (column.Type.UnNullify().IsEnum) - return obj => Convert.ChangeType(obj, typeof(int)).ToString(); + return obj => Convert.ChangeType(obj, typeof(int))!.ToString()!; switch (Type.GetTypeCode(column.Type.UnNullify())) { @@ -435,12 +435,12 @@ internal ResultRow(int index, ResultTable table) public Lite Entity { - get { return (Lite)Table.entityColumn.Values[Index]; } + get { return (Lite)Table.entityColumn.Values[Index]!; } } public Lite? TryEntity { - get { return Table.entityColumn == null ? null : (Lite)Table.entityColumn.Values[Index]; } + get { return Table.entityColumn == null ? null : (Lite?)Table.entityColumn.Values[Index]; } } public T GetValue(string columnName) @@ -468,6 +468,6 @@ public T GetValue(ResultColumn column) return result; } - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; } } diff --git a/Signum.Entities/DynamicQuery/Tokens/CountToken.cs b/Signum.Entities/DynamicQuery/Tokens/CountToken.cs index afb50db12f..c6a5e79388 100644 --- a/Signum.Entities/DynamicQuery/Tokens/CountToken.cs +++ b/Signum.Entities/DynamicQuery/Tokens/CountToken.cs @@ -41,7 +41,7 @@ protected override Expression BuildExpressionInternal(BuildExpressionContext con { var parentResult = parent.BuildExpression(context); - var result = Expression.Call(miCount.MakeGenericMethod(parentResult.Type.ElementType()), parentResult); + var result = Expression.Call(miCount.MakeGenericMethod(parentResult.Type.ElementType()!), parentResult); return result.Nullify(); } diff --git a/Signum.Entities/DynamicQuery/Tokens/ExtensionDictionaryToken.cs b/Signum.Entities/DynamicQuery/Tokens/ExtensionDictionaryToken.cs index 13091a8195..81db650d23 100644 --- a/Signum.Entities/DynamicQuery/Tokens/ExtensionDictionaryToken.cs +++ b/Signum.Entities/DynamicQuery/Tokens/ExtensionDictionaryToken.cs @@ -32,12 +32,12 @@ public ExtensionDictionaryToken(QueryToken parent, K key, public override string ToString() { - return "[" + (((object)keyValue) is Enum e ? e.NiceToString() : keyValue.ToString()) + "]"; + return "[" + (keyValue is Enum e ? e.NiceToString() : keyValue.ToString()) + "]"; } public override string NiceName() { - return ((object)keyValue) is Enum e ? e.NiceToString() : keyValue.ToString(); + return keyValue is Enum e ? e.NiceToString() : keyValue.ToString()!; } public override Type Type { get { return typeof(V).BuildLiteNullifyUnwrapPrimaryKey(new[] { this.GetPropertyRoute()! }); } } diff --git a/Signum.Entities/DynamicQuery/Tokens/ExtensionToken.cs b/Signum.Entities/DynamicQuery/Tokens/ExtensionToken.cs index b5ea070108..c35dc4e2dd 100644 --- a/Signum.Entities/DynamicQuery/Tokens/ExtensionToken.cs +++ b/Signum.Entities/DynamicQuery/Tokens/ExtensionToken.cs @@ -70,7 +70,7 @@ protected override List SubTokensOverride(SubTokensOptions options) return base.SubTokensBase(type, options, implementations); } - public static Func BuildExtension; + public static Func? BuildExtension; protected override Expression BuildExpressionInternal(BuildExpressionContext context) { diff --git a/Signum.Entities/DynamicQuery/Tokens/QueryToken.cs b/Signum.Entities/DynamicQuery/Tokens/QueryToken.cs index 2945690771..e54110201d 100644 --- a/Signum.Entities/DynamicQuery/Tokens/QueryToken.cs +++ b/Signum.Entities/DynamicQuery/Tokens/QueryToken.cs @@ -79,7 +79,7 @@ public Func GetAccessor(BuildExpressionContext context) public Expression BuildExpression(BuildExpressionContext context) { - if (context.Replacemens != null && context.Replacemens.TryGetValue(this, out Expression result)) + if (context.Replacemens != null && context.Replacemens.TryGetValue(this, out var result)) return result; return BuildExpressionInternal(context); @@ -217,7 +217,7 @@ public static IEnumerable OnEntityExtension(QueryToken parent) return EntityExtensions(parent); } - public static Func> EntityExtensions; + public static Func>? EntityExtensions; public static List DateTimeProperties(QueryToken parent, DateTimePrecision precision) @@ -316,7 +316,7 @@ public string FullKey() return Parent.FullKey() + "." + Key; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is QueryToken && obj.GetType() == this.GetType() && Equals((QueryToken)obj); } diff --git a/Signum.Entities/Entity.cs b/Signum.Entities/Entity.cs index feeee843e3..df21169d94 100644 --- a/Signum.Entities/Entity.cs +++ b/Signum.Entities/Entity.cs @@ -83,7 +83,7 @@ public string BaseToString() return "{0} ({1})".FormatWith(GetType().NiceName(), id.HasValue ? id.ToString() : LiteMessage.New_G.NiceToString().ForGenderAndNumber(this.GetType().GetGender())); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if(obj == this) return true; @@ -115,7 +115,7 @@ public override int GetHashCode() { return id == null ? base.GetHashCode() : - StringHashEncoder.GetHashCode32(GetType().FullName) ^ id.Value.GetHashCode(); + StringHashEncoder.GetHashCode32(GetType().FullName!) ^ id.Value.GetHashCode(); } public Entity() diff --git a/Signum.Entities/EnumEntity.cs b/Signum.Entities/EnumEntity.cs index 93c6f84797..21fcec8d91 100644 --- a/Signum.Entities/EnumEntity.cs +++ b/Signum.Entities/EnumEntity.cs @@ -69,7 +69,7 @@ public static class EnumEntity { public static Entity FromEnumUntyped(Enum value) { - Entity ident = (Entity)Activator.CreateInstance(Generate(value.GetType())); + Entity ident = (Entity)Activator.CreateInstance(Generate(value.GetType()))!; ident.Id = new PrimaryKey(EnumExtensions.GetUnderlyingValue(value)); return ident; @@ -79,7 +79,7 @@ public static Enum ToEnum(Entity ident) { Type enumType = Extract(ident.GetType())!; - return (Enum)Enum.ToObject(enumType, ident.id); + return (Enum)Enum.ToObject(enumType, ident.id!.Value.Object); } public static bool IsEnumEntity(this Type type) @@ -118,15 +118,15 @@ public static Type Generate(Type enumType) class FromEnumMethodExpander : IMethodExpander { - internal static MethodInfo miQuery; + internal static MethodInfo miQuery = null!; static readonly MethodInfo miSingleOrDefault = ReflectionTools.GetMethodInfo(() => Enumerable.SingleOrDefault(null, i => true)).GetGenericMethodDefinition(); public Expression Expand(Expression instance, Expression[] arguments, System.Reflection.MethodInfo mi) { - var type = mi.DeclaringType; - var query = Expression.Call(null, miQuery.MakeGenericMethod(mi.DeclaringType)); + var type = mi.DeclaringType!; + var query = Expression.Call(null, miQuery.MakeGenericMethod(mi.DeclaringType!)); - var underlyingType = Enum.GetUnderlyingType(mi.DeclaringType.GetGenericArguments().Single()); + var underlyingType = Enum.GetUnderlyingType(mi.DeclaringType!.GetGenericArguments().Single()); var param = Expression.Parameter(mi.DeclaringType); var filter = Expression.Lambda(Expression.Equal( diff --git a/Signum.Entities/FieldAttributes.cs b/Signum.Entities/FieldAttributes.cs index d859c00227..63051ce840 100644 --- a/Signum.Entities/FieldAttributes.cs +++ b/Signum.Entities/FieldAttributes.cs @@ -154,9 +154,9 @@ public override string ToString() return "ImplementedBy({0})".FormatWith(Types.ToString(t => t.Name, ", ")); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { - return obj is Implementations || Equals((Implementations)obj); + return obj is Implementations imp && Equals(imp); } public bool Equals(Implementations other) @@ -173,7 +173,7 @@ public override int GetHashCode() Implementations(SerializationInfo info, StreamingContext context) { - string str = info.GetString("arrayOrType"); + string str = info.GetString("arrayOrType")!; arrayOrType = str == "ALL" ? null : str.Split('|').Select(Type.GetType).ToArray(); diff --git a/Signum.Entities/Lite.cs b/Signum.Entities/Lite.cs index 05564075e7..c6a00d132f 100644 --- a/Signum.Entities/Lite.cs +++ b/Signum.Entities/Lite.cs @@ -182,7 +182,7 @@ protected internal override void PreSaving(PreSavingContext ctx) return this.toStr; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj == null) return false; @@ -204,7 +204,7 @@ public override bool Equals(object obj) public override int GetHashCode() { return this.id == null ? entityOrNull!.GetHashCode() ^ MagicMask : - this.EntityType.FullName.GetHashCode() ^ this.Id.GetHashCode() ^ MagicMask; + this.EntityType.FullName!.GetHashCode() ^ this.Id.GetHashCode() ^ MagicMask; } public string Key() @@ -222,7 +222,7 @@ public int CompareTo(Lite other) return ToString()!.CompareTo(other.ToString()); } - public int CompareTo(object obj) + public int CompareTo(object? obj) { if (obj is Lite lite) return CompareTo(lite); @@ -248,10 +248,10 @@ private LiteImp(SerializationInfo info, StreamingContext ctxt) { switch (item.Name) { - case "modified": this.Modified = (ModifiedState)Enum.Parse(typeof(ModifiedState), (string)item.Value); modifiedSet = true; break; - case "entityOrNull": this.entityOrNull = (T)item.Value; break; - case "id": this.id = (PrimaryKey)item.Value; break; - case "toStr": this.toStr = (string)item.Value; break; + case "modified": this.Modified = (ModifiedState)Enum.Parse(typeof(ModifiedState), (string)item.Value!); modifiedSet = true; break; + case "entityOrNull": this.entityOrNull = (T)item.Value!; break; + case "id": this.id = (PrimaryKey)item.Value!; break; + case "toStr": this.toStr = (string)item.Value!; break; default: throw new InvalidOperationException("Unexpected SerializationEntry"); } } @@ -565,9 +565,13 @@ public static Lite Create(PrimaryKey id, string toStr) where T : Entity static ConcurrentDictionary ciLiteConstructorId = new ConcurrentDictionary(); public static ConstructorInfo LiteConstructorId(Type type) { - return ciLiteConstructorId.GetOrAdd(type, t => typeof(LiteImp<>).MakeGenericType(t).GetConstructor(new[] { typeof(PrimaryKey), typeof(string) })); + var hc = type.GetHashCode(); + var equals = type.Equals(type); + + return ciLiteConstructorId.GetOrAdd(type, Bla.CreateLiteConstructor); } + public static NewExpression NewExpression(Type type, Expression id, Expression toString) { return Expression.New(Lite.LiteConstructorId(type), id.UnNullify(), toString); @@ -613,4 +617,13 @@ public enum LiteMessage [Description("Text")] ToStr } + + static class Bla + { + internal static ConstructorInfo CreateLiteConstructor(Type t) + { + return typeof(LiteImp<>).MakeGenericType(t).GetConstructor(new[] { typeof(PrimaryKey), typeof(string) })!; + } + + } } diff --git a/Signum.Entities/MList.cs b/Signum.Entities/MList.cs index 1475f4d921..d00f202464 100644 --- a/Signum.Entities/MList.cs +++ b/Signum.Entities/MList.cs @@ -71,7 +71,7 @@ public override int GetHashCode() return Element == null ? 0 : Element.GetHashCode(); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is RowIdElement && base.Equals((RowIdElement)obj); } @@ -99,7 +99,7 @@ private RowIdElement(SerializationInfo info, StreamingContext ctxt) { case "rowid": this.RowId = (PrimaryKey?)item.Value; break; case "oldindex": this.OldIndex = (int?)item.Value; break; - case "value": this.Element = (T)item.Value; break; + case "value": this.Element = (T)item.Value!; break; default: throw new InvalidOperationException("Unexpected SerializationEntry"); } } @@ -453,6 +453,7 @@ public int RemoveAllElements(Predicate predicate) return removed.Count; } + //void IList.RemoveAt(int index) => RemoveAt(index!.Value); public void RemoveAt(int index) { AssertNotSealed(); @@ -582,25 +583,25 @@ public override string ToString() #region IList Members - int IList.Add(object value) + int IList.Add(object? value) { - this.Add((T)value); + this.Add((T)value!); return this.Count; } - bool IList.Contains(object value) + bool IList.Contains(object? value) { - return this.Contains((T)value); + return this.Contains((T)value!); } - int IList.IndexOf(object value) + int IList.IndexOf(object? value) { - return this.IndexOf((T)value); + return this.IndexOf((T)value!); } - void IList.Insert(int index, object value) + void IList.Insert(int index, object? value) { - this.Insert(index, (T)value); + this.Insert(index, (T)value!); } bool IList.IsFixedSize @@ -608,9 +609,9 @@ bool IList.IsFixedSize get { return false; } } - void IList.Remove(object value) + void IList.Remove(object? value) { - this.Remove((T)value); + this.Remove((T)value!); } object? IList.this[int index] @@ -779,6 +780,11 @@ public void AssignAndPostRetrieving(IMListPrivate newList) this.AssignMList((MList)newList); this.PostRetrieving(); } + + public void Insert(int? index, object? value) + { + throw new NotImplementedException(); + } } diff --git a/Signum.Entities/ModelEntity.cs b/Signum.Entities/ModelEntity.cs index 7edb1207f7..1c9eaa5ec6 100644 --- a/Signum.Entities/ModelEntity.cs +++ b/Signum.Entities/ModelEntity.cs @@ -37,8 +37,8 @@ public static Implementations GetImplementations(PropertyRoute route) return Implementations.FromAttributes( route.Type.CleanType(), route, - fieldRoute.FieldInfo.GetCustomAttribute(), - fieldRoute.FieldInfo.GetCustomAttribute()); + fieldRoute.FieldInfo!.GetCustomAttribute(), + fieldRoute.FieldInfo!.GetCustomAttribute()); } } } diff --git a/Signum.Entities/ModifiableEntity.cs b/Signum.Entities/ModifiableEntity.cs index e0cd051027..6b8c634284 100644 --- a/Signum.Entities/ModifiableEntity.cs +++ b/Signum.Entities/ModifiableEntity.cs @@ -65,7 +65,7 @@ protected virtual bool Set(ref T field, T value, [CallerMemberName]string? au colb.CollectionChanged -= ChildCollectionChanged; if (AttributeManager.FieldContainsAttribute(GetType(), pi)) - foreach (ModifiableEntity item in (IEnumerable)colb) + foreach (var item in (IEnumerable)colb) item.SetParentEntity(null); } @@ -84,7 +84,7 @@ protected virtual bool Set(ref T field, T value, [CallerMemberName]string? au cola.CollectionChanged += ChildCollectionChanged; if (AttributeManager.FieldContainsAttribute(GetType(), pi)) - foreach (ModifiableEntity item in (IEnumerable)cola) + foreach (var item in (IEnumerable)cola) item.SetParentEntity(this); } @@ -115,7 +115,7 @@ public PropertyKey(Type type, string propertyName) public string PropertyName; public bool Equals(PropertyKey other) => other.Type == Type && other.PropertyName == PropertyName; - public override bool Equals(object obj) => obj is PropertyKey && Equals((PropertyKey)obj); + public override bool Equals(object? obj) => obj is PropertyKey pk && Equals(pk); public override int GetHashCode() => Type.GetHashCode() ^ PropertyName.GetHashCode(); } @@ -128,13 +128,13 @@ protected PropertyInfo GetPropertyInfo(string propertyName) key.Type.GetInterfaces().Select(i => i.GetProperty(key.PropertyName, flags)).NotNull().FirstOrDefault()); } - static Expression> ToStringPropertyExpression = m => m.ToString(); + static Expression> ToStringPropertyExpression = m => m.ToString()!; [HiddenProperty, ExpressionField("ToStringPropertyExpression")] public string ToStringProperty { get { - string str = ToString(); + string? str = ToString(); return str.HasText() ? str : this.GetType().NiceName(); } } @@ -165,7 +165,7 @@ protected virtual void RebindEvents() entity.SetParentEntity(this); else { - foreach (ModifiableEntity item in (IEnumerable)field!) + foreach (var item in (IEnumerable)field!) item.SetParentEntity(this); } } @@ -211,7 +211,7 @@ protected virtual void ChildPropertyChanged(object sender, PropertyChangedEventA #endregion [field: NonSerialized, Ignore] - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; [NonSerialized, Ignore] ModifiableEntity? parentEntity; @@ -284,7 +284,7 @@ internal ModifiableEntity() public override int GetHashCode() { - return GetType().FullName.GetHashCode() ^ temporalId.GetHashCode(); + return GetType().FullName!.GetHashCode() ^ temporalId.GetHashCode(); } #endregion diff --git a/Signum.Entities/ObjectDumper.cs b/Signum.Entities/ObjectDumper.cs index ce933c743c..014196a3e0 100644 --- a/Signum.Entities/ObjectDumper.cs +++ b/Signum.Entities/ObjectDumper.cs @@ -59,7 +59,7 @@ public DumpVisitor(ShowIgnoredFields showIgnoredFields, bool showByteArrays) this.showByteArrays = showByteArrays; } - public void DumpObject(object o) + public void DumpObject(object? o) { if (o == null) { @@ -138,8 +138,8 @@ public void DumpObject(object o) { Sb.AppendLine().AppendLine("{".Indent(level)); level += 1; - var prop = o.GetType().GetProperty(nameof(Lite.Entity)); - DumpPropertyOrField(prop.PropertyType, prop.Name, prop.GetValue(o, null)); + var prop = o.GetType().GetProperty(nameof(Lite.Entity))!; + DumpPropertyOrField(prop.PropertyType, prop.Name, prop.GetValue(o, null)!); level -= 1; Sb.Append("}".Indent(level)); } @@ -172,14 +172,14 @@ public void DumpObject(object o) } else if (o is IEnumerable) { - if (o is IDictionary) + if (o is IDictionary dic) { - foreach (DictionaryEntry item in (o as IDictionary)!) + foreach (DictionaryEntry? item in dic) { Sb.Append("{".Indent(level)); - DumpObject(item.Key); + DumpObject(item!.Value.Key); Sb.Append(", "); - DumpObject(item.Value); + DumpObject(item!.Value.Value); Sb.AppendLine("},"); } } @@ -249,7 +249,7 @@ private static string SafeToString(object o) string toString; try { - toString = o.ToString(); + toString = o.ToString()!; } catch (Exception e) { @@ -286,7 +286,7 @@ private bool Any(IEnumerable ie) return false; } - private void DumpPropertyOrField(Type type, string name, object obj) + private void DumpPropertyOrField(Type type, string name, object? obj) { Sb.AppendFormat("{0} = ".Indent(level), name); DumpObject(obj); diff --git a/Signum.Entities/Patterns/CorruptEntity.cs b/Signum.Entities/Patterns/CorruptEntity.cs index 02f3e819d5..d2538b0de6 100644 --- a/Signum.Entities/Patterns/CorruptEntity.cs +++ b/Signum.Entities/Patterns/CorruptEntity.cs @@ -52,14 +52,14 @@ public static class Corruption return new Disposable(() => allowed.Value = true); } - public static event Action> SaveCorrupted; + public static event Action>? SaveCorrupted; public static void OnSaveCorrupted(Entity corruptEntity, Dictionary integrity) { SaveCorrupted?.Invoke(corruptEntity, integrity); } - public static event Action CorruptionRemoved; + public static event Action? CorruptionRemoved; public static void OnCorruptionRemoved(Entity corruptEntity) { diff --git a/Signum.Entities/Patterns/LockeableEntity.cs b/Signum.Entities/Patterns/LockeableEntity.cs index d85daef7ef..bfad6792ba 100644 --- a/Signum.Entities/Patterns/LockeableEntity.cs +++ b/Signum.Entities/Patterns/LockeableEntity.cs @@ -29,13 +29,13 @@ protected virtual void ItemLockedChanged(bool locked) { } - protected override bool Set(ref T field, T value, [CallerMemberNameAttribute]string? automaticPropertyName = null) + protected override bool Set(ref T field, T value, [CallerMemberName]string? automaticPropertyName = null) { if (EqualityComparer.Default.Equals(field, value)) return false; if (this.locked) - throw new ApplicationException(EntityMessage.AttemptToSet0InLockedEntity1.NiceToString(this.GetType().GetProperty(automaticPropertyName, flags).NiceName(), this.ToString())); + throw new ApplicationException(EntityMessage.AttemptToSet0InLockedEntity1.NiceToString(this.GetType().GetProperty(automaticPropertyName!, flags)!.NiceName(), this.ToString())); return base.Set(ref field, value, automaticPropertyName); } diff --git a/Signum.Entities/PrimaryKey.cs b/Signum.Entities/PrimaryKey.cs index d40f79dc6e..7128f18c04 100644 --- a/Signum.Entities/PrimaryKey.cs +++ b/Signum.Entities/PrimaryKey.cs @@ -53,14 +53,14 @@ public PrimaryKey(IComparable obj, string variableName) this.VariableName = variableName; } - public override string ToString() + public override string? ToString() { return Object.ToString(); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { - return obj is PrimaryKey && this.Equals((PrimaryKey)obj); + return obj is PrimaryKey pk && this.Equals(pk); } public override int GetHashCode() @@ -76,9 +76,9 @@ public bool Equals(PrimaryKey other) return other.Object.Equals(this.Object); } - public int CompareTo(object obj) + public int CompareTo(object? obj) { - return CompareTo((PrimaryKey)obj); + return CompareTo((PrimaryKey)obj!); } public int CompareTo(PrimaryKey other) @@ -280,7 +280,7 @@ private PrimaryKey(SerializationInfo info, StreamingContext ctxt) { switch (item.Name) { - case "Object": this.Object = (IComparable)item.Value; break; + case "Object": this.Object = (IComparable)item.Value!; break; } } diff --git a/Signum.Entities/PropertyRoute.cs b/Signum.Entities/PropertyRoute.cs index 19e8f037b4..61271d016d 100644 --- a/Signum.Entities/PropertyRoute.cs +++ b/Signum.Entities/PropertyRoute.cs @@ -74,8 +74,9 @@ public PropertyRoute Add(string fieldOrProperty) MemberInfo GetMember(string fieldOrProperty) { - MemberInfo mi = (MemberInfo)Type.GetProperty(fieldOrProperty, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, null, IsCollection() ? new[] { typeof(int) } : new Type[0], null) ?? - (MemberInfo)Type.GetField(fieldOrProperty, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); + MemberInfo? mi = + (MemberInfo?)Type.GetProperty(fieldOrProperty, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, null, IsCollection() ? new[] { typeof(int) } : new Type[0], null) ?? + (MemberInfo?)Type.GetField(fieldOrProperty, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (mi == null && Type.IsEntity()) { @@ -349,7 +350,7 @@ public static void SetFindImplementationsCallback(Func FindImplementations; + static Func? FindImplementations; public Implementations? TryGetImplementations() { @@ -372,7 +373,7 @@ public static void SetIsAllowedCallback(Func isAllowed) IsAllowedCallback = isAllowed; } - static Func IsAllowedCallback; + static Func? IsAllowedCallback; public string? IsAllowed() { @@ -447,7 +448,7 @@ public override int GetHashCode() return this.RootType.GetHashCode() ^ (this.PropertyRouteType == Entities.PropertyRouteType.Root ? 0 : this.PropertyString().GetHashCode()); } - public override bool Equals(object obj) => obj is PropertyRoute pr && Equals(pr); + public override bool Equals(object? obj) => obj is PropertyRoute pr && Equals(pr); public bool Equals(PropertyRoute other) { if (other.PropertyRouteType != this.PropertyRouteType) @@ -512,11 +513,11 @@ public PropertyRoute SimplifyToPropertyOrRoot() PropertyRoute(SerializationInfo info, StreamingContext ctxt) #pragma warning restore IDE0051 // Remove unused private members { - string rootName = info.GetString("rootType"); + string rootName = info.GetString("rootType")!; - Type root = Type.GetType(rootName); + Type root = Type.GetType(rootName)!; - string route = info.GetString("property"); + string? route = info.GetString("property"); if (route == null) this.SetRootType(root); @@ -666,7 +667,7 @@ public bool IsToStringProperty() if (result != true) return result; - var list = (IList)this.PropertyInfo!.GetValue(parentEntity); + var list = (IList?)this.PropertyInfo!.GetValue(parentEntity); return list != null && list.Contains(entity); } diff --git a/Signum.Entities/Reflection/EntityStructuralEqualityComparer.cs b/Signum.Entities/Reflection/EntityStructuralEqualityComparer.cs index cea4443458..7018f8cdfd 100644 --- a/Signum.Entities/Reflection/EntityStructuralEqualityComparer.cs +++ b/Signum.Entities/Reflection/EntityStructuralEqualityComparer.cs @@ -80,7 +80,7 @@ public override int GetHashCode(T obj) int result = obj.GetType().GetHashCode(); foreach (var p in Properties.Values) { - result = result * 31 + p.Comparer.GetHashCode(p.Getter(obj)); + result = result * 31 + p.Comparer.GetHashCode(p.Getter(obj)!); } if (Mixins != null) @@ -141,7 +141,7 @@ public override int GetHashCode(T obj) int result = obj.GetType().GetHashCode(); foreach (var p in Properties.Values) { - result = result * 31 + p.Comparer.GetHashCode(p.Getter(obj)); + result = result * 31 + p.Comparer.GetHashCode(p.Getter(obj)!); } return result; @@ -293,21 +293,21 @@ protected override IEqualityComparer GetEqualityComparerInternal(Type type, Prop { if (typeof(ModifiableEntity).IsAssignableFrom(type)) { - return (IEqualityComparer)Activator.CreateInstance(typeof(EntityStructuralEqualityComparer<>).MakeGenericType(type)); + return (IEqualityComparer)Activator.CreateInstance(typeof(EntityStructuralEqualityComparer<>).MakeGenericType(type))!; } if (typeof(IList).IsAssignableFrom(type)) { if (pi?.HasAttribute() == true) - return (IEqualityComparer)Activator.CreateInstance(typeof(SortedListEqualityComparer<>).MakeGenericType(type.ElementType())); + return (IEqualityComparer)Activator.CreateInstance(typeof(SortedListEqualityComparer<>).MakeGenericType(type.ElementType()!))!; else - return (IEqualityComparer)Activator.CreateInstance(typeof(UnsortedListEqualityComparer<>).MakeGenericType(type.ElementType())); + return (IEqualityComparer)Activator.CreateInstance(typeof(UnsortedListEqualityComparer<>).MakeGenericType(type.ElementType()!))!; } if (type.IsClass && type.GetMethod("Equals", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, new[] { typeof(object) }, null) == null) - return (IEqualityComparer)Activator.CreateInstance(typeof(ClassStructuralEqualityComparer<>).MakeGenericType(type)); + return (IEqualityComparer)Activator.CreateInstance(typeof(ClassStructuralEqualityComparer<>).MakeGenericType(type))!; - return (IEqualityComparer)typeof(EqualityComparer<>).MakeGenericType(type).GetProperty("Default").GetValue(null); + return (IEqualityComparer)typeof(EqualityComparer<>).MakeGenericType(type).GetProperty("Default")!.GetValue(null)!; } } diff --git a/Signum.Entities/Reflection/GraphExplorer.cs b/Signum.Entities/Reflection/GraphExplorer.cs index eda8003de8..7db5d87693 100644 --- a/Signum.Entities/Reflection/GraphExplorer.cs +++ b/Signum.Entities/Reflection/GraphExplorer.cs @@ -78,7 +78,9 @@ public static DirectedGraph FromRootsEntity(IEnumerable roots) return DirectedGraph.Generate(roots.Cast(), ModifyInspector.EntityExplore, ReferenceEqualityComparer.Default); } - public static Dictionary? ToDictionaryOrNull(this IEnumerable collection, Func keySelector, Func nullableValueSelector) where V : class + public static Dictionary? ToDictionaryOrNull(this IEnumerable collection, Func keySelector, Func nullableValueSelector) + where V : class + where K : notnull { Dictionary? result = null; @@ -110,11 +112,11 @@ public static DirectedGraph FromRootsEntity(IEnumerable roots) DirectedGraph identGraph = DirectedGraph.Generate(graph.Where(a => a is Entity), graph.RelatedTo); - var identErrors = identGraph.OfType().Select(ident => ident.EntityIntegrityCheck()).NotNull().SelectMany(errors => errors.Values); + var identErrors = identGraph.OfType().Select(ident => ident.EntityIntegrityCheck()).NotNull().SelectMany(errors => errors.Values).ToList(); var modErros = graph.Except(identGraph).OfType() .Select(a => a.IntegrityCheck()) - .NotNull(); + .NotNull().ToList(); return identErrors.Concat(modErros).ToDictionaryOrNull(a => a.TemporalId, a => a); } @@ -207,7 +209,7 @@ public static DirectedGraph PreSaving(Func public static string SuperGraphviz(this DirectedGraph modifiables) { - Func color = t => colors[Math.Abs(t.FullName.GetHashCode()) % colors.Length]; + Func color = t => colors[Math.Abs(t.FullName!.GetHashCode()) % colors.Length]; var listNodes = modifiables.Nodes.Select(n => new { @@ -227,7 +229,7 @@ public static string SuperGraphviz(this DirectedGraph modifiables) Style = n is Entity ? ", style=\"diagonals,filled,bold\"" : n is Lite ? "style=\"solid,bold\"" : "", - Label = n.ToString().Etc(30, "..").RemoveDiacritics() + Label = n.ToString()!.Etc(30, "..").RemoveDiacritics() }).ToList(); @@ -263,7 +265,7 @@ public static XDocument EntityDGML(this DirectedGraph graph) { new XAttribute("Label", n.ToString() ?? "[null]"), new XAttribute("TypeName", n.GetType().TypeName()), - new XAttribute("Background", ColorExtensions.ToHtmlColor(n.GetType().FullName.GetHashCode())) + new XAttribute("Background", ColorExtensions.ToHtmlColor(n.GetType().FullName!.GetHashCode())) }); } @@ -273,7 +275,7 @@ private static XAttribute[] GetAttributes(Entity ie) { new XAttribute("Label", (ie.ToString() ?? "[null]") + Modified(ie)), new XAttribute("TypeName", ie.GetType().TypeName()), - new XAttribute("Background", ColorExtensions.ToHtmlColor(ie.GetType().FullName.GetHashCode())), + new XAttribute("Background", ColorExtensions.ToHtmlColor(ie.GetType().FullName!.GetHashCode())), new XAttribute("Description", ie.IdOrNull?.ToString() ?? "New") }; } @@ -289,7 +291,7 @@ private static XAttribute[] GetAttributes(Lite lite) { new XAttribute("Label", (lite.ToString() ?? "[null]") + Modified((Modifiable)lite)), new XAttribute("TypeName", lite.GetType().TypeName()), - new XAttribute("Stroke", ColorExtensions.ToHtmlColor(lite.EntityType.FullName.GetHashCode())), + new XAttribute("Stroke", ColorExtensions.ToHtmlColor(lite.EntityType.FullName!.GetHashCode())), new XAttribute("StrokeThickness", "2"), new XAttribute("Background", ColorExtensions.ToHtmlColor(lite.EntityType.FullName.GetHashCode()).Replace("#", "#44")), new XAttribute("Description", lite.IdOrNull?.ToString() ?? "New") @@ -303,7 +305,7 @@ private static XAttribute[] GetAttributes(EmbeddedEntity ee) new XAttribute("Label", (ee.ToString() ?? "[null]")+ Modified(ee)), new XAttribute("TypeName", ee.GetType().TypeName()), new XAttribute("NodeRadius", 0), - new XAttribute("Background", ColorExtensions.ToHtmlColor(ee.GetType().FullName.GetHashCode())), + new XAttribute("Background", ColorExtensions.ToHtmlColor(ee.GetType().FullName!.GetHashCode())), }; } @@ -313,7 +315,7 @@ private static XAttribute[] GetAttributes(MixinEntity ee) { new XAttribute("Label", (ee.ToString() ?? "[null]") + Modified(ee)), new XAttribute("TypeName", ee.GetType().TypeName()), - new XAttribute("Background", ColorExtensions.ToHtmlColor(ee.GetType().FullName.GetHashCode())), + new XAttribute("Background", ColorExtensions.ToHtmlColor(ee.GetType().FullName!.GetHashCode())), }; } @@ -324,7 +326,7 @@ private static XAttribute[] GetAttributes(IList list) new XAttribute("Label", (list.ToString() ?? "[null]") + Modified((Modifiable)list)), new XAttribute("TypeName", list.GetType().TypeName()), new XAttribute("NodeRadius", 2), - new XAttribute("Background", ColorExtensions.ToHtmlColor(list.GetType().ElementType()!.FullName.GetHashCode())), + new XAttribute("Background", ColorExtensions.ToHtmlColor(list.GetType().ElementType()!.FullName!.GetHashCode())), }; } @@ -360,7 +362,7 @@ public class IntegrityCheckException : Exception { public Dictionary Errors { - get { return (Dictionary)this.Data["integrityErrors"]; } + get { return (Dictionary)this.Data["integrityErrors"]!; } set { this.Data["integrityErrors"] = value; } } diff --git a/Signum.Entities/Reflection/ModifyInspector.cs b/Signum.Entities/Reflection/ModifyInspector.cs index 96c371977b..9465adf328 100644 --- a/Signum.Entities/Reflection/ModifyInspector.cs +++ b/Signum.Entities/Reflection/ModifyInspector.cs @@ -56,10 +56,9 @@ public static IEnumerable FullExplore(Modifiable obj) Type t = obj.GetType().ElementType()!; if (Reflector.IsModifiableIdentifiableOrLite(t)) { - IEnumerable col = (IEnumerable)obj; - foreach (Modifiable item in col) + foreach (var item in (IEnumerable)obj) if (item != null) - yield return item; + yield return (Modifiable)item; } } else @@ -94,10 +93,9 @@ public static IEnumerable FullExploreVirtual(Modifiable obj) Type t = obj.GetType().ElementType()!; if (Reflector.IsModifiableIdentifiableOrLite(t)) { - IEnumerable col = (IEnumerable)obj; - foreach (Modifiable item in col!) + foreach (var item in (IEnumerable)obj!) if (item != null) - yield return item; + yield return (Modifiable)item; } } else @@ -133,10 +131,9 @@ public static IEnumerable EntityExplore(Modifiable obj) if (t.IsModifiable() && !t.IsEntity()) { - IEnumerable col = (IEnumerable)obj; - foreach (Modifiable item in col) + foreach (var item in (IEnumerable)obj) if (item != null) - yield return item; + yield return (Modifiable)item; } } else diff --git a/Signum.Entities/Reflection/Reflector.cs b/Signum.Entities/Reflection/Reflector.cs index 44dfe6c331..43e974a426 100644 --- a/Signum.Entities/Reflection/Reflector.cs +++ b/Signum.Entities/Reflection/Reflector.cs @@ -171,7 +171,7 @@ public static FieldInfo[] InstanceFieldsInOrder(Type type) { using (HeavyProfiler.LogNoStackTrace("Reflector", () => type.Name)) { - var result = type.For(t => t != typeof(object), t => t.BaseType) + var result = type.For(t => t != typeof(object), t => t.BaseType!) .Reverse() .SelectMany(t => t.GetFields(flags | BindingFlags.DeclaredOnly).OrderBy(f => f.MetadataToken)).ToArray(); @@ -251,7 +251,7 @@ public static MemberInfo[] GetMemberListBase(Expression e) case ExpressionType.MemberAccess: { MemberExpression me = (MemberExpression)e; - if (me.Member.DeclaringType.IsLite() && !me.Member.Name.StartsWith("Entity")) + if (me.Member.DeclaringType!.IsLite() && !me.Member.Name.StartsWith("Entity")) throw new InvalidOperationException("Members of Lite not supported"); return me.Member; @@ -286,10 +286,10 @@ internal static FieldInfo FindFieldInfo(Type type, PropertyInfo value) static readonly BindingFlags privateFlags = BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.NonPublic; public static FieldInfo? TryFindFieldInfo(Type type, PropertyInfo pi) { - string? prefix = pi.DeclaringType != type && pi.DeclaringType.IsInterface ? pi.DeclaringType.FullName + "." : null; + string? prefix = pi.DeclaringType != type && pi.DeclaringType!.IsInterface ? pi.DeclaringType.FullName + "." : null; FieldInfo? fi = null; - for (Type tempType = type; tempType != null && fi == null; tempType = tempType.BaseType) + for (Type? tempType = type; tempType != null && fi == null; tempType = tempType.BaseType) { fi = tempType.GetField("<" + pi.Name + ">k__BackingField", privateFlags) ?? (prefix != null ? tempType.GetField("<" + prefix + pi.Name + ">k__BackingField", privateFlags) : null); @@ -306,7 +306,7 @@ internal static FieldInfo FindFieldInfo(Type type, PropertyInfo value) private static void CheckSignumProcessed(FieldInfo fieldInfo) { - var isProcessed = processedAssemblies.GetOrAdd(fieldInfo.DeclaringType.Assembly, + var isProcessed = processedAssemblies.GetOrAdd(fieldInfo.DeclaringType!.Assembly, a => a.GetCustomAttributes().Any(gc => gc.Tool == "SignumTask")); if (!isProcessed) @@ -340,7 +340,7 @@ public static PropertyInfo FindPropertyInfo(FieldInfo fi) else propertyName = fi.Name.FirstUpper(); - var result = fi.DeclaringType.GetProperty(propertyName, flags, null, null, new Type[0], null); + var result = fi.DeclaringType!.GetProperty(propertyName, flags, null, null, new Type[0], null); if (result != null) return result; @@ -358,7 +358,7 @@ public static PropertyInfo FindPropertyInfo(FieldInfo fi) } catch (Exception e) { - throw new InvalidOperationException(e.Message + $" (FieldInfo: {fi.FieldName()} DeclaringType: {fi.DeclaringType.TypeName()})", e); + throw new InvalidOperationException(e.Message + $" (FieldInfo: {fi.FieldName()} DeclaringType: {fi.DeclaringType!.TypeName()})", e); } } @@ -401,7 +401,7 @@ public static bool QueryableProperty(Type type, PropertyInfo pi) { PropertyRoute simpleRoute = route.SimplifyToProperty(); - FormatAttribute format = simpleRoute.PropertyInfo.GetCustomAttribute(); + FormatAttribute? format = simpleRoute.PropertyInfo!.GetCustomAttribute(); if (format != null) return format.Format; diff --git a/Signum.Entities/Signum.Entities.csproj b/Signum.Entities/Signum.Entities.csproj index 082d08fefc..becfcbe311 100644 --- a/Signum.Entities/Signum.Entities.csproj +++ b/Signum.Entities/Signum.Entities.csproj @@ -1,27 +1,35 @@ - - - - netcoreapp3.0 - preview - true - enable - true - x64;x86;AnyCPU - NU1605 - - - - - - - - - - - - - - PreserveNewest - - - + + + + netcoreapp3.0 + preview + true + enable + true + x64;x86;AnyCPU + NU1605 + + + + + + + + + + + + + + + + PreserveNewest + + + + + + + + + diff --git a/Signum.Entities/TypeAttributes.cs b/Signum.Entities/TypeAttributes.cs index ba4d70542f..fd24a58470 100644 --- a/Signum.Entities/TypeAttributes.cs +++ b/Signum.Entities/TypeAttributes.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Concurrent; using System.Reflection; using Signum.Entities.Reflection; @@ -117,7 +117,7 @@ public static EntityKindAttribute TryGetAttribute(Type type) if (!t.IsIEntity()) throw new InvalidOperationException("{0} should be a non-abstrat Entity".FormatWith(type.TypeName())); - return t.GetCustomAttribute(true); + return t.GetCustomAttribute(true)!; }); } @@ -255,4 +255,4 @@ public enum EntityData /// Transactional } -} \ No newline at end of file +} diff --git a/Signum.Entities/Validator.cs b/Signum.Entities/Validator.cs index 1fa7771a0f..16776341c0 100644 --- a/Signum.Entities/Validator.cs +++ b/Signum.Entities/Validator.cs @@ -25,7 +25,7 @@ public static IDisposable ModelBinderScope() return new Disposable(() => inModelBinderVariable.Value = old); } - public static Func GlobalValidation { get; set; } + public static Func? GlobalValidation { get; set; } static readonly Polymorphic> validators = new Polymorphic>(PolymorphicMerger.InheritDictionary, typeof(ModifiableEntity)); @@ -44,7 +44,7 @@ static void GenerateType() where T : ModifiableEntity return; if(typeof(T) != typeof(ModifiableEntity)) - GenerateType(typeof(T).BaseType); + GenerateType(typeof(T).BaseType!); var dic = (from pi in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) where !pi.HasAttribute() && !pi.HasAttribute() diff --git a/Signum.MSBuildTask/Program.cs b/Signum.MSBuildTask/Program.cs index 3b73280ac1..40797b3468 100644 --- a/Signum.MSBuildTask/Program.cs +++ b/Signum.MSBuildTask/Program.cs @@ -51,7 +51,10 @@ public static int Main(string[] args) return 0; } - var errors = new ExpressionFieldGenerator(assembly, resolver, log).FixAutoExpressionField(); + log.WriteLine("Signum.MSBuildTask doing nothing"); + + bool errors = false; + errors |= new ExpressionFieldGenerator(assembly, resolver, log).FixAutoExpressionField(); errors |= new FieldAutoInitializer(assembly, resolver, log).FixAutoInitializer(); errors |= new AutoPropertyConverter(assembly, resolver).FixProperties(); diff --git a/Signum.MSBuildTask/Signum.MSBuildTask.csproj b/Signum.MSBuildTask/Signum.MSBuildTask.csproj index 8ef52fef1e..d505f1eb58 100644 --- a/Signum.MSBuildTask/Signum.MSBuildTask.csproj +++ b/Signum.MSBuildTask/Signum.MSBuildTask.csproj @@ -14,7 +14,7 @@ - + \ No newline at end of file diff --git a/Signum.React/ApiControllers/OperationController.cs b/Signum.React/ApiControllers/OperationController.cs index a2c24e7413..f9b742ed1d 100644 --- a/Signum.React/ApiControllers/OperationController.cs +++ b/Signum.React/ApiControllers/OperationController.cs @@ -227,7 +227,7 @@ public StateCanExecuteResponse StateCanExecutes([Required, FromBody]StateCanExec } - public static Func[], bool> AnyReadonly; + public static Func[], bool>? AnyReadonly; #pragma warning disable CS8618 // Non-nullable field is uninitialized. public class StateCanExecuteRequest diff --git a/Signum.React/Facades/ReflectionServer.cs b/Signum.React/Facades/ReflectionServer.cs index 6c5a6d1353..a5a7304b7c 100644 --- a/Signum.React/Facades/ReflectionServer.cs +++ b/Signum.React/Facades/ReflectionServer.cs @@ -35,7 +35,7 @@ public static object GetCurrentValidCulture() public static ConcurrentDictionary> cache = new ConcurrentDictionary>(); - public static Dictionary> EntityAssemblies; + public static Dictionary> EntityAssemblies = null!; public static ResetLazy> TypesByName = new ResetLazy>( () => GetTypes().Where(t => typeof(ModifiableEntity).IsAssignableFrom(t) || @@ -45,7 +45,7 @@ public static object GetCurrentValidCulture() public static void RegisterLike(Type type) { TypesByName.Reset(); - EntityAssemblies.GetOrCreate(type.Assembly).Add(type.Namespace); + EntityAssemblies.GetOrCreate(type.Assembly).Add(type.Namespace!); } internal static void Start() @@ -55,16 +55,16 @@ internal static void Start() var mainTypes = Schema.Current.Tables.Keys; var mixins = mainTypes.SelectMany(t => MixinDeclarations.GetMixinDeclarations(t)); - var operations = OperationLogic.RegisteredOperations.Select(o => o.FieldInfo.DeclaringType); + var operations = OperationLogic.RegisteredOperations.Select(o => o.FieldInfo.DeclaringType!); - EntityAssemblies = mainTypes.Concat(mixins).Concat(operations).AgGroupToDictionary(t => t.Assembly, gr => gr.Select(a => a.Namespace).ToHashSet()); - EntityAssemblies[typeof(PaginationMode).Assembly].Add(typeof(PaginationMode).Namespace); + EntityAssemblies = mainTypes.Concat(mixins).Concat(operations).AgGroupToDictionary(t => t.Assembly, gr => gr.Select(a => a.Namespace!).ToHashSet()); + EntityAssemblies[typeof(PaginationMode).Assembly].Add(typeof(PaginationMode).Namespace!); } const BindingFlags instanceFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly; const BindingFlags staticFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly; - public static event Action AddTypeExtension; + public static event Action? AddTypeExtension; static TypeInfoTS OnAddTypeExtension(TypeInfoTS ti, Type t) { foreach (var a in AddTypeExtension.GetInvocationListTyped()) @@ -73,7 +73,7 @@ static TypeInfoTS OnAddTypeExtension(TypeInfoTS ti, Type t) return ti; } - public static event Action AddPropertyRouteExtension; + public static event Action? AddPropertyRouteExtension; static MemberInfoTS OnAddPropertyRouteExtension(MemberInfoTS mi, PropertyRoute m) { if (AddPropertyRouteExtension == null) @@ -86,7 +86,7 @@ static MemberInfoTS OnAddPropertyRouteExtension(MemberInfoTS mi, PropertyRoute m } - public static event Action AddFieldInfoExtension; + public static event Action? AddFieldInfoExtension; static MemberInfoTS OnAddFieldInfoExtension(MemberInfoTS mi, FieldInfo m) { if (AddFieldInfoExtension == null) @@ -98,7 +98,7 @@ static MemberInfoTS OnAddFieldInfoExtension(MemberInfoTS mi, FieldInfo m) return mi; } - public static event Action AddOperationExtension; + public static event Action? AddOperationExtension; static OperationInfoTS OnAddOperationExtension(OperationInfoTS oi, OperationInfo o, Type type) { if (AddOperationExtension == null) @@ -135,7 +135,7 @@ public static List GetTypes() { return EntityAssemblies.SelectMany(kvp => { - var normalTypes = kvp.Key.GetTypes().Where(t => kvp.Value.Contains(t.Namespace)); + var normalTypes = kvp.Key.GetTypes().Where(t => kvp.Value.Contains(t.Namespace!)); var usedEnums = (from type in normalTypes where typeof(ModifiableEntity).IsAssignableFrom(type) @@ -170,7 +170,7 @@ where typeof(ModelEntity).IsAssignableFrom(type) && !type.IsAbstract select KVP.Create(GetTypeName(type), OnAddTypeExtension(new TypeInfoTS { Kind = KindOfType.Entity, - FullName = type.FullName, + FullName = type.FullName!, NiceName = descOptions.HasFlag(DescriptionOptions.Description) ? type.NiceName() : null, NicePluralName = descOptions.HasFlag(DescriptionOptions.PluralDescription) ? type.NicePluralName() : null, Gender = descOptions.HasFlag(DescriptionOptions.Gender) ? type.GetGender().ToString() : null, @@ -248,10 +248,10 @@ where type.IsEnum select KVP.Create(GetTypeName(type), OnAddTypeExtension(new TypeInfoTS { Kind = kind, - FullName = type.FullName, + FullName = type.FullName!, NiceName = descOptions.HasFlag(DescriptionOptions.Description) ? type.NiceName() : null, Members = type.GetFields(staticFlags) - .Where(fi => kind != KindOfType.Query || queries.QueryDefined(fi.GetValue(null))) + .Where(fi => kind != KindOfType.Query || queries.QueryDefined(fi.GetValue(null)!)) .ToDictionary(fi => fi.Name, fi => OnAddFieldInfoExtension(new MemberInfoTS { NiceName = fi.NiceName(), @@ -271,7 +271,7 @@ where type.IsStaticClass() && type.HasAttribute() select KVP.Create(GetTypeName(type), OnAddTypeExtension(new TypeInfoTS { Kind = KindOfType.SymbolContainer, - FullName = type.FullName, + FullName = type.FullName!, Members = type.GetFields(staticFlags) .Select(f => GetSymbolInfo(f)) .Where(s => @@ -291,7 +291,7 @@ select KVP.Create(GetTypeName(type), OnAddTypeExtension(new TypeInfoTS private static (FieldInfo FieldInfo, PrimaryKey? IdOrNull) GetSymbolInfo(FieldInfo m) { - object v = m.GetValue(null); + object? v = m.GetValue(null); if (v is IOperationSymbolContainer osc) v = osc.Symbol; diff --git a/Signum.React/Facades/SignumControllerFactory.cs b/Signum.React/Facades/SignumControllerFactory.cs index de1ca3ea20..ae273589ed 100644 --- a/Signum.React/Facades/SignumControllerFactory.cs +++ b/Signum.React/Facades/SignumControllerFactory.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Signum.Utilities; @@ -26,16 +26,16 @@ public static void RegisterController() } public static Dictionary> AllowedAreas { get; private set; } = new Dictionary>(); - public static void RegisterArea(MethodBase mb) => RegisterArea(mb.DeclaringType); + public static void RegisterArea(MethodBase? mb) => RegisterArea(mb!.DeclaringType!); public static void RegisterArea(Type type) { - AllowedAreas.GetOrCreate(type.Assembly).Add(type.Namespace); + AllowedAreas.GetOrCreate(type.Assembly).Add(type.Namespace!); } public void PopulateFeature(IEnumerable parts, ControllerFeature feature) { var allowed = feature.Controllers.Where(ti => ti.Assembly == MainAssembly || - (AllowedAreas.TryGetC(ti.Assembly)?.Any(ns => ti.Namespace.StartsWith(ns)) ?? false) || + (AllowedAreas.TryGetC(ti.Assembly)?.Any(ns => ti.Namespace!.StartsWith(ns)) ?? false) || AllowedControllers.Contains(ti.AsType())); var toRemove = feature.Controllers.Where(ti => !allowed.Contains(ti)); diff --git a/Signum.React/Facades/SignumServer.cs b/Signum.React/Facades/SignumServer.cs index 57b5cd25a7..9ba7549a56 100644 --- a/Signum.React/Facades/SignumServer.cs +++ b/Signum.React/Facades/SignumServer.cs @@ -19,9 +19,9 @@ namespace Signum.React.Facades { public static class SignumServer { - public static JsonSerializerSettings JsonSerializerSettings; + public static JsonSerializerSettings JsonSerializerSettings = null!; - public static MvcJsonOptions AddSignumJsonConverters(this MvcJsonOptions jsonOptions) + public static MvcNewtonsoftJsonOptions AddSignumJsonConverters(this MvcNewtonsoftJsonOptions jsonOptions) { //Signum converters jsonOptions.SerializerSettings.Do(s => @@ -56,14 +56,14 @@ public static MvcOptions AddSignumGlobalFilters(this MvcOptions options) return options; } - public static void Start(IApplicationBuilder app, IHostingEnvironment hostingEnvironment, Assembly mainAsembly) + public static void Start(IApplicationBuilder app, IWebHostEnvironment hostingEnvironment, Assembly mainAsembly) { Schema.Current.ApplicationName = hostingEnvironment.ContentRootPath; //app.Services.Replace(typeof(IHttpControllerSelector), new SignumControllerFactory(config, mainAsembly)); SignumControllerFactory.RegisterArea(typeof(EntitiesController)); - SignumControllerFactory.RegisterArea(MethodInfo.GetCurrentMethod()); + SignumControllerFactory.RegisterArea(MethodInfo.GetCurrentMethod()!); //// Web API configuration and services @@ -112,7 +112,7 @@ public class EntityPackTS [JsonExtensionData] public Dictionary extension { get; set; } = new Dictionary(); - public static Action AddExtension; + public static Action? AddExtension; public EntityPackTS(Entity entity, Dictionary canExecute) { diff --git a/Signum.React/Filters/SignumExceptionFilterAttribute.cs b/Signum.React/Filters/SignumExceptionFilterAttribute.cs index 6e91c6751c..b3c15c9c08 100644 --- a/Signum.React/Filters/SignumExceptionFilterAttribute.cs +++ b/Signum.React/Filters/SignumExceptionFilterAttribute.cs @@ -126,7 +126,7 @@ public class HttpError public HttpError(Exception e, bool includeErrorDetails = true) { this.ExceptionMessage = e.Message; - this.ExceptionType = e.GetType().FullName; + this.ExceptionType = e.GetType().FullName!; if (includeErrorDetails) { this.ExceptionId = e.GetExceptionEntity()?.Id.ToString(); diff --git a/Signum.React/Filters/SignumFilters.cs b/Signum.React/Filters/SignumFilters.cs index cfc9e109af..88948355cc 100644 --- a/Signum.React/Filters/SignumFilters.cs +++ b/Signum.React/Filters/SignumFilters.cs @@ -72,7 +72,7 @@ public SignumAuthenticationFilter() : base("Signum_User") { } public class SignumCultureSelectorFilter : IResourceFilter { - public static Func GetCurrentCultures; + public static Func? GetCurrentCultures; const string Culture_Key = "OldCulture"; const string UICulture_Key = "OldUICulture"; @@ -174,7 +174,7 @@ public void OnResourceExecuting(ResourceExecutingContext context) public void OnResourceExecuted(ResourceExecutedContext context) { - if (context.HttpContext.Items.TryGetValue(ResourceKey, out object result)) + if (context.HttpContext.Items.TryGetValue(ResourceKey, out object? result)) { if (result != null) ((IDisposable)result).Dispose(); diff --git a/Signum.React/Filters/VersionFilterAttribute.cs b/Signum.React/Filters/VersionFilterAttribute.cs index 9e3b4724e8..3e9df347bc 100644 --- a/Signum.React/Filters/VersionFilterAttribute.cs +++ b/Signum.React/Filters/VersionFilterAttribute.cs @@ -1,4 +1,4 @@ -using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.AspNetCore.Mvc.Filters; using System.Reflection; namespace Signum.React.Filters @@ -6,7 +6,7 @@ namespace Signum.React.Filters public class VersionFilterAttribute : ActionFilterAttribute { //In Global.asax: VersionFilterAttribute.CurrentVersion = CustomAssembly.GetName().Version.ToString() - public static string CurrentVersion = Assembly.GetEntryAssembly().GetName().Version.ToString(); + public static string CurrentVersion = Assembly.GetEntryAssembly()!.GetName().Version!.ToString()!; public override void OnActionExecuted(ActionExecutedContext context) { @@ -15,4 +15,4 @@ public override void OnActionExecuted(ActionExecutedContext context) context.HttpContext.Response.Headers.Add("X-App-Version", CurrentVersion); } } -} \ No newline at end of file +} diff --git a/Signum.React/JsonConverters/ArgsJsonConverter.cs b/Signum.React/JsonConverters/ArgsJsonConverter.cs index 49e78d5482..07369b98a1 100644 --- a/Signum.React/JsonConverters/ArgsJsonConverter.cs +++ b/Signum.React/JsonConverters/ArgsJsonConverter.cs @@ -33,7 +33,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { - var request = (OperationController.BaseOperationRequest)Activator.CreateInstance(objectType); + var request = (OperationController.BaseOperationRequest)Activator.CreateInstance(objectType)!; serializer.Populate(reader, request); var operationSymbol = SymbolLogic.ToSymbol(request.operationKey); if (request.args != null) diff --git a/Signum.React/JsonConverters/EntityJsonConverter.cs b/Signum.React/JsonConverters/EntityJsonConverter.cs index 963b2c7fd7..9d32e843f0 100644 --- a/Signum.React/JsonConverters/EntityJsonConverter.cs +++ b/Signum.React/JsonConverters/EntityJsonConverter.cs @@ -221,7 +221,7 @@ private static PropertyRoute GetCurrentPropertyRoute(object value) return pr; } - public static Func CanReadPropertyRoute; + public static Func? CanReadPropertyRoute; public void WriteJsonProperty(JsonWriter writer, JsonSerializer serializer, ModifiableEntity mod, string lowerCaseName, PropertyConverter pc, PropertyRoute route) { @@ -401,7 +401,7 @@ private bool IsEquals(object newValue, object? oldValue) } - public static Func CanWritePropertyRoute; + public static Func? CanWritePropertyRoute; public static void AssertCanWrite(PropertyRoute pr) { string? error = CanWritePropertyRoute?.Invoke(pr); @@ -425,7 +425,7 @@ public ModifiableEntity GetEntity(JsonReader reader, Type objectType, object exi if (identityInfo.IsNew == true) { - var result = (ModifiableEntity)Activator.CreateInstance(type, nonPublic: true); + var result = (ModifiableEntity)Activator.CreateInstance(type, nonPublic: true)!; if (identityInfo.Id != null) ((Entity)result).SetId(PrimaryKey.Parse(identityInfo.Id, type)); @@ -462,7 +462,7 @@ public ModifiableEntity GetEntity(JsonReader reader, Type objectType, object exi var existingMod = (ModifiableEntity)existingValue; if (existingMod == null || existingMod.GetType() != type) - return (ModifiableEntity)Activator.CreateInstance(type, nonPublic: true); + return (ModifiableEntity)Activator.CreateInstance(type, nonPublic: true)!; return existingMod; } diff --git a/Signum.React/JsonModelValidators/Bla.cs b/Signum.React/JsonModelValidators/Bla.cs new file mode 100644 index 0000000000..afee07db28 --- /dev/null +++ b/Signum.React/JsonModelValidators/Bla.cs @@ -0,0 +1,121 @@ +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Threading.Tasks; + +namespace Signum.React.JsonModelValidators +{ + /// + /// The default implementation of for a complex object. + /// + internal class DefaultComplexObjectValidationStrategy : IValidationStrategy + { + private static readonly bool IsMono = Type.GetType("Mono.Runtime") != null; + + /// + /// Gets an instance of . + /// + public static readonly IValidationStrategy Instance = new DefaultComplexObjectValidationStrategy(); + + private DefaultComplexObjectValidationStrategy() + { + } + + /// + public IEnumerator GetChildren( + ModelMetadata metadata, + string key, + object model) + { + return new Enumerator(metadata.Properties, key, model); + } + + private class Enumerator : IEnumerator + { + private readonly string _key; + private readonly object _model; + private readonly ModelPropertyCollection _properties; + + private ValidationEntry _entry; + private int _index; + + public Enumerator( + ModelPropertyCollection properties, + string key, + object model) + { + _properties = properties; + _key = key; + _model = model; + + _index = -1; + } + + public ValidationEntry Current => _entry; + + object IEnumerator.Current => Current; + + public bool MoveNext() + { + _index++; + if (_index >= _properties.Count) + { + return false; + } + + var property = _properties[_index]; + var propertyName = property.BinderModelName ?? property.PropertyName; + var key = ModelNames.CreatePropertyModelName(_key, propertyName); + + if (_model == null) + { + // Performance: Never create a delegate when container is null. + _entry = new ValidationEntry(property, key, model: null); + } + else if (IsMono) + { + _entry = new ValidationEntry(property, key, () => GetModelOnMono(_model, property.PropertyName)); + } + else + { + _entry = new ValidationEntry(property, key, () => GetModel(_model, property)); + } + + return true; + } + + public void Dispose() + { + } + + public void Reset() + { + throw new NotImplementedException(); + } + + private static object GetModel(object container, ModelMetadata property) + { + return property.PropertyGetter(container); + } + + // Our property accessors don't work on Mono 4.0.4 - see https://github.com/aspnet/External/issues/44 + // This is a workaround for what the PropertyGetter does in the background. + private static object? GetModelOnMono(object container, string propertyName) + { + var propertyInfo = container.GetType().GetProperty(propertyName)!; + try + { + return propertyInfo.GetValue(container); + } + catch (TargetInvocationException ex) + { + throw ex.InnerException!; + } + } + } + } +} diff --git a/Signum.React/JsonModelValidators/DefaultCollectionValidationStrategy.cs b/Signum.React/JsonModelValidators/DefaultCollectionValidationStrategy.cs new file mode 100644 index 0000000000..ed0cdd0f3c --- /dev/null +++ b/Signum.React/JsonModelValidators/DefaultCollectionValidationStrategy.cs @@ -0,0 +1,141 @@ +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Threading.Tasks; + +namespace Signum.React.JsonModelValidators +{ + + /// + /// The default implementation of for a collection. + /// + /// + /// This implementation handles cases like: + /// + /// Model: IList<Student> + /// Query String: ?students[0].Age=8&students[1].Age=9 + /// + /// In this case the elements of the collection are identified in the input data set by an incrementing + /// integer index. + /// + /// + /// or: + /// + /// + /// Model: IDictionary<string, int> + /// Query String: ?students[0].Key=Joey&students[0].Value=8 + /// + /// In this case the dictionary is treated as a collection of key-value pairs, and the elements of the + /// collection are identified in the input data set by an incrementing integer index. + /// + /// + /// Using this key format, the enumerator enumerates model objects of type matching + /// . The indices of the elements in the collection are used to + /// compute the model prefix keys. + /// + internal class DefaultCollectionValidationStrategy : IValidationStrategy + { + private static readonly MethodInfo _getEnumerator = typeof(DefaultCollectionValidationStrategy) + .GetMethod(nameof(GetEnumerator), BindingFlags.Static | BindingFlags.NonPublic)!; + + /// + /// Gets an instance of . + /// + public static readonly DefaultCollectionValidationStrategy Instance = new DefaultCollectionValidationStrategy(); + private readonly ConcurrentDictionary> _genericGetEnumeratorCache = new ConcurrentDictionary>(); + + private DefaultCollectionValidationStrategy() + { + } + + /// + public IEnumerator GetChildren( + ModelMetadata metadata, + string key, + object model) + { + var enumerator = GetEnumeratorForElementType(metadata, model); + return new Enumerator(metadata.ElementMetadata, key, enumerator); + } + + public IEnumerator GetEnumeratorForElementType(ModelMetadata metadata, object model) + { + Func getEnumerator = _genericGetEnumeratorCache.GetOrAdd( + key: metadata.ElementType, + valueFactory: (type) => { + var getEnumeratorMethod = _getEnumerator.MakeGenericMethod(type); + var parameter = Expression.Parameter(typeof(object), "model"); + var expression = + Expression.Lambda>( + Expression.Call(null, getEnumeratorMethod, parameter), + parameter); + return expression.Compile(); + }); + + return getEnumerator(model); + } + + // Called via reflection. + private static IEnumerator GetEnumerator(object model) + { + return (model as IEnumerable)?.GetEnumerator() ?? ((IEnumerable)model).GetEnumerator(); + } + + private class Enumerator : IEnumerator + { + private readonly string _key; + private readonly ModelMetadata _metadata; + private readonly IEnumerator _enumerator; + + private ValidationEntry _entry; + private int _index; + + public Enumerator( + ModelMetadata metadata, + string key, + IEnumerator enumerator) + { + _metadata = metadata; + _key = key; + _enumerator = enumerator; + + _index = -1; + } + + public ValidationEntry Current => _entry; + + object IEnumerator.Current => Current; + + public bool MoveNext() + { + _index++; + if (!_enumerator.MoveNext()) + { + return false; + } + + var key = ModelNames.CreateIndexModelName(_key, _index); + var model = _enumerator.Current; + + _entry = new ValidationEntry(_metadata, key, model); + + return true; + } + + public void Dispose() + { + } + + public void Reset() + { + _enumerator.Reset(); + } + } + } +} diff --git a/Signum.React/JsonModelValidators/DefaultValidator.cs b/Signum.React/JsonModelValidators/DefaultValidator.cs index 0213d21a27..e68d5590f1 100644 --- a/Signum.React/JsonModelValidators/DefaultValidator.cs +++ b/Signum.React/JsonModelValidators/DefaultValidator.cs @@ -5,12 +5,10 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Internal; using Microsoft.AspNetCore.Mvc.ModelBinding; -using Microsoft.AspNetCore.Mvc.ModelBinding.Internal; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; -namespace Signum.React +namespace Signum.React.JsonModelValidators { /// /// A visitor implementation that interprets to traverse @@ -18,6 +16,8 @@ namespace Signum.React /// public class ValidationVisitor { + protected readonly ValidationStack CurrentPath; + /// /// Creates a new . /// @@ -29,9 +29,7 @@ public class ValidationVisitor public ValidationVisitor( ActionContext actionContext, IModelValidatorProvider validatorProvider, -#pragma warning disable PUB0001 // Pubternal type in public API ValidatorCache validatorCache, -#pragma warning restore PUB0001 IModelMetadataProvider metadataProvider, ValidationStateDictionary validationState) { @@ -63,15 +61,11 @@ public ValidationVisitor( protected IModelValidatorProvider ValidatorProvider { get; } protected IModelMetadataProvider MetadataProvider { get; } -#pragma warning disable PUB0001 // Pubternal type in public API + protected ValidatorCache Cache { get; } -#pragma warning restore PUB0001 protected ActionContext Context { get; } protected ModelStateDictionary ModelState { get; } protected ValidationStateDictionary ValidationState { get; } -#pragma warning disable PUB0001 // Pubternal type in public API - protected ValidationStack CurrentPath { get; } -#pragma warning restore PUB0001 protected object? Container { get; set; } protected string? Key { get; set; } @@ -79,6 +73,7 @@ public ValidationVisitor( protected ModelMetadata? Metadata { get; set; } protected IValidationStrategy? Strategy { get; set; } + /// /// Indicates whether validation of a complex type should be performed if validation fails for any of its children. The default behavior is false. /// @@ -103,12 +98,15 @@ public bool Validate(ModelMetadata metadata, string key, object model) /// The model object. /// If true, applies validation rules even if the top-level value is null. /// true if the object is valid, otherwise false. - public virtual bool Validate(ModelMetadata? metadata, string key, object? model, bool alwaysValidateAtTopLevel) + public virtual bool Validate(ModelMetadata? metadata, string? key, object? model, bool alwaysValidateAtTopLevel) { if (model == null && key != null && !alwaysValidateAtTopLevel) { var entry = ModelState[key]; - if (entry != null && entry.ValidationState != ModelValidationState.Valid) + + // Rationale: We might see the same model state key for two different objects and want to preserve any + // known invalidity. + if (entry != null && entry.ValidationState != ModelValidationState.Invalid) { entry.ValidationState = ModelValidationState.Valid; } @@ -181,7 +179,7 @@ protected virtual bool ValidateNode() } } - protected virtual bool Visit(ModelMetadata? metadata, string key, object model) + protected virtual bool Visit(ModelMetadata? metadata, string? key, object? model) { RuntimeHelpers.EnsureSufficientExecutionStack(); @@ -208,6 +206,24 @@ protected virtual bool Visit(ModelMetadata? metadata, string key, object model) CurrentPath.Pop(model); return true; } + // If the metadata indicates that no validators exist AND the aggregate state for the key says that the model graph + // is not invalid (i.e. is one of Unvalidated, Valid, or Skipped) we can safely mark the graph as valid. + else if (metadata!.HasValidators == false && + ModelState.GetFieldValidationState(key) != ModelValidationState.Invalid) + { + // No validators will be created for this graph of objects. Mark it as valid if it wasn't previously validated. + var entries = ModelState.FindKeysWithPrefix(key); + foreach (var item in entries) + { + if (item.Value.ValidationState == ModelValidationState.Unvalidated) + { + item.Value.ValidationState = ModelValidationState.Valid; + } + } + + CurrentPath.Pop(model); + return true; + } using (StateManager.Recurse(this, key ?? string.Empty, metadata, model, strategy)) { @@ -240,7 +256,7 @@ protected virtual bool VisitComplexType(IValidationStrategy defaultStrategy) // Suppress validation for the entries matching this prefix. This will temporarily set // the current node to 'skipped' but we're going to visit it right away, so subsequent // code will set it to 'valid' or 'invalid' - SuppressValidation(Key!); + SuppressValidation(Key); } // Double-checking HasReachedMaxErrors just in case this model has no properties. @@ -257,7 +273,7 @@ protected virtual bool VisitSimpleType() { if (ModelState.HasReachedMaxErrors) { - SuppressValidation(Key!); + SuppressValidation(Key); return false; } @@ -287,7 +303,7 @@ protected virtual bool VisitChildren(IValidationStrategy strategy) return isValid; } - protected virtual void SuppressValidation(string key) + protected virtual void SuppressValidation(string? key) { if (key == null) { @@ -299,25 +315,30 @@ protected virtual void SuppressValidation(string key) var entries = ModelState.FindKeysWithPrefix(key); foreach (var entry in entries) { - entry.Value.ValidationState = ModelValidationState.Skipped; + if (entry.Value.ValidationState != ModelValidationState.Invalid) + { + entry.Value.ValidationState = ModelValidationState.Skipped; + } } } protected virtual ValidationStateEntry? GetValidationEntry(object? model) { if (model == null || ValidationState == null) + { return null; + } ValidationState.TryGetValue(model, out var entry); return entry; } - protected struct StateManager : IDisposable + protected readonly struct StateManager : IDisposable { private readonly ValidationVisitor _visitor; - private readonly object _container; - private readonly string _key; - private readonly ModelMetadata _metadata; + private readonly object? _container; + private readonly string? _key; + private readonly ModelMetadata? _metadata; private readonly object? _model; private readonly object? _newModel; private readonly IValidationStrategy? _strategy; @@ -345,10 +366,10 @@ public StateManager(ValidationVisitor visitor, object? newModel) _visitor = visitor; _newModel = newModel; - _container = _visitor.Container!; - _key = _visitor.Key!; - _metadata = _visitor.Metadata!; - _model = _visitor.Model!; + _container = _visitor.Container; + _key = _visitor.Key; + _metadata = _visitor.Metadata; + _model = _visitor.Model; _strategy = _visitor.Strategy; } diff --git a/Signum.React/JsonModelValidators/SignumObjectValidator.cs b/Signum.React/JsonModelValidators/SignumObjectValidator.cs index 036aabda62..f8c684dc12 100644 --- a/Signum.React/JsonModelValidators/SignumObjectValidator.cs +++ b/Signum.React/JsonModelValidators/SignumObjectValidator.cs @@ -1,15 +1,15 @@ using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Internal; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; using Signum.Entities; +using Signum.React.Json; using Signum.Utilities; using System; using System.Collections; using System.Collections.Generic; using System.Linq; -namespace Signum.React.Json +namespace Signum.React.JsonModelValidators { public class SignumObjectModelValidator : IObjectModelValidator { @@ -114,7 +114,7 @@ public ValidationVisitor GetValidationVisitor( } } - public class SignumValidationVisitor : Signum.React.ValidationVisitor + public class SignumValidationVisitor : ValidationVisitor { public SignumValidationVisitor( ActionContext actionContext, @@ -177,7 +177,7 @@ private bool ValidateMList(IMListPrivate mlist) Type elementType = mlist.GetType().ElementType()!; int i = 0; - foreach (object element in (IEnumerable)mlist) + foreach (object? element in (IEnumerable)mlist) { if (this.CurrentPath.Push(element)) diff --git a/Signum.React/JsonModelValidators/ValidationStack.cs b/Signum.React/JsonModelValidators/ValidationStack.cs new file mode 100644 index 0000000000..317f293d21 --- /dev/null +++ b/Signum.React/JsonModelValidators/ValidationStack.cs @@ -0,0 +1,73 @@ +using Signum.Utilities.DataStructures; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Threading.Tasks; + +namespace Signum.React.JsonModelValidators +{ + public class ValidationStack + { + public int Count => HashSet?.Count ?? List.Count; + + // We tested the performance of a list at size 15 and found it still better than hashset, but to avoid a costly + // O(n) search at larger n we set the cutoff to 20. If someone finds the point where they intersect feel free to change this number. + internal const int CutOff = 20; + + internal List List { get; } = new List(); + + internal HashSet? HashSet { get; set; } + + public bool Push(object? model) + { + if (HashSet != null) + { + return HashSet.Add(model); + } + + if (ListContains(model)) + { + return false; + } + + List.Add(model); + + if (HashSet == null && List.Count > CutOff) + { + HashSet = new HashSet(List, ReferenceEqualityComparer.Default!); + } + + return true; + } + + public void Pop(object? model) + { + if (HashSet != null) + { + HashSet.Remove(model); + } + else + { + if (model != null) + { + Debug.Assert(ReferenceEquals(List[List.Count - 1], model)); + List.RemoveAt(List.Count - 1); + } + } + } + + private bool ListContains(object? model) + { + for (var i = 0; i < List.Count; i++) + { + if (ReferenceEquals(model, List[i])) + { + return true; + } + } + + return false; + } + } +} diff --git a/Signum.React/Signum.React.csproj b/Signum.React/Signum.React.csproj index ec0b1517f3..9ece88b5ea 100644 --- a/Signum.React/Signum.React.csproj +++ b/Signum.React/Signum.React.csproj @@ -33,7 +33,7 @@ - + runtime; build; native; contentfiles; analyzers all @@ -46,6 +46,7 @@ + diff --git a/Signum.Test/Environment/MusicStarter.cs b/Signum.Test/Environment/MusicStarter.cs index 4459b16416..a525fe95c2 100644 --- a/Signum.Test/Environment/MusicStarter.cs +++ b/Signum.Test/Environment/MusicStarter.cs @@ -53,7 +53,7 @@ public static void Start(string connectionString) Connector.Default = new SqlConnector(connectionString, sb.Schema, sqlVersion ?? SqlServerVersion.SqlServer2017); - sb.Schema.Version = typeof(MusicStarter).Assembly.GetName().Version; + sb.Schema.Version = typeof(MusicStarter).Assembly.GetName().Version!; sb.Schema.Settings.FieldAttributes((OperationLogEntity ol) => ol.User).Add(new ImplementedByAttribute()); sb.Schema.Settings.FieldAttributes((ExceptionEntity e) => e.User).Add(new ImplementedByAttribute()); diff --git a/Signum.Test/LinqProvider/JoinGroupTest.cs b/Signum.Test/LinqProvider/JoinGroupTest.cs index fb6b687da9..a5630f3fdf 100644 --- a/Signum.Test/LinqProvider/JoinGroupTest.cs +++ b/Signum.Test/LinqProvider/JoinGroupTest.cs @@ -1,4 +1,4 @@ -using System.Linq; +using System.Linq; using Xunit; using Signum.Engine; using Signum.Entities; @@ -140,7 +140,7 @@ public void LeftOuterMyView() join b in Database.View() on a.ToLite() equals b.Artist into g select a.ToLite()).ToList(); - Assert.True(artists.All(a => a.ToString().StartsWith("M"))); + Assert.True(artists.All(a => a.ToString()!.StartsWith("M"))); var list1 = Database.View().ToList(); var list2 = Database.Query().Where(a => a.Name.StartsWith("M")).ToList(); diff --git a/Signum.Test/LinqProvider/SelectImplementations.cs b/Signum.Test/LinqProvider/SelectImplementations.cs index 5588358959..423732d06c 100644 --- a/Signum.Test/LinqProvider/SelectImplementations.cs +++ b/Signum.Test/LinqProvider/SelectImplementations.cs @@ -59,7 +59,7 @@ public void SelectLiteIBDouble() public void SelectLiteIBDoubleWhereUnion() { var query = Database.Query() - .Where(a => a.Author.CombineUnion().ToLite().ToString().Length > 0) + .Where(a => a.Author.CombineUnion().ToLite().ToString()!.Length > 0) .Select(a => a.Author.CombineUnion().ToLite()); Assert.Equal(3, query.QueryText().CountRepetitions("LEFT OUTER JOIN")); @@ -70,7 +70,7 @@ public void SelectLiteIBDoubleWhereUnion() public void SelectLiteIBDoubleWhereSwitch() { var query = Database.Query() - .Where(a => a.Author.CombineCase().ToLite().ToString().Length > 0) + .Where(a => a.Author.CombineCase().ToLite().ToString()!.Length > 0) .Select(a => a.Author.CombineCase().ToLite()); Assert.Equal(2, query.QueryText().CountRepetitions("LEFT OUTER JOIN")); @@ -184,7 +184,7 @@ public void SelectLiteIBWhereUnion() { var list = Database.Query() .Select(a => a.Author.CombineUnion().ToLite()) - .Where(a => a.ToString().StartsWith("Michael")).ToList(); + .Where(a => a.ToString()!.StartsWith("Michael")).ToList(); } [Fact] @@ -192,7 +192,7 @@ public void SelectLiteIBWhereSwitch() { var list = Database.Query() .Select(a => a.Author.CombineCase().ToLite()) - .Where(a => a.ToString().StartsWith("Michael")).ToList(); + .Where(a => a.ToString()!.StartsWith("Michael")).ToList(); } [Fact] diff --git a/Signum.Test/LinqProvider/SqlFunctionsTest.cs b/Signum.Test/LinqProvider/SqlFunctionsTest.cs index 257b79144a..dd35f699a2 100644 --- a/Signum.Test/LinqProvider/SqlFunctionsTest.cs +++ b/Signum.Test/LinqProvider/SqlFunctionsTest.cs @@ -74,13 +74,13 @@ public void CoalesceFirstOrDefault() [Fact] public void StringContainsUnion() { - var list = Database.Query().Where(a => !a.Author.CombineUnion().ToString().Contains("Hola")).ToList(); + var list = Database.Query().Where(a => !a.Author.CombineUnion().ToString()!.Contains("Hola")).ToList(); } [Fact] public void StringContainsSwitch() { - var list = Database.Query().Where(a => !a.Author.CombineCase().ToString().Contains("Hola")).ToList(); + var list = Database.Query().Where(a => !a.Author.CombineCase().ToString()!.Contains("Hola")).ToList(); } [Fact] diff --git a/Signum.Test/LinqProvider/WhereTest.cs b/Signum.Test/LinqProvider/WhereTest.cs index 7f5fbfde62..c0856a367b 100644 --- a/Signum.Test/LinqProvider/WhereTest.cs +++ b/Signum.Test/LinqProvider/WhereTest.cs @@ -263,7 +263,7 @@ public void WhereOptimize() public void WhereInnerQueryable() { var females = Database.Query().Where(a => a.Sex == Sex.Female); - string f = females.ToString(); + string f = females.ToString()!; var female = Database.Query().SingleEx(a => females.Contains(a)); } diff --git a/Signum.Utilities/DataStructures/RecentsDictionary.cs b/Signum.Utilities/DataStructures/RecentsDictionary.cs index f13220dda9..24d611a138 100644 --- a/Signum.Utilities/DataStructures/RecentsDictionary.cs +++ b/Signum.Utilities/DataStructures/RecentsDictionary.cs @@ -169,7 +169,7 @@ public int Count /// /// Event that is fired when an item falls outside of the cache /// - public event Action Purged; + public event Action? Purged; public override string ToString() { diff --git a/Signum.Utilities/DataStructures/ReferenceEqualityComparer.cs b/Signum.Utilities/DataStructures/ReferenceEqualityComparer.cs index db470ff8fd..1903a35511 100644 --- a/Signum.Utilities/DataStructures/ReferenceEqualityComparer.cs +++ b/Signum.Utilities/DataStructures/ReferenceEqualityComparer.cs @@ -6,9 +6,10 @@ namespace Signum.Utilities.DataStructures { [Serializable] - public class ReferenceEqualityComparer : IEqualityComparer, IEqualityComparer where T : class + public class ReferenceEqualityComparer : IEqualityComparer, IEqualityComparer + where T : class { - static ReferenceEqualityComparer _default; + static ReferenceEqualityComparer? _default; ReferenceEqualityComparer() { } diff --git a/Signum.Utilities/DescriptionManager.cs b/Signum.Utilities/DescriptionManager.cs index b39eda344f..9484aee997 100644 --- a/Signum.Utilities/DescriptionManager.cs +++ b/Signum.Utilities/DescriptionManager.cs @@ -123,7 +123,7 @@ public static class DescriptionManager public static event Func DefaultDescriptionOptions = t => t.IsEnum && t.Name.EndsWith("Message") ? DescriptionOptions.Members : (DescriptionOptions?)null; public static event Func ShouldLocalizeMemeber = m => true; - public static event Action NotLocalizedMember; + public static event Action? NotLocalizedMember; public static Dictionary> ExternalEnums = new Dictionary> { @@ -348,7 +348,7 @@ public static bool OnShouldLocalizeMember(MemberInfo m) return true; } - public static Action Invalidated; + public static Action? Invalidated; public static void Invalidate() { localizations.Clear(); diff --git a/Signum.Utilities/Disposable.cs b/Signum.Utilities/Disposable.cs index 7d900d835b..bf497c9e83 100644 --- a/Signum.Utilities/Disposable.cs +++ b/Signum.Utilities/Disposable.cs @@ -39,7 +39,7 @@ public void Dispose() () => { try { first!.Dispose(); } finally { second!.Dispose(); } }); } - public static IDisposable? Combine(Del delegated, Func invoke) where Del : class, ICloneable, ISerializable + public static IDisposable? Combine(Del? delegated, Func invoke) where Del : class, ICloneable, ISerializable { if (delegated == null) return null; diff --git a/Signum.Utilities/Extensions/EnumerableExtensions.cs b/Signum.Utilities/Extensions/EnumerableExtensions.cs index 349685aff7..1b25da88ba 100644 --- a/Signum.Utilities/Extensions/EnumerableExtensions.cs +++ b/Signum.Utilities/Extensions/EnumerableExtensions.cs @@ -1010,18 +1010,6 @@ public static IOrderedEnumerable OrderByDescending(this IEnumerable col #endregion #region Zip - public static IEnumerable<(A first, B second)> Zip(this IEnumerable colA, IEnumerable colB) - { - using (var enumA = colA.GetEnumerator()) - using (var enumB = colB.GetEnumerator()) - { - while (enumA.MoveNext() && enumB.MoveNext()) - { - yield return (first: enumA.Current, second: enumB.Current); - } - } - } - public static IEnumerable ZipOrDefault(this IEnumerable colA, IEnumerable colB, Func resultSelector) { bool okA = true, okB = true; diff --git a/Signum.Utilities/Extensions/StreamExtensions.cs b/Signum.Utilities/Extensions/StreamExtensions.cs index 0e28e90aee..02bce91919 100644 --- a/Signum.Utilities/Extensions/StreamExtensions.cs +++ b/Signum.Utilities/Extensions/StreamExtensions.cs @@ -139,7 +139,7 @@ public class ProgressStream : Stream { readonly Stream InnerStream; - public event EventHandler ProgressChanged; + public event EventHandler? ProgressChanged; public ProgressStream(Stream innerStream) { diff --git a/Signum.Utilities/Extensions/TreeHelper.cs b/Signum.Utilities/Extensions/TreeHelper.cs index a77a250cac..cc263eb9ca 100644 --- a/Signum.Utilities/Extensions/TreeHelper.cs +++ b/Signum.Utilities/Extensions/TreeHelper.cs @@ -160,8 +160,8 @@ public override string ToString() void Never() { - PropertyChanged(null, null); + PropertyChanged?.Invoke(null, null); } - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; } } diff --git a/Signum.Utilities/MyRandom.cs b/Signum.Utilities/MyRandom.cs index 1bbef6140f..b06a4353b4 100644 --- a/Signum.Utilities/MyRandom.cs +++ b/Signum.Utilities/MyRandom.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; @@ -7,17 +7,9 @@ namespace Signum.Utilities public static class MyRandom { [ThreadStatic] - static Random random; + static Random? random; - public static Random Current - { - get - { - if (random == null) - random = new Random(); - return random; - } - } + public static Random Current => random ??= new Random(); } public static class RandomExtensions diff --git a/Signum.Utilities/ProgressProxy.cs b/Signum.Utilities/ProgressProxy.cs index ed7cc94d47..1117f43fb6 100644 --- a/Signum.Utilities/ProgressProxy.cs +++ b/Signum.Utilities/ProgressProxy.cs @@ -12,7 +12,7 @@ public class ProgressProxy private int max; private int position; - public event EventHandler Changed; + public event EventHandler? Changed; public ProgressProxy() { diff --git a/Signum.Utilities/StartParameters.cs b/Signum.Utilities/StartParameters.cs index 23da701431..b27789ca31 100644 --- a/Signum.Utilities/StartParameters.cs +++ b/Signum.Utilities/StartParameters.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; namespace Signum.Utilities @@ -8,10 +8,10 @@ public static class StartParameters //The best development experience is to throw an exception when starting but in some scenarios is better to try to start at all costs: // * Green / Blue deployments where the Application and the DB could be mistmatched for a while - public static List IgnoredDatabaseMismatches; //Initialize to enable + public static List? IgnoredDatabaseMismatches; //Initialize to enable // * Dynamic code where everithing could happen (like duplicated entities, entities without operations, etc..) - public static List IgnoredCodeErrors;//Initialize to enable + public static List? IgnoredCodeErrors;//Initialize to enable public static List SelectCatch(this IEnumerable elements, Func selectorOrCrash) diff --git a/Signum.Utilities/Synchronization/ResetLazy.cs b/Signum.Utilities/Synchronization/ResetLazy.cs index f1bc6da2cf..3866047343 100644 --- a/Signum.Utilities/Synchronization/ResetLazy.cs +++ b/Signum.Utilities/Synchronization/ResetLazy.cs @@ -169,6 +169,6 @@ ResetLazyStats IResetLazy.Stats() }; } - public event EventHandler OnReset; + public event EventHandler? OnReset; } }